@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
@@ -134,66 +134,6 @@ var init_env = __esm({
134
134
  }
135
135
  });
136
136
 
137
- // src/_internal/spans.ts
138
- function generateTraceId() {
139
- return randomHex(32);
140
- }
141
- function generateSpanId() {
142
- return randomHex(32);
143
- }
144
- function randomHex(chars) {
145
- const bytes = new Uint8Array(Math.ceil(chars / 2));
146
- const cryptoObj = globalThis.crypto;
147
- if (cryptoObj?.getRandomValues) {
148
- cryptoObj.getRandomValues(bytes);
149
- } else {
150
- for (let i = 0; i < bytes.length; i++) {
151
- bytes[i] = Math.floor(Math.random() * 256);
152
- }
153
- }
154
- let hex = "";
155
- for (const b of bytes) {
156
- hex += b.toString(16).padStart(2, "0");
157
- }
158
- return hex.slice(0, chars);
159
- }
160
- function nowIso() {
161
- return (/* @__PURE__ */ new Date()).toISOString();
162
- }
163
- function spanToWire(span) {
164
- const out = {};
165
- for (const [k, v] of Object.entries(span)) {
166
- if (v !== void 0 && v !== null) {
167
- out[k] = v;
168
- }
169
- }
170
- return out;
171
- }
172
- function buildTraceEntry(fields, spans) {
173
- return {
174
- trace: fields,
175
- spans: spans.map(spanToWire)
176
- };
177
- }
178
- var SpanType;
179
- var init_spans = __esm({
180
- "src/_internal/spans.ts"() {
181
- SpanType = {
182
- AGENT: "agent",
183
- LLM: "llm",
184
- TOOL: "tool",
185
- HTTP: "http",
186
- DB: "db",
187
- CUSTOM: "custom",
188
- MEMORY: "memory",
189
- // MHQ-482: matches Python's `SpanType.RETRIEVER` (apps/sdk/python/src/morse_ai/spans.py).
190
- // @beta — retriever span type is subject to change before SDK v1.0 (see
191
- // the plain-LangChain adapter's on_retriever_* callbacks in src/langchain/).
192
- RETRIEVER: "retriever"
193
- };
194
- }
195
- });
196
-
197
137
  // src/_internal/redaction.ts
198
138
  function buildRedactionConfig(options) {
199
139
  const opts = options ?? {};
@@ -381,6 +321,390 @@ var init_redaction = __esm({
381
321
  MAX_DEPTH = 10;
382
322
  }
383
323
  });
324
+
325
+ // src/_internal/diagnostics.ts
326
+ function setRedactionConfig(config) {
327
+ activeRedactionConfig = config;
328
+ }
329
+ function setLevel(raw) {
330
+ if (!raw) return;
331
+ const value = String(raw).trim().toLowerCase();
332
+ if (!VALID_LEVELS.has(value)) return;
333
+ level = value;
334
+ }
335
+ function transmissionAllowed() {
336
+ if (isTelemetryDisabled() || isDisabled()) return false;
337
+ return level !== LEVEL_OFF;
338
+ }
339
+ function checkBucket(buckets, key, limit, windowMs) {
340
+ const now = Date.now();
341
+ const bucket = buckets.get(key) ?? [];
342
+ const cutoff = now - windowMs;
343
+ while (bucket.length > 0 && bucket[0] < cutoff) bucket.shift();
344
+ if (bucket.length >= limit) {
345
+ buckets.set(key, bucket);
346
+ return false;
347
+ }
348
+ bucket.push(now);
349
+ buckets.set(key, bucket);
350
+ return true;
351
+ }
352
+ function checkRateLimit(fingerprint) {
353
+ const limit = level === LEVEL_DEBUG ? RATE_LIMIT_PER_WINDOW_DEBUG : RATE_LIMIT_PER_WINDOW;
354
+ return checkBucket(rateBuckets, fingerprint, limit, RATE_WINDOW_MS);
355
+ }
356
+ function isMorseFrame(line) {
357
+ return MORSE_PATH_MARKERS.some((marker) => line.includes(marker));
358
+ }
359
+ function parseFrame(line) {
360
+ const withParens = /^\s*at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)\s*$/.exec(line);
361
+ if (withParens) {
362
+ return {
363
+ fn: withParens[1],
364
+ file: withParens[2],
365
+ lineNo: Number(withParens[3])
366
+ };
367
+ }
368
+ const bare = /^\s*at\s+(.+?):(\d+):(\d+)\s*$/.exec(line);
369
+ if (bare) return { file: bare[1], lineNo: Number(bare[2]) };
370
+ return {};
371
+ }
372
+ function buildScopedStack(error) {
373
+ const frames = [];
374
+ try {
375
+ const stack = error instanceof Error ? error.stack ?? "" : "";
376
+ if (!stack) return frames;
377
+ let elided = 0;
378
+ for (const raw of stack.split("\n")) {
379
+ if (!raw.trim().startsWith("at ")) continue;
380
+ if (isMorseFrame(raw)) {
381
+ if (elided > 0) {
382
+ frames.push({ elided });
383
+ elided = 0;
384
+ }
385
+ const { file, lineNo, fn } = parseFrame(raw);
386
+ const frame = {};
387
+ if (file) frame.file = file.split(/[\\/]/).slice(-3).join("/");
388
+ if (typeof lineNo === "number" && !Number.isNaN(lineNo)) frame.line = lineNo;
389
+ if (fn) frame.function = fn.slice(0, 255);
390
+ frames.push(frame);
391
+ } else {
392
+ elided += 1;
393
+ }
394
+ }
395
+ if (elided > 0) frames.push({ elided });
396
+ } catch {
397
+ }
398
+ return frames.length > MAX_STACK_ENTRIES ? frames.slice(-MAX_STACK_ENTRIES) : frames;
399
+ }
400
+ function redactedMessage(error) {
401
+ let raw;
402
+ try {
403
+ raw = error instanceof Error ? error.message : String(error);
404
+ } catch {
405
+ return "";
406
+ }
407
+ try {
408
+ if (activeRedactionConfig) {
409
+ const out = redactValue(raw, activeRedactionConfig);
410
+ raw = typeof out === "string" ? out : String(out);
411
+ }
412
+ } catch {
413
+ return "<redaction unavailable>";
414
+ }
415
+ return raw.slice(0, MAX_MESSAGE_CHARS);
416
+ }
417
+ function scrubExtra(extra) {
418
+ const out = {};
419
+ if (!extra) return out;
420
+ for (const [key, value] of Object.entries(extra)) {
421
+ if (ALLOWED_EXTRA_KEYS.has(key) && value != null) {
422
+ out[key] = String(value).slice(0, 255);
423
+ }
424
+ }
425
+ return out;
426
+ }
427
+ function recordDrop(reason, category, quantity = 1) {
428
+ try {
429
+ if (quantity <= 0) return;
430
+ const key = `${reason}:${category}`;
431
+ const existing = counters.get(key);
432
+ if (existing) existing.quantity += quantity;
433
+ else counters.set(key, { reason, category, quantity });
434
+ if (checkBucket(localLogBuckets, `drop:${key}`, LOCAL_LOG_LIMIT_PER_WINDOW, LOCAL_LOG_WINDOW_MS)) {
435
+ console.warn(`morse: dropped ${quantity} ${category} (${reason}) \u2014 telemetry is being lost`);
436
+ }
437
+ } catch {
438
+ }
439
+ }
440
+ function drainCounters() {
441
+ if (counters.size === 0) return [];
442
+ const drained = [...counters.values()];
443
+ counters.clear();
444
+ return drained;
445
+ }
446
+ function report(error, options) {
447
+ if (reporting) return;
448
+ reporting = true;
449
+ try {
450
+ const errClass = error instanceof Error ? error.name : "Error";
451
+ const errMessage = error instanceof Error ? error.message : String(error);
452
+ if (checkBucket(
453
+ localLogBuckets,
454
+ options.fingerprint,
455
+ LOCAL_LOG_LIMIT_PER_WINDOW,
456
+ LOCAL_LOG_WINDOW_MS
457
+ )) {
458
+ const line = `morse internal error [${options.fingerprint}]: ${errClass}: ${errMessage}`;
459
+ if (isDebug()) console.error(line, error);
460
+ else console.warn(line);
461
+ }
462
+ if (!transmissionAllowed()) return;
463
+ if (!checkRateLimit(options.fingerprint)) return;
464
+ enqueue({
465
+ kind: "error",
466
+ fingerprint: options.fingerprint.slice(0, 255),
467
+ error_type: errClass.slice(0, 255),
468
+ message: redactedMessage(error),
469
+ stack: buildScopedStack(error),
470
+ sdk_language: "typescript",
471
+ sdk_version: sdkVersion(),
472
+ runtime_version: runtimeVersion(),
473
+ platform: platformLabel(),
474
+ extra: scrubExtra(options.extra)
475
+ });
476
+ } catch {
477
+ } finally {
478
+ reporting = false;
479
+ }
480
+ }
481
+ function sdkVersion() {
482
+ return SDK_VERSION;
483
+ }
484
+ function runtimeVersion() {
485
+ try {
486
+ const proc = globalThis.process;
487
+ return proc?.version ? String(proc.version) : "";
488
+ } catch {
489
+ return "";
490
+ }
491
+ }
492
+ function platformLabel() {
493
+ try {
494
+ const proc = globalThis.process;
495
+ if (proc?.platform) return `${proc.platform}-${proc.arch ?? ""}`.slice(0, 128);
496
+ return "browser";
497
+ } catch {
498
+ return "";
499
+ }
500
+ }
501
+ function enqueue(event) {
502
+ pending.push(event);
503
+ while (pending.length > MAX_PENDING) pending.shift();
504
+ ensureTimer();
505
+ }
506
+ function ensureTimer() {
507
+ if (timer !== null) return;
508
+ try {
509
+ timer = setInterval(() => {
510
+ void flushOnce();
511
+ }, FLUSH_INTERVAL_MS);
512
+ timer?.unref?.();
513
+ } catch {
514
+ timer = null;
515
+ }
516
+ }
517
+ function breakerBlocks() {
518
+ return breakerOpenUntil > 0 && Date.now() < breakerOpenUntil;
519
+ }
520
+ function recordResult(ok) {
521
+ if (ok) {
522
+ consecutiveFailures = 0;
523
+ breakerOpenUntil = 0;
524
+ return;
525
+ }
526
+ consecutiveFailures += 1;
527
+ if (consecutiveFailures >= BREAKER_THRESHOLD) {
528
+ breakerOpenUntil = Date.now() + BREAKER_COOLDOWN_MS;
529
+ }
530
+ }
531
+ async function flushOnce() {
532
+ try {
533
+ const batch = pending.splice(0, MAX_BATCH_EVENTS);
534
+ const drained = drainCounters();
535
+ if (drained.length > 0) {
536
+ batch.push({
537
+ kind: "counters",
538
+ fingerprint: "morse.transport.delivery",
539
+ counters: drained,
540
+ sdk_language: "typescript",
541
+ sdk_version: sdkVersion()
542
+ });
543
+ }
544
+ if (batch.length === 0) return;
545
+ if (breakerBlocks() || !transmissionAllowed()) return;
546
+ const target = resolveTarget();
547
+ if (target === null) return;
548
+ let response;
549
+ try {
550
+ response = await fetch(target.url, {
551
+ method: "POST",
552
+ headers: {
553
+ Authorization: `Bearer ${target.apiKey}`,
554
+ "Content-Type": "application/json"
555
+ },
556
+ body: JSON.stringify({ events: batch })
557
+ });
558
+ } catch {
559
+ recordResult(false);
560
+ return;
561
+ }
562
+ setLevel(response.headers.get("X-Morse-Diagnostics"));
563
+ recordResult(response.ok);
564
+ } catch {
565
+ }
566
+ }
567
+ function resolveTarget() {
568
+ try {
569
+ const apiKey = getApiKey();
570
+ if (!apiKey) return null;
571
+ const url = deriveDiagnosticsUrl(String(getEndpoint() ?? ""));
572
+ if (!url) return null;
573
+ return { apiKey: String(apiKey), url };
574
+ } catch {
575
+ return null;
576
+ }
577
+ }
578
+ function deriveDiagnosticsUrl(tracesEndpoint) {
579
+ try {
580
+ const parsed = new URL(tracesEndpoint);
581
+ return `${parsed.protocol}//${parsed.host}${DIAGNOSTICS_PATH}`;
582
+ } catch {
583
+ return null;
584
+ }
585
+ }
586
+ function _resetForTesting() {
587
+ rateBuckets.clear();
588
+ localLogBuckets.clear();
589
+ counters.clear();
590
+ pending = [];
591
+ if (timer !== null) {
592
+ clearInterval(timer);
593
+ timer = null;
594
+ }
595
+ consecutiveFailures = 0;
596
+ breakerOpenUntil = 0;
597
+ reporting = false;
598
+ level = LEVEL_ERROR;
599
+ activeRedactionConfig = null;
600
+ }
601
+ 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, REASON_QUEUE_FULL, REASON_RETRY_EXHAUSTED, REASON_QUOTA_REJECTED, REASON_SHUTDOWN_DROP, counters, activeRedactionConfig, pending, timer, consecutiveFailures, breakerOpenUntil, reporting, MORSE_PATH_MARKERS;
602
+ var init_diagnostics = __esm({
603
+ "src/_internal/diagnostics.ts"() {
604
+ init_env();
605
+ init_redaction();
606
+ SDK_VERSION = "0.5.0-rc.2" ;
607
+ LEVEL_OFF = "off";
608
+ LEVEL_ERROR = "error";
609
+ LEVEL_DEBUG = "debug";
610
+ VALID_LEVELS = /* @__PURE__ */ new Set([LEVEL_OFF, LEVEL_ERROR, LEVEL_DEBUG]);
611
+ level = LEVEL_ERROR;
612
+ RATE_WINDOW_MS = 6e4;
613
+ RATE_LIMIT_PER_WINDOW = 100;
614
+ RATE_LIMIT_PER_WINDOW_DEBUG = 1e3;
615
+ rateBuckets = /* @__PURE__ */ new Map();
616
+ LOCAL_LOG_WINDOW_MS = 6e4;
617
+ LOCAL_LOG_LIMIT_PER_WINDOW = 10;
618
+ localLogBuckets = /* @__PURE__ */ new Map();
619
+ MAX_STACK_ENTRIES = 64;
620
+ MAX_MESSAGE_CHARS = 4096;
621
+ MAX_BATCH_EVENTS = 32;
622
+ ALLOWED_EXTRA_KEYS = /* @__PURE__ */ new Set([
623
+ "adapter",
624
+ "module",
625
+ "function",
626
+ "operation",
627
+ "endpoint_host"
628
+ ]);
629
+ DIAGNOSTICS_PATH = "/api/v1/diagnostics/sdk";
630
+ MAX_PENDING = 100;
631
+ FLUSH_INTERVAL_MS = 5e3;
632
+ BREAKER_THRESHOLD = 3;
633
+ BREAKER_COOLDOWN_MS = 3e5;
634
+ REASON_QUEUE_FULL = "queue_full";
635
+ REASON_RETRY_EXHAUSTED = "retry_exhausted";
636
+ REASON_QUOTA_REJECTED = "quota_rejected";
637
+ REASON_SHUTDOWN_DROP = "shutdown_drop";
638
+ counters = /* @__PURE__ */ new Map();
639
+ activeRedactionConfig = null;
640
+ pending = [];
641
+ timer = null;
642
+ consecutiveFailures = 0;
643
+ breakerOpenUntil = 0;
644
+ reporting = false;
645
+ MORSE_PATH_MARKERS = ["@morsehq/sdk", "morse-sdk", "/morse/", "morse_ai"];
646
+ }
647
+ });
648
+
649
+ // src/_internal/spans.ts
650
+ function generateTraceId() {
651
+ return randomHex(32);
652
+ }
653
+ function generateSpanId() {
654
+ return randomHex(32);
655
+ }
656
+ function randomHex(chars) {
657
+ const bytes = new Uint8Array(Math.ceil(chars / 2));
658
+ const cryptoObj = globalThis.crypto;
659
+ if (cryptoObj?.getRandomValues) {
660
+ cryptoObj.getRandomValues(bytes);
661
+ } else {
662
+ for (let i = 0; i < bytes.length; i++) {
663
+ bytes[i] = Math.floor(Math.random() * 256);
664
+ }
665
+ }
666
+ let hex = "";
667
+ for (const b of bytes) {
668
+ hex += b.toString(16).padStart(2, "0");
669
+ }
670
+ return hex.slice(0, chars);
671
+ }
672
+ function nowIso() {
673
+ return (/* @__PURE__ */ new Date()).toISOString();
674
+ }
675
+ function spanToWire(span) {
676
+ const out = {};
677
+ for (const [k, v] of Object.entries(span)) {
678
+ if (v !== void 0 && v !== null) {
679
+ out[k] = v;
680
+ }
681
+ }
682
+ return out;
683
+ }
684
+ function buildTraceEntry(fields, spans) {
685
+ return {
686
+ trace: fields,
687
+ spans: spans.map(spanToWire)
688
+ };
689
+ }
690
+ var SpanType;
691
+ var init_spans = __esm({
692
+ "src/_internal/spans.ts"() {
693
+ SpanType = {
694
+ AGENT: "agent",
695
+ LLM: "llm",
696
+ TOOL: "tool",
697
+ HTTP: "http",
698
+ DB: "db",
699
+ CUSTOM: "custom",
700
+ MEMORY: "memory",
701
+ // MHQ-482: matches Python's `SpanType.RETRIEVER` (apps/sdk/python/src/morse_ai/spans.py).
702
+ // @beta — retriever span type is subject to change before SDK v1.0 (see
703
+ // the plain-LangChain adapter's on_retriever_* callbacks in src/langchain/).
704
+ RETRIEVER: "retriever"
705
+ };
706
+ }
707
+ });
384
708
  function ensureGlobalContextManager() {
385
709
  if (contextManagerRegistered) return;
386
710
  contextManagerRegistered = true;
@@ -604,13 +928,21 @@ function emitTraceEntry(entry) {
604
928
  });
605
929
  }
606
930
  otelSpan.end(endTime);
607
- } catch {
931
+ } catch (err) {
932
+ reportSwallowed(err, "morse.otel_provider.shutdown");
608
933
  }
609
934
  }
610
935
  }
936
+ function reportSwallowed(err, fingerprint) {
937
+ try {
938
+ report(err, { fingerprint });
939
+ } catch {
940
+ }
941
+ }
611
942
  var INSTRUMENTATION_NAME, DEFAULT_MAX_FIELD_BYTES, TRUNCATION_MARKER, contextManagerRegistered, MAX_U64, RedactingSpanExporter, RecordingSpanExporter, ResultCapturingExporter, OtelEngine, engine;
612
943
  var init_otel_provider = __esm({
613
944
  "src/_internal/otel-provider.ts"() {
945
+ init_diagnostics();
614
946
  init_redaction();
615
947
  INSTRUMENTATION_NAME = "morse-typescript";
616
948
  DEFAULT_MAX_FIELD_BYTES = 65536;
@@ -763,7 +1095,8 @@ var init_otel_provider = __esm({
763
1095
  if (provider !== null) {
764
1096
  try {
765
1097
  await provider.forceFlush();
766
- } catch {
1098
+ } catch (err) {
1099
+ reportSwallowed(err, "morse.otel_provider.force_flush");
767
1100
  }
768
1101
  }
769
1102
  }
@@ -810,6 +1143,17 @@ function tryLoadAls() {
810
1143
  als = null;
811
1144
  return als;
812
1145
  }
1146
+ try {
1147
+ const getBuiltin = process?.getBuiltinModule;
1148
+ if (typeof getBuiltin === "function") {
1149
+ const mod = getBuiltin("node:async_hooks");
1150
+ if (mod?.AsyncLocalStorage) {
1151
+ als = new mod.AsyncLocalStorage();
1152
+ return als;
1153
+ }
1154
+ }
1155
+ } catch {
1156
+ }
813
1157
  try {
814
1158
  const dynamicRequire = Function("m", "return require(m)");
815
1159
  const mod = dynamicRequire("node:async_hooks");
@@ -842,8 +1186,9 @@ function setTransport(t) {
842
1186
  function getTransport() {
843
1187
  return transport;
844
1188
  }
845
- function setRedactionConfig(config) {
1189
+ function setRedactionConfig2(config) {
846
1190
  redactionConfig = config;
1191
+ setRedactionConfig(config);
847
1192
  }
848
1193
  function getRedactionConfig() {
849
1194
  return redactionConfig;
@@ -932,8 +1277,15 @@ function buildTraceDict(state, rootSpan) {
932
1277
  spans: spans.map((s) => redactSpanDict(s, config))
933
1278
  };
934
1279
  const effectiveSource = state.sourceOverride || _source;
1280
+ const resource = {};
935
1281
  if (effectiveSource) {
936
- out.resource = { "morse_ai.source": effectiveSource };
1282
+ resource["morse_ai.source"] = effectiveSource;
1283
+ }
1284
+ if (state.framework) {
1285
+ resource["morse_ai.framework"] = state.framework;
1286
+ }
1287
+ if (Object.keys(resource).length > 0) {
1288
+ out.resource = resource;
937
1289
  }
938
1290
  return out;
939
1291
  }
@@ -1029,16 +1381,37 @@ function errToString(e) {
1029
1381
  if (e instanceof Error) return e.message;
1030
1382
  return String(e);
1031
1383
  }
1384
+ function isThenable(v) {
1385
+ return v !== null && (typeof v === "object" || typeof v === "function") && typeof v.then === "function";
1386
+ }
1032
1387
  function runSync(opts, fn) {
1033
1388
  const { state, rootSpan, startMono } = startTrace(opts);
1034
1389
  const handle = buildRunHandle(state);
1035
1390
  const store = tryLoadAls();
1036
1391
  const runFn = () => withDbCaptureContext(state.traceId, rootSpan.span_id, () => fn(handle));
1037
- if (store) {
1038
- try {
1039
- const result = store.run(state, runFn);
1392
+ const settle = (result, onDone) => {
1393
+ if (!isThenable(result)) {
1040
1394
  endTrace(state, rootSpan, startMono, void 0);
1395
+ onDone();
1041
1396
  return result;
1397
+ }
1398
+ return result.then(
1399
+ (value) => {
1400
+ endTrace(state, rootSpan, startMono, void 0);
1401
+ onDone();
1402
+ return value;
1403
+ },
1404
+ (err) => {
1405
+ endTrace(state, rootSpan, startMono, err);
1406
+ onDone();
1407
+ throw err;
1408
+ }
1409
+ );
1410
+ };
1411
+ if (store) {
1412
+ try {
1413
+ return settle(store.run(state, runFn), () => {
1414
+ });
1042
1415
  } catch (err) {
1043
1416
  endTrace(state, rootSpan, startMono, err);
1044
1417
  throw err;
@@ -1046,14 +1419,11 @@ function runSync(opts, fn) {
1046
1419
  } else {
1047
1420
  const reset = setActiveTraceState(state);
1048
1421
  try {
1049
- const result = runFn();
1050
- endTrace(state, rootSpan, startMono, void 0);
1051
- return result;
1422
+ return settle(runFn(), reset);
1052
1423
  } catch (err) {
1053
1424
  endTrace(state, rootSpan, startMono, err);
1054
- throw err;
1055
- } finally {
1056
1425
  reset();
1426
+ throw err;
1057
1427
  }
1058
1428
  }
1059
1429
  }
@@ -1154,7 +1524,7 @@ async function spanAsync(opts, fn) {
1154
1524
  throw err;
1155
1525
  }
1156
1526
  }
1157
- function _resetForTesting() {
1527
+ function _resetForTesting2() {
1158
1528
  browserState = null;
1159
1529
  lastTrace = null;
1160
1530
  redactionConfig = buildRedactionConfig();
@@ -1164,6 +1534,7 @@ var init_tracing = __esm({
1164
1534
  "src/_internal/tracing.ts"() {
1165
1535
  init_env();
1166
1536
  init_otel_provider();
1537
+ init_diagnostics();
1167
1538
  init_redaction();
1168
1539
  init_spans();
1169
1540
  als = null;
@@ -1281,6 +1652,6 @@ var init_propagation = __esm({
1281
1652
  }
1282
1653
  });
1283
1654
 
1284
- export { DEFAULT_ENDPOINT, SpanType, W3C_TRACEPARENT_HEADER, _resetForTesting, buildRedactionConfig, buildTraceEntry, extractTraceparent, formatTraceparent, generateSpanId, generateTraceId, getActiveTraceState, getApiKey, getEndpoint, getEngine, getFlushIntervalSeconds, getInternalSource, getLastTrace, getMaxBatchSize, getMaxFieldBytes, getMaxQueueSize, getRedactionConfig, getSampleRate, getTransport, init_env, init_otel_provider, init_propagation, init_redaction, init_spans, init_tracing, injectIntoRequestInit, injectTraceparent, isAutoDetectDisabled, isDbCaptureEnabled, isDebug, isDisabled, isTelemetryDisabled, isValidInternalSource, nowIso, redactValue, runAsync, runSync, sendTrace, setContext, setRedactionConfig, setSource, setTransport, spanAsync, spanSync, startSpan };
1285
- //# sourceMappingURL=chunk-LTKGLXAE.js.map
1286
- //# sourceMappingURL=chunk-LTKGLXAE.js.map
1655
+ export { DEFAULT_ENDPOINT, REASON_QUEUE_FULL, REASON_QUOTA_REJECTED, REASON_RETRY_EXHAUSTED, REASON_SHUTDOWN_DROP, SpanType, W3C_TRACEPARENT_HEADER, _resetForTesting, _resetForTesting2, buildRedactionConfig, buildTraceEntry, extractTraceparent, formatTraceparent, generateSpanId, generateTraceId, getActiveTraceState, getApiKey, getEndpoint, getEngine, getFlushIntervalSeconds, getInternalSource, getLastTrace, getMaxBatchSize, getMaxFieldBytes, getMaxQueueSize, getRedactionConfig, getSampleRate, getTransport, init_diagnostics, init_env, init_otel_provider, init_propagation, init_redaction, init_spans, init_tracing, injectIntoRequestInit, injectTraceparent, isAutoDetectDisabled, isDbCaptureEnabled, isDisabled, isValidInternalSource, nowIso, recordDrop, redactValue, report, runAsync, runSync, sendTrace, setContext, setLevel, setRedactionConfig2 as setRedactionConfig, setSource, setTransport, spanAsync, spanSync, startSpan };
1656
+ //# sourceMappingURL=chunk-3IGQWLWE.js.map
1657
+ //# sourceMappingURL=chunk-3IGQWLWE.js.map