@morsehq-dev/sdk 0.4.1 → 0.5.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/dist/anthropic/index.cjs +12 -10
  2. package/dist/anthropic/index.js +5 -3
  3. package/dist/anthropic-agent-sdk/index.cjs +52 -34
  4. package/dist/anthropic-agent-sdk/index.cjs.map +1 -1
  5. package/dist/anthropic-agent-sdk/index.js +25 -7
  6. package/dist/anthropic-agent-sdk/index.js.map +1 -1
  7. package/dist/browser/anthropic/index.cjs +12 -10
  8. package/dist/browser/anthropic/index.js +5 -3
  9. package/dist/browser/anthropic-agent-sdk/index.cjs +52 -34
  10. package/dist/browser/anthropic-agent-sdk/index.cjs.map +1 -1
  11. package/dist/browser/anthropic-agent-sdk/index.js +25 -7
  12. package/dist/browser/anthropic-agent-sdk/index.js.map +1 -1
  13. package/dist/browser/{chunk-GWJYOQNC.js → chunk-3MTJGZGX.js} +10 -4
  14. package/dist/browser/chunk-3MTJGZGX.js.map +1 -0
  15. package/dist/browser/{chunk-EFUQVASI.cjs → chunk-63ZI6PGP.cjs} +17 -15
  16. package/dist/browser/chunk-63ZI6PGP.cjs.map +1 -0
  17. package/dist/browser/{chunk-DXWHT3HK.cjs → chunk-A5EYWAOT.cjs} +428 -63
  18. package/dist/browser/chunk-A5EYWAOT.cjs.map +1 -0
  19. package/dist/browser/{chunk-AYNX24P5.js → chunk-AM6LMQCT.js} +3 -3
  20. package/dist/browser/{chunk-AYNX24P5.js.map → chunk-AM6LMQCT.js.map} +1 -1
  21. package/dist/{chunk-SBGY5NS4.js → browser/chunk-FDE32B3R.js} +6 -4
  22. package/dist/browser/chunk-FDE32B3R.js.map +1 -0
  23. package/dist/browser/{chunk-DOLWR7LD.js → chunk-L6FWDEGJ.js} +4 -4
  24. package/dist/browser/{chunk-DOLWR7LD.js.map → chunk-L6FWDEGJ.js.map} +1 -1
  25. package/dist/browser/{chunk-QWRQJO57.js → chunk-MLDVXMQD.js} +3 -3
  26. package/dist/browser/{chunk-QWRQJO57.js.map → chunk-MLDVXMQD.js.map} +1 -1
  27. package/dist/{chunk-Y7SVGUKY.cjs → browser/chunk-N3PXJCOE.cjs} +7 -7
  28. package/dist/browser/{chunk-YNUZGKUA.cjs.map → chunk-N3PXJCOE.cjs.map} +1 -1
  29. package/dist/browser/chunk-NH54DAJP.js +118 -0
  30. package/dist/browser/chunk-NH54DAJP.js.map +1 -0
  31. package/dist/browser/chunk-NRYB5GJT.js +28 -0
  32. package/dist/browser/chunk-NRYB5GJT.js.map +1 -0
  33. package/dist/browser/{chunk-F3B4UR64.js → chunk-OOGAYEJF.js} +423 -61
  34. package/dist/browser/chunk-OOGAYEJF.js.map +1 -0
  35. package/dist/browser/{chunk-3643DC7K.cjs → chunk-RBNCTHK3.cjs} +5 -2
  36. package/dist/browser/{chunk-3643DC7K.cjs.map → chunk-RBNCTHK3.cjs.map} +1 -1
  37. package/dist/browser/chunk-SOJYLXCR.cjs +126 -0
  38. package/dist/browser/chunk-SOJYLXCR.cjs.map +1 -0
  39. package/dist/browser/{chunk-HGN7J3EU.cjs → chunk-T4NHSVXH.cjs} +12 -12
  40. package/dist/browser/{chunk-HGN7J3EU.cjs.map → chunk-T4NHSVXH.cjs.map} +1 -1
  41. package/dist/browser/chunk-YMEU6XQQ.cjs +31 -0
  42. package/dist/browser/chunk-YMEU6XQQ.cjs.map +1 -0
  43. package/dist/browser/{chunk-M2GZJ3RS.cjs → chunk-YR2FCEWM.cjs} +20 -14
  44. package/dist/browser/chunk-YR2FCEWM.cjs.map +1 -0
  45. package/dist/browser/index.cjs +112 -82
  46. package/dist/browser/index.cjs.map +1 -1
  47. package/dist/browser/index.js +40 -10
  48. package/dist/browser/index.js.map +1 -1
  49. package/dist/browser/integrations/pino.cjs +4 -4
  50. package/dist/browser/integrations/pino.js +3 -3
  51. package/dist/browser/langchain/index.cjs +19 -19
  52. package/dist/browser/langchain/index.js +3 -3
  53. package/dist/browser/langgraph/index.cjs +34 -26
  54. package/dist/browser/langgraph/index.cjs.map +1 -1
  55. package/dist/browser/langgraph/index.js +16 -8
  56. package/dist/browser/langgraph/index.js.map +1 -1
  57. package/dist/browser/openai/index.cjs +22 -8
  58. package/dist/browser/openai/index.cjs.map +1 -1
  59. package/dist/browser/openai/index.js +17 -3
  60. package/dist/browser/openai/index.js.map +1 -1
  61. package/dist/browser/openai-agents/index.cjs +42 -34
  62. package/dist/browser/openai-agents/index.cjs.map +1 -1
  63. package/dist/browser/openai-agents/index.js +13 -5
  64. package/dist/browser/openai-agents/index.js.map +1 -1
  65. package/dist/browser/vercel-ai/index.cjs +16 -16
  66. package/dist/browser/vercel-ai/index.js +4 -4
  67. package/dist/{chunk-LTKGLXAE.js → chunk-3IGQWLWE.js} +447 -76
  68. package/dist/chunk-3IGQWLWE.js.map +1 -0
  69. package/dist/{chunk-4R4SHGOK.js → chunk-4JPZV2VZ.js} +3 -3
  70. package/dist/{chunk-4R4SHGOK.js.map → chunk-4JPZV2VZ.js.map} +1 -1
  71. package/dist/chunk-6DZNK4VX.cjs +31 -0
  72. package/dist/chunk-6DZNK4VX.cjs.map +1 -0
  73. package/dist/{browser/chunk-F7BGQ26H.js → chunk-FCAPLB7A.js} +6 -4
  74. package/dist/chunk-FCAPLB7A.js.map +1 -0
  75. package/dist/{chunk-KJEO52QS.cjs → chunk-HICEJ4LV.cjs} +5 -2
  76. package/dist/{chunk-KJEO52QS.cjs.map → chunk-HICEJ4LV.cjs.map} +1 -1
  77. package/dist/chunk-S4WUABAU.js +28 -0
  78. package/dist/chunk-S4WUABAU.js.map +1 -0
  79. package/dist/{chunk-V5J6J4ZR.js → chunk-SHK2XEPB.js} +4 -4
  80. package/dist/{chunk-V5J6J4ZR.js.map → chunk-SHK2XEPB.js.map} +1 -1
  81. package/dist/{chunk-LQI63FHF.cjs → chunk-SNGYSP7Z.cjs} +20 -14
  82. package/dist/chunk-SNGYSP7Z.cjs.map +1 -0
  83. package/dist/chunk-VHF4GWJ4.cjs +126 -0
  84. package/dist/chunk-VHF4GWJ4.cjs.map +1 -0
  85. package/dist/{chunk-HNCWTENX.cjs → chunk-XCOZIFHC.cjs} +452 -78
  86. package/dist/chunk-XCOZIFHC.cjs.map +1 -0
  87. package/dist/chunk-XJUH6PR5.js +118 -0
  88. package/dist/chunk-XJUH6PR5.js.map +1 -0
  89. package/dist/{browser/chunk-YNUZGKUA.cjs → chunk-Y2QHMV6H.cjs} +7 -7
  90. package/dist/{chunk-Y7SVGUKY.cjs.map → chunk-Y2QHMV6H.cjs.map} +1 -1
  91. package/dist/{chunk-STK4KJQ6.js → chunk-YJYF4NSA.js} +10 -4
  92. package/dist/chunk-YJYF4NSA.js.map +1 -0
  93. package/dist/{chunk-5D6SBSEI.cjs → chunk-Z2IYSTRT.cjs} +17 -15
  94. package/dist/chunk-Z2IYSTRT.cjs.map +1 -0
  95. package/dist/{chunk-QXRJUPDP.cjs → chunk-ZIER4DGK.cjs} +12 -12
  96. package/dist/{chunk-QXRJUPDP.cjs.map → chunk-ZIER4DGK.cjs.map} +1 -1
  97. package/dist/{chunk-AEFUXEKV.js → chunk-ZWOSPXS4.js} +3 -3
  98. package/dist/{chunk-AEFUXEKV.js.map → chunk-ZWOSPXS4.js.map} +1 -1
  99. package/dist/index.cjs +119 -89
  100. package/dist/index.cjs.map +1 -1
  101. package/dist/index.d.cts +2 -2
  102. package/dist/index.d.ts +2 -2
  103. package/dist/index.js +41 -11
  104. package/dist/index.js.map +1 -1
  105. package/dist/integrations/pino.cjs +4 -4
  106. package/dist/integrations/pino.js +3 -3
  107. package/dist/langchain/index.cjs +19 -19
  108. package/dist/langchain/index.d.cts +1 -1
  109. package/dist/langchain/index.d.ts +1 -1
  110. package/dist/langchain/index.js +3 -3
  111. package/dist/langgraph/index.cjs +34 -26
  112. package/dist/langgraph/index.cjs.map +1 -1
  113. package/dist/langgraph/index.d.cts +1 -1
  114. package/dist/langgraph/index.d.ts +1 -1
  115. package/dist/langgraph/index.js +16 -8
  116. package/dist/langgraph/index.js.map +1 -1
  117. package/dist/openai/index.cjs +22 -8
  118. package/dist/openai/index.cjs.map +1 -1
  119. package/dist/openai/index.js +17 -3
  120. package/dist/openai/index.js.map +1 -1
  121. package/dist/openai-agents/index.cjs +42 -34
  122. package/dist/openai-agents/index.cjs.map +1 -1
  123. package/dist/openai-agents/index.js +13 -5
  124. package/dist/openai-agents/index.js.map +1 -1
  125. package/dist/{tracing-BYAqjT5Q.d.cts → tracing-CNlre8TK.d.cts} +1 -0
  126. package/dist/{tracing-rz9cWQ8d.d.ts → tracing-J8ZgxVzU.d.ts} +1 -0
  127. package/dist/vercel-ai/index.cjs +16 -16
  128. package/dist/vercel-ai/index.js +4 -4
  129. package/package.json +1 -9
  130. package/dist/browser/chunk-3BGG7GH3.cjs +0 -183
  131. package/dist/browser/chunk-3BGG7GH3.cjs.map +0 -1
  132. package/dist/browser/chunk-DXWHT3HK.cjs.map +0 -1
  133. package/dist/browser/chunk-EFUQVASI.cjs.map +0 -1
  134. package/dist/browser/chunk-F3B4UR64.js.map +0 -1
  135. package/dist/browser/chunk-F7BGQ26H.js.map +0 -1
  136. package/dist/browser/chunk-GWJYOQNC.js.map +0 -1
  137. package/dist/browser/chunk-M2GZJ3RS.cjs.map +0 -1
  138. package/dist/browser/chunk-YHV5GL32.js +0 -178
  139. package/dist/browser/chunk-YHV5GL32.js.map +0 -1
  140. package/dist/chunk-5D6SBSEI.cjs.map +0 -1
  141. package/dist/chunk-HNCWTENX.cjs.map +0 -1
  142. package/dist/chunk-LQI63FHF.cjs.map +0 -1
  143. package/dist/chunk-LTKGLXAE.js.map +0 -1
  144. package/dist/chunk-POCQNSVD.js +0 -178
  145. package/dist/chunk-POCQNSVD.js.map +0 -1
  146. package/dist/chunk-SBGY5NS4.js.map +0 -1
  147. package/dist/chunk-STK4KJQ6.js.map +0 -1
  148. package/dist/chunk-T2KW3P23.cjs +0 -183
  149. package/dist/chunk-T2KW3P23.cjs.map +0 -1
@@ -136,66 +136,6 @@ var init_env = __esm({
136
136
  }
137
137
  });
138
138
 
139
- // src/_internal/spans.ts
140
- function generateTraceId() {
141
- return randomHex(32);
142
- }
143
- function generateSpanId() {
144
- return randomHex(32);
145
- }
146
- function randomHex(chars) {
147
- const bytes = new Uint8Array(Math.ceil(chars / 2));
148
- const cryptoObj = globalThis.crypto;
149
- if (cryptoObj?.getRandomValues) {
150
- cryptoObj.getRandomValues(bytes);
151
- } else {
152
- for (let i = 0; i < bytes.length; i++) {
153
- bytes[i] = Math.floor(Math.random() * 256);
154
- }
155
- }
156
- let hex = "";
157
- for (const b of bytes) {
158
- hex += b.toString(16).padStart(2, "0");
159
- }
160
- return hex.slice(0, chars);
161
- }
162
- function nowIso() {
163
- return (/* @__PURE__ */ new Date()).toISOString();
164
- }
165
- function spanToWire(span) {
166
- const out = {};
167
- for (const [k, v] of Object.entries(span)) {
168
- if (v !== void 0 && v !== null) {
169
- out[k] = v;
170
- }
171
- }
172
- return out;
173
- }
174
- function buildTraceEntry(fields, spans) {
175
- return {
176
- trace: fields,
177
- spans: spans.map(spanToWire)
178
- };
179
- }
180
- exports.SpanType = void 0;
181
- var init_spans = __esm({
182
- "src/_internal/spans.ts"() {
183
- exports.SpanType = {
184
- AGENT: "agent",
185
- LLM: "llm",
186
- TOOL: "tool",
187
- HTTP: "http",
188
- DB: "db",
189
- CUSTOM: "custom",
190
- MEMORY: "memory",
191
- // MHQ-482: matches Python's `SpanType.RETRIEVER` (apps/sdk/python/src/morse_ai/spans.py).
192
- // @beta — retriever span type is subject to change before SDK v1.0 (see
193
- // the plain-LangChain adapter's on_retriever_* callbacks in src/langchain/).
194
- RETRIEVER: "retriever"
195
- };
196
- }
197
- });
198
-
199
139
  // src/_internal/redaction.ts
200
140
  function buildRedactionConfig(options) {
201
141
  const opts = options ?? {};
@@ -383,6 +323,390 @@ var init_redaction = __esm({
383
323
  MAX_DEPTH = 10;
384
324
  }
385
325
  });
326
+
327
+ // src/_internal/diagnostics.ts
328
+ function setRedactionConfig(config) {
329
+ activeRedactionConfig = config;
330
+ }
331
+ function setLevel(raw) {
332
+ if (!raw) return;
333
+ const value = String(raw).trim().toLowerCase();
334
+ if (!VALID_LEVELS.has(value)) return;
335
+ level = value;
336
+ }
337
+ function transmissionAllowed() {
338
+ if (isTelemetryDisabled() || isDisabled()) return false;
339
+ return level !== LEVEL_OFF;
340
+ }
341
+ function checkBucket(buckets, key, limit, windowMs) {
342
+ const now = Date.now();
343
+ const bucket = buckets.get(key) ?? [];
344
+ const cutoff = now - windowMs;
345
+ while (bucket.length > 0 && bucket[0] < cutoff) bucket.shift();
346
+ if (bucket.length >= limit) {
347
+ buckets.set(key, bucket);
348
+ return false;
349
+ }
350
+ bucket.push(now);
351
+ buckets.set(key, bucket);
352
+ return true;
353
+ }
354
+ function checkRateLimit(fingerprint) {
355
+ const limit = level === LEVEL_DEBUG ? RATE_LIMIT_PER_WINDOW_DEBUG : RATE_LIMIT_PER_WINDOW;
356
+ return checkBucket(rateBuckets, fingerprint, limit, RATE_WINDOW_MS);
357
+ }
358
+ function isMorseFrame(line) {
359
+ return MORSE_PATH_MARKERS.some((marker) => line.includes(marker));
360
+ }
361
+ function parseFrame(line) {
362
+ const withParens = /^\s*at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)\s*$/.exec(line);
363
+ if (withParens) {
364
+ return {
365
+ fn: withParens[1],
366
+ file: withParens[2],
367
+ lineNo: Number(withParens[3])
368
+ };
369
+ }
370
+ const bare = /^\s*at\s+(.+?):(\d+):(\d+)\s*$/.exec(line);
371
+ if (bare) return { file: bare[1], lineNo: Number(bare[2]) };
372
+ return {};
373
+ }
374
+ function buildScopedStack(error) {
375
+ const frames = [];
376
+ try {
377
+ const stack = error instanceof Error ? error.stack ?? "" : "";
378
+ if (!stack) return frames;
379
+ let elided = 0;
380
+ for (const raw of stack.split("\n")) {
381
+ if (!raw.trim().startsWith("at ")) continue;
382
+ if (isMorseFrame(raw)) {
383
+ if (elided > 0) {
384
+ frames.push({ elided });
385
+ elided = 0;
386
+ }
387
+ const { file, lineNo, fn } = parseFrame(raw);
388
+ const frame = {};
389
+ if (file) frame.file = file.split(/[\\/]/).slice(-3).join("/");
390
+ if (typeof lineNo === "number" && !Number.isNaN(lineNo)) frame.line = lineNo;
391
+ if (fn) frame.function = fn.slice(0, 255);
392
+ frames.push(frame);
393
+ } else {
394
+ elided += 1;
395
+ }
396
+ }
397
+ if (elided > 0) frames.push({ elided });
398
+ } catch {
399
+ }
400
+ return frames.length > MAX_STACK_ENTRIES ? frames.slice(-MAX_STACK_ENTRIES) : frames;
401
+ }
402
+ function redactedMessage(error) {
403
+ let raw;
404
+ try {
405
+ raw = error instanceof Error ? error.message : String(error);
406
+ } catch {
407
+ return "";
408
+ }
409
+ try {
410
+ if (activeRedactionConfig) {
411
+ const out = redactValue(raw, activeRedactionConfig);
412
+ raw = typeof out === "string" ? out : String(out);
413
+ }
414
+ } catch {
415
+ return "<redaction unavailable>";
416
+ }
417
+ return raw.slice(0, MAX_MESSAGE_CHARS);
418
+ }
419
+ function scrubExtra(extra) {
420
+ const out = {};
421
+ if (!extra) return out;
422
+ for (const [key, value] of Object.entries(extra)) {
423
+ if (ALLOWED_EXTRA_KEYS.has(key) && value != null) {
424
+ out[key] = String(value).slice(0, 255);
425
+ }
426
+ }
427
+ return out;
428
+ }
429
+ function recordDrop(reason, category, quantity = 1) {
430
+ try {
431
+ if (quantity <= 0) return;
432
+ const key = `${reason}:${category}`;
433
+ const existing = counters.get(key);
434
+ if (existing) existing.quantity += quantity;
435
+ else counters.set(key, { reason, category, quantity });
436
+ if (checkBucket(localLogBuckets, `drop:${key}`, LOCAL_LOG_LIMIT_PER_WINDOW, LOCAL_LOG_WINDOW_MS)) {
437
+ console.warn(`morse: dropped ${quantity} ${category} (${reason}) \u2014 telemetry is being lost`);
438
+ }
439
+ } catch {
440
+ }
441
+ }
442
+ function drainCounters() {
443
+ if (counters.size === 0) return [];
444
+ const drained = [...counters.values()];
445
+ counters.clear();
446
+ return drained;
447
+ }
448
+ function report(error, options) {
449
+ if (reporting) return;
450
+ reporting = true;
451
+ try {
452
+ const errClass = error instanceof Error ? error.name : "Error";
453
+ const errMessage = error instanceof Error ? error.message : String(error);
454
+ if (checkBucket(
455
+ localLogBuckets,
456
+ options.fingerprint,
457
+ LOCAL_LOG_LIMIT_PER_WINDOW,
458
+ LOCAL_LOG_WINDOW_MS
459
+ )) {
460
+ const line = `morse internal error [${options.fingerprint}]: ${errClass}: ${errMessage}`;
461
+ if (isDebug()) console.error(line, error);
462
+ else console.warn(line);
463
+ }
464
+ if (!transmissionAllowed()) return;
465
+ if (!checkRateLimit(options.fingerprint)) return;
466
+ enqueue({
467
+ kind: "error",
468
+ fingerprint: options.fingerprint.slice(0, 255),
469
+ error_type: errClass.slice(0, 255),
470
+ message: redactedMessage(error),
471
+ stack: buildScopedStack(error),
472
+ sdk_language: "typescript",
473
+ sdk_version: sdkVersion(),
474
+ runtime_version: runtimeVersion(),
475
+ platform: platformLabel(),
476
+ extra: scrubExtra(options.extra)
477
+ });
478
+ } catch {
479
+ } finally {
480
+ reporting = false;
481
+ }
482
+ }
483
+ function sdkVersion() {
484
+ return SDK_VERSION;
485
+ }
486
+ function runtimeVersion() {
487
+ try {
488
+ const proc = globalThis.process;
489
+ return proc?.version ? String(proc.version) : "";
490
+ } catch {
491
+ return "";
492
+ }
493
+ }
494
+ function platformLabel() {
495
+ try {
496
+ const proc = globalThis.process;
497
+ if (proc?.platform) return `${proc.platform}-${proc.arch ?? ""}`.slice(0, 128);
498
+ return "browser";
499
+ } catch {
500
+ return "";
501
+ }
502
+ }
503
+ function enqueue(event) {
504
+ pending.push(event);
505
+ while (pending.length > MAX_PENDING) pending.shift();
506
+ ensureTimer();
507
+ }
508
+ function ensureTimer() {
509
+ if (timer !== null) return;
510
+ try {
511
+ timer = setInterval(() => {
512
+ void flushOnce();
513
+ }, FLUSH_INTERVAL_MS);
514
+ timer?.unref?.();
515
+ } catch {
516
+ timer = null;
517
+ }
518
+ }
519
+ function breakerBlocks() {
520
+ return breakerOpenUntil > 0 && Date.now() < breakerOpenUntil;
521
+ }
522
+ function recordResult(ok) {
523
+ if (ok) {
524
+ consecutiveFailures = 0;
525
+ breakerOpenUntil = 0;
526
+ return;
527
+ }
528
+ consecutiveFailures += 1;
529
+ if (consecutiveFailures >= BREAKER_THRESHOLD) {
530
+ breakerOpenUntil = Date.now() + BREAKER_COOLDOWN_MS;
531
+ }
532
+ }
533
+ async function flushOnce() {
534
+ try {
535
+ const batch = pending.splice(0, MAX_BATCH_EVENTS);
536
+ const drained = drainCounters();
537
+ if (drained.length > 0) {
538
+ batch.push({
539
+ kind: "counters",
540
+ fingerprint: "morse.transport.delivery",
541
+ counters: drained,
542
+ sdk_language: "typescript",
543
+ sdk_version: sdkVersion()
544
+ });
545
+ }
546
+ if (batch.length === 0) return;
547
+ if (breakerBlocks() || !transmissionAllowed()) return;
548
+ const target = resolveTarget();
549
+ if (target === null) return;
550
+ let response;
551
+ try {
552
+ response = await fetch(target.url, {
553
+ method: "POST",
554
+ headers: {
555
+ Authorization: `Bearer ${target.apiKey}`,
556
+ "Content-Type": "application/json"
557
+ },
558
+ body: JSON.stringify({ events: batch })
559
+ });
560
+ } catch {
561
+ recordResult(false);
562
+ return;
563
+ }
564
+ setLevel(response.headers.get("X-Morse-Diagnostics"));
565
+ recordResult(response.ok);
566
+ } catch {
567
+ }
568
+ }
569
+ function resolveTarget() {
570
+ try {
571
+ const apiKey = getApiKey();
572
+ if (!apiKey) return null;
573
+ const url = deriveDiagnosticsUrl(String(getEndpoint() ?? ""));
574
+ if (!url) return null;
575
+ return { apiKey: String(apiKey), url };
576
+ } catch {
577
+ return null;
578
+ }
579
+ }
580
+ function deriveDiagnosticsUrl(tracesEndpoint) {
581
+ try {
582
+ const parsed = new URL(tracesEndpoint);
583
+ return `${parsed.protocol}//${parsed.host}${DIAGNOSTICS_PATH}`;
584
+ } catch {
585
+ return null;
586
+ }
587
+ }
588
+ function _resetForTesting() {
589
+ rateBuckets.clear();
590
+ localLogBuckets.clear();
591
+ counters.clear();
592
+ pending = [];
593
+ if (timer !== null) {
594
+ clearInterval(timer);
595
+ timer = null;
596
+ }
597
+ consecutiveFailures = 0;
598
+ breakerOpenUntil = 0;
599
+ reporting = false;
600
+ level = LEVEL_ERROR;
601
+ activeRedactionConfig = null;
602
+ }
603
+ var SDK_VERSION, LEVEL_OFF, LEVEL_ERROR, LEVEL_DEBUG, VALID_LEVELS, level, RATE_WINDOW_MS, RATE_LIMIT_PER_WINDOW, RATE_LIMIT_PER_WINDOW_DEBUG, rateBuckets, LOCAL_LOG_WINDOW_MS, LOCAL_LOG_LIMIT_PER_WINDOW, localLogBuckets, MAX_STACK_ENTRIES, MAX_MESSAGE_CHARS, MAX_BATCH_EVENTS, ALLOWED_EXTRA_KEYS, DIAGNOSTICS_PATH, MAX_PENDING, FLUSH_INTERVAL_MS, BREAKER_THRESHOLD, BREAKER_COOLDOWN_MS; exports.REASON_QUEUE_FULL = void 0; exports.REASON_RETRY_EXHAUSTED = void 0; exports.REASON_QUOTA_REJECTED = void 0; exports.REASON_SHUTDOWN_DROP = void 0; var counters, activeRedactionConfig, pending, timer, consecutiveFailures, breakerOpenUntil, reporting, MORSE_PATH_MARKERS;
604
+ var init_diagnostics = __esm({
605
+ "src/_internal/diagnostics.ts"() {
606
+ init_env();
607
+ init_redaction();
608
+ SDK_VERSION = "0.5.0-rc.2" ;
609
+ LEVEL_OFF = "off";
610
+ LEVEL_ERROR = "error";
611
+ LEVEL_DEBUG = "debug";
612
+ VALID_LEVELS = /* @__PURE__ */ new Set([LEVEL_OFF, LEVEL_ERROR, LEVEL_DEBUG]);
613
+ level = LEVEL_ERROR;
614
+ RATE_WINDOW_MS = 6e4;
615
+ RATE_LIMIT_PER_WINDOW = 100;
616
+ RATE_LIMIT_PER_WINDOW_DEBUG = 1e3;
617
+ rateBuckets = /* @__PURE__ */ new Map();
618
+ LOCAL_LOG_WINDOW_MS = 6e4;
619
+ LOCAL_LOG_LIMIT_PER_WINDOW = 10;
620
+ localLogBuckets = /* @__PURE__ */ new Map();
621
+ MAX_STACK_ENTRIES = 64;
622
+ MAX_MESSAGE_CHARS = 4096;
623
+ MAX_BATCH_EVENTS = 32;
624
+ ALLOWED_EXTRA_KEYS = /* @__PURE__ */ new Set([
625
+ "adapter",
626
+ "module",
627
+ "function",
628
+ "operation",
629
+ "endpoint_host"
630
+ ]);
631
+ DIAGNOSTICS_PATH = "/api/v1/diagnostics/sdk";
632
+ MAX_PENDING = 100;
633
+ FLUSH_INTERVAL_MS = 5e3;
634
+ BREAKER_THRESHOLD = 3;
635
+ BREAKER_COOLDOWN_MS = 3e5;
636
+ exports.REASON_QUEUE_FULL = "queue_full";
637
+ exports.REASON_RETRY_EXHAUSTED = "retry_exhausted";
638
+ exports.REASON_QUOTA_REJECTED = "quota_rejected";
639
+ exports.REASON_SHUTDOWN_DROP = "shutdown_drop";
640
+ counters = /* @__PURE__ */ new Map();
641
+ activeRedactionConfig = null;
642
+ pending = [];
643
+ timer = null;
644
+ consecutiveFailures = 0;
645
+ breakerOpenUntil = 0;
646
+ reporting = false;
647
+ MORSE_PATH_MARKERS = ["@morsehq/sdk", "morse-sdk", "/morse/", "morse_ai"];
648
+ }
649
+ });
650
+
651
+ // src/_internal/spans.ts
652
+ function generateTraceId() {
653
+ return randomHex(32);
654
+ }
655
+ function generateSpanId() {
656
+ return randomHex(32);
657
+ }
658
+ function randomHex(chars) {
659
+ const bytes = new Uint8Array(Math.ceil(chars / 2));
660
+ const cryptoObj = globalThis.crypto;
661
+ if (cryptoObj?.getRandomValues) {
662
+ cryptoObj.getRandomValues(bytes);
663
+ } else {
664
+ for (let i = 0; i < bytes.length; i++) {
665
+ bytes[i] = Math.floor(Math.random() * 256);
666
+ }
667
+ }
668
+ let hex = "";
669
+ for (const b of bytes) {
670
+ hex += b.toString(16).padStart(2, "0");
671
+ }
672
+ return hex.slice(0, chars);
673
+ }
674
+ function nowIso() {
675
+ return (/* @__PURE__ */ new Date()).toISOString();
676
+ }
677
+ function spanToWire(span) {
678
+ const out = {};
679
+ for (const [k, v] of Object.entries(span)) {
680
+ if (v !== void 0 && v !== null) {
681
+ out[k] = v;
682
+ }
683
+ }
684
+ return out;
685
+ }
686
+ function buildTraceEntry(fields, spans) {
687
+ return {
688
+ trace: fields,
689
+ spans: spans.map(spanToWire)
690
+ };
691
+ }
692
+ exports.SpanType = void 0;
693
+ var init_spans = __esm({
694
+ "src/_internal/spans.ts"() {
695
+ exports.SpanType = {
696
+ AGENT: "agent",
697
+ LLM: "llm",
698
+ TOOL: "tool",
699
+ HTTP: "http",
700
+ DB: "db",
701
+ CUSTOM: "custom",
702
+ MEMORY: "memory",
703
+ // MHQ-482: matches Python's `SpanType.RETRIEVER` (apps/sdk/python/src/morse_ai/spans.py).
704
+ // @beta — retriever span type is subject to change before SDK v1.0 (see
705
+ // the plain-LangChain adapter's on_retriever_* callbacks in src/langchain/).
706
+ RETRIEVER: "retriever"
707
+ };
708
+ }
709
+ });
386
710
  function ensureGlobalContextManager() {
387
711
  if (contextManagerRegistered) return;
388
712
  contextManagerRegistered = true;
@@ -606,13 +930,21 @@ function emitTraceEntry(entry) {
606
930
  });
607
931
  }
608
932
  otelSpan.end(endTime);
609
- } catch {
933
+ } catch (err) {
934
+ reportSwallowed(err, "morse.otel_provider.shutdown");
610
935
  }
611
936
  }
612
937
  }
938
+ function reportSwallowed(err, fingerprint) {
939
+ try {
940
+ report(err, { fingerprint });
941
+ } catch {
942
+ }
943
+ }
613
944
  var INSTRUMENTATION_NAME, DEFAULT_MAX_FIELD_BYTES, TRUNCATION_MARKER, contextManagerRegistered, MAX_U64, RedactingSpanExporter, RecordingSpanExporter, ResultCapturingExporter, OtelEngine, engine;
614
945
  var init_otel_provider = __esm({
615
946
  "src/_internal/otel-provider.ts"() {
947
+ init_diagnostics();
616
948
  init_redaction();
617
949
  INSTRUMENTATION_NAME = "morse-typescript";
618
950
  DEFAULT_MAX_FIELD_BYTES = 65536;
@@ -765,7 +1097,8 @@ var init_otel_provider = __esm({
765
1097
  if (provider !== null) {
766
1098
  try {
767
1099
  await provider.forceFlush();
768
- } catch {
1100
+ } catch (err) {
1101
+ reportSwallowed(err, "morse.otel_provider.force_flush");
769
1102
  }
770
1103
  }
771
1104
  }
@@ -812,6 +1145,17 @@ function tryLoadAls() {
812
1145
  als = null;
813
1146
  return als;
814
1147
  }
1148
+ try {
1149
+ const getBuiltin = process?.getBuiltinModule;
1150
+ if (typeof getBuiltin === "function") {
1151
+ const mod = getBuiltin("node:async_hooks");
1152
+ if (mod?.AsyncLocalStorage) {
1153
+ als = new mod.AsyncLocalStorage();
1154
+ return als;
1155
+ }
1156
+ }
1157
+ } catch {
1158
+ }
815
1159
  try {
816
1160
  const dynamicRequire = Function("m", "return require(m)");
817
1161
  const mod = dynamicRequire("node:async_hooks");
@@ -844,8 +1188,9 @@ function setTransport(t) {
844
1188
  function getTransport() {
845
1189
  return transport;
846
1190
  }
847
- function setRedactionConfig(config) {
1191
+ function setRedactionConfig2(config) {
848
1192
  redactionConfig = config;
1193
+ setRedactionConfig(config);
849
1194
  }
850
1195
  function getRedactionConfig() {
851
1196
  return redactionConfig;
@@ -934,8 +1279,15 @@ function buildTraceDict(state, rootSpan) {
934
1279
  spans: spans.map((s) => redactSpanDict(s, config))
935
1280
  };
936
1281
  const effectiveSource = state.sourceOverride || _source;
1282
+ const resource = {};
937
1283
  if (effectiveSource) {
938
- out.resource = { "morse_ai.source": effectiveSource };
1284
+ resource["morse_ai.source"] = effectiveSource;
1285
+ }
1286
+ if (state.framework) {
1287
+ resource["morse_ai.framework"] = state.framework;
1288
+ }
1289
+ if (Object.keys(resource).length > 0) {
1290
+ out.resource = resource;
939
1291
  }
940
1292
  return out;
941
1293
  }
@@ -1031,16 +1383,37 @@ function errToString(e) {
1031
1383
  if (e instanceof Error) return e.message;
1032
1384
  return String(e);
1033
1385
  }
1386
+ function isThenable(v) {
1387
+ return v !== null && (typeof v === "object" || typeof v === "function") && typeof v.then === "function";
1388
+ }
1034
1389
  function runSync(opts, fn) {
1035
1390
  const { state, rootSpan, startMono } = startTrace(opts);
1036
1391
  const handle = buildRunHandle(state);
1037
1392
  const store = tryLoadAls();
1038
1393
  const runFn = () => withDbCaptureContext(state.traceId, rootSpan.span_id, () => fn(handle));
1039
- if (store) {
1040
- try {
1041
- const result = store.run(state, runFn);
1394
+ const settle = (result, onDone) => {
1395
+ if (!isThenable(result)) {
1042
1396
  endTrace(state, rootSpan, startMono, void 0);
1397
+ onDone();
1043
1398
  return result;
1399
+ }
1400
+ return result.then(
1401
+ (value) => {
1402
+ endTrace(state, rootSpan, startMono, void 0);
1403
+ onDone();
1404
+ return value;
1405
+ },
1406
+ (err) => {
1407
+ endTrace(state, rootSpan, startMono, err);
1408
+ onDone();
1409
+ throw err;
1410
+ }
1411
+ );
1412
+ };
1413
+ if (store) {
1414
+ try {
1415
+ return settle(store.run(state, runFn), () => {
1416
+ });
1044
1417
  } catch (err) {
1045
1418
  endTrace(state, rootSpan, startMono, err);
1046
1419
  throw err;
@@ -1048,14 +1421,11 @@ function runSync(opts, fn) {
1048
1421
  } else {
1049
1422
  const reset = setActiveTraceState(state);
1050
1423
  try {
1051
- const result = runFn();
1052
- endTrace(state, rootSpan, startMono, void 0);
1053
- return result;
1424
+ return settle(runFn(), reset);
1054
1425
  } catch (err) {
1055
1426
  endTrace(state, rootSpan, startMono, err);
1056
- throw err;
1057
- } finally {
1058
1427
  reset();
1428
+ throw err;
1059
1429
  }
1060
1430
  }
1061
1431
  }
@@ -1156,7 +1526,7 @@ async function spanAsync(opts, fn) {
1156
1526
  throw err;
1157
1527
  }
1158
1528
  }
1159
- function _resetForTesting() {
1529
+ function _resetForTesting2() {
1160
1530
  browserState = null;
1161
1531
  lastTrace = null;
1162
1532
  redactionConfig = buildRedactionConfig();
@@ -1166,6 +1536,7 @@ var init_tracing = __esm({
1166
1536
  "src/_internal/tracing.ts"() {
1167
1537
  init_env();
1168
1538
  init_otel_provider();
1539
+ init_diagnostics();
1169
1540
  init_redaction();
1170
1541
  init_spans();
1171
1542
  als = null;
@@ -1284,6 +1655,7 @@ var init_propagation = __esm({
1284
1655
  });
1285
1656
 
1286
1657
  exports._resetForTesting = _resetForTesting;
1658
+ exports._resetForTesting2 = _resetForTesting2;
1287
1659
  exports.buildRedactionConfig = buildRedactionConfig;
1288
1660
  exports.buildTraceEntry = buildTraceEntry;
1289
1661
  exports.extractTraceparent = extractTraceparent;
@@ -1303,6 +1675,7 @@ exports.getMaxQueueSize = getMaxQueueSize;
1303
1675
  exports.getRedactionConfig = getRedactionConfig;
1304
1676
  exports.getSampleRate = getSampleRate;
1305
1677
  exports.getTransport = getTransport;
1678
+ exports.init_diagnostics = init_diagnostics;
1306
1679
  exports.init_env = init_env;
1307
1680
  exports.init_otel_provider = init_otel_provider;
1308
1681
  exports.init_propagation = init_propagation;
@@ -1313,21 +1686,22 @@ exports.injectIntoRequestInit = injectIntoRequestInit;
1313
1686
  exports.injectTraceparent = injectTraceparent;
1314
1687
  exports.isAutoDetectDisabled = isAutoDetectDisabled;
1315
1688
  exports.isDbCaptureEnabled = isDbCaptureEnabled;
1316
- exports.isDebug = isDebug;
1317
1689
  exports.isDisabled = isDisabled;
1318
- exports.isTelemetryDisabled = isTelemetryDisabled;
1319
1690
  exports.isValidInternalSource = isValidInternalSource;
1320
1691
  exports.nowIso = nowIso;
1692
+ exports.recordDrop = recordDrop;
1321
1693
  exports.redactValue = redactValue;
1694
+ exports.report = report;
1322
1695
  exports.runAsync = runAsync;
1323
1696
  exports.runSync = runSync;
1324
1697
  exports.sendTrace = sendTrace;
1325
1698
  exports.setContext = setContext;
1326
- exports.setRedactionConfig = setRedactionConfig;
1699
+ exports.setLevel = setLevel;
1700
+ exports.setRedactionConfig = setRedactionConfig2;
1327
1701
  exports.setSource = setSource;
1328
1702
  exports.setTransport = setTransport;
1329
1703
  exports.spanAsync = spanAsync;
1330
1704
  exports.spanSync = spanSync;
1331
1705
  exports.startSpan = startSpan;
1332
- //# sourceMappingURL=chunk-HNCWTENX.cjs.map
1333
- //# sourceMappingURL=chunk-HNCWTENX.cjs.map
1706
+ //# sourceMappingURL=chunk-XCOZIFHC.cjs.map
1707
+ //# sourceMappingURL=chunk-XCOZIFHC.cjs.map