@morsehq-dev/sdk 0.4.0-rc.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.
Files changed (161) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +294 -0
  3. package/dist/anthropic/index.cjs +39 -0
  4. package/dist/anthropic/index.cjs.map +1 -0
  5. package/dist/anthropic/index.d.cts +213 -0
  6. package/dist/anthropic/index.d.ts +213 -0
  7. package/dist/anthropic/index.js +6 -0
  8. package/dist/anthropic/index.js.map +1 -0
  9. package/dist/anthropic-agent-sdk/index.cjs +744 -0
  10. package/dist/anthropic-agent-sdk/index.cjs.map +1 -0
  11. package/dist/anthropic-agent-sdk/index.d.cts +371 -0
  12. package/dist/anthropic-agent-sdk/index.d.ts +371 -0
  13. package/dist/anthropic-agent-sdk/index.js +735 -0
  14. package/dist/anthropic-agent-sdk/index.js.map +1 -0
  15. package/dist/browser/anthropic/index.cjs +39 -0
  16. package/dist/browser/anthropic/index.cjs.map +1 -0
  17. package/dist/browser/anthropic/index.js +6 -0
  18. package/dist/browser/anthropic/index.js.map +1 -0
  19. package/dist/browser/anthropic-agent-sdk/index.cjs +744 -0
  20. package/dist/browser/anthropic-agent-sdk/index.cjs.map +1 -0
  21. package/dist/browser/anthropic-agent-sdk/index.js +735 -0
  22. package/dist/browser/anthropic-agent-sdk/index.js.map +1 -0
  23. package/dist/browser/chunk-3643DC7K.cjs +365 -0
  24. package/dist/browser/chunk-3643DC7K.cjs.map +1 -0
  25. package/dist/browser/chunk-4FALQMOZ.js +232 -0
  26. package/dist/browser/chunk-4FALQMOZ.js.map +1 -0
  27. package/dist/browser/chunk-5J2QBK75.js +884 -0
  28. package/dist/browser/chunk-5J2QBK75.js.map +1 -0
  29. package/dist/browser/chunk-7MSXWGAH.js +53 -0
  30. package/dist/browser/chunk-7MSXWGAH.js.map +1 -0
  31. package/dist/browser/chunk-A24L5N5N.js +596 -0
  32. package/dist/browser/chunk-A24L5N5N.js.map +1 -0
  33. package/dist/browser/chunk-B7DEUDP6.cjs +177 -0
  34. package/dist/browser/chunk-B7DEUDP6.cjs.map +1 -0
  35. package/dist/browser/chunk-F6CJACNH.cjs +604 -0
  36. package/dist/browser/chunk-F6CJACNH.cjs.map +1 -0
  37. package/dist/browser/chunk-JBOYFQSB.js +412 -0
  38. package/dist/browser/chunk-JBOYFQSB.js.map +1 -0
  39. package/dist/browser/chunk-KRBADE6R.cjs +183 -0
  40. package/dist/browser/chunk-KRBADE6R.cjs.map +1 -0
  41. package/dist/browser/chunk-MCJYZH6W.cjs +415 -0
  42. package/dist/browser/chunk-MCJYZH6W.cjs.map +1 -0
  43. package/dist/browser/chunk-NQG2IAQS.js +178 -0
  44. package/dist/browser/chunk-NQG2IAQS.js.map +1 -0
  45. package/dist/browser/chunk-O4HG3OSK.cjs +929 -0
  46. package/dist/browser/chunk-O4HG3OSK.cjs.map +1 -0
  47. package/dist/browser/chunk-QWRQJO57.js +363 -0
  48. package/dist/browser/chunk-QWRQJO57.js.map +1 -0
  49. package/dist/browser/chunk-SWQOPFE4.cjs +234 -0
  50. package/dist/browser/chunk-SWQOPFE4.cjs.map +1 -0
  51. package/dist/browser/chunk-TYDG747E.js +171 -0
  52. package/dist/browser/chunk-TYDG747E.js.map +1 -0
  53. package/dist/browser/chunk-TZRSDDFP.cjs +56 -0
  54. package/dist/browser/chunk-TZRSDDFP.cjs.map +1 -0
  55. package/dist/browser/index.cjs +587 -0
  56. package/dist/browser/index.cjs.map +1 -0
  57. package/dist/browser/index.js +522 -0
  58. package/dist/browser/index.js.map +1 -0
  59. package/dist/browser/integrations/pino.cjs +89 -0
  60. package/dist/browser/integrations/pino.cjs.map +1 -0
  61. package/dist/browser/integrations/pino.js +86 -0
  62. package/dist/browser/integrations/pino.js.map +1 -0
  63. package/dist/browser/langchain/index.cjs +535 -0
  64. package/dist/browser/langchain/index.cjs.map +1 -0
  65. package/dist/browser/langchain/index.js +528 -0
  66. package/dist/browser/langchain/index.js.map +1 -0
  67. package/dist/browser/langgraph/index.cjs +377 -0
  68. package/dist/browser/langgraph/index.cjs.map +1 -0
  69. package/dist/browser/langgraph/index.js +371 -0
  70. package/dist/browser/langgraph/index.js.map +1 -0
  71. package/dist/browser/openai/index.cjs +125 -0
  72. package/dist/browser/openai/index.cjs.map +1 -0
  73. package/dist/browser/openai/index.js +122 -0
  74. package/dist/browser/openai/index.js.map +1 -0
  75. package/dist/browser/openai-agents/index.cjs +689 -0
  76. package/dist/browser/openai-agents/index.cjs.map +1 -0
  77. package/dist/browser/openai-agents/index.js +678 -0
  78. package/dist/browser/openai-agents/index.js.map +1 -0
  79. package/dist/browser/vercel-ai/index.cjs +233 -0
  80. package/dist/browser/vercel-ai/index.cjs.map +1 -0
  81. package/dist/browser/vercel-ai/index.js +231 -0
  82. package/dist/browser/vercel-ai/index.js.map +1 -0
  83. package/dist/chunk-4R4SHGOK.js +363 -0
  84. package/dist/chunk-4R4SHGOK.js.map +1 -0
  85. package/dist/chunk-7EO7MQBA.cjs +183 -0
  86. package/dist/chunk-7EO7MQBA.cjs.map +1 -0
  87. package/dist/chunk-7YCENA54.cjs +604 -0
  88. package/dist/chunk-7YCENA54.cjs.map +1 -0
  89. package/dist/chunk-CKFOGDUF.js +596 -0
  90. package/dist/chunk-CKFOGDUF.js.map +1 -0
  91. package/dist/chunk-FJUNILZT.cjs +1324 -0
  92. package/dist/chunk-FJUNILZT.cjs.map +1 -0
  93. package/dist/chunk-HDAFUKQ3.js +171 -0
  94. package/dist/chunk-HDAFUKQ3.js.map +1 -0
  95. package/dist/chunk-KBWPNIH4.cjs +234 -0
  96. package/dist/chunk-KBWPNIH4.cjs.map +1 -0
  97. package/dist/chunk-KJEO52QS.cjs +365 -0
  98. package/dist/chunk-KJEO52QS.cjs.map +1 -0
  99. package/dist/chunk-KZBCOZIQ.cjs +177 -0
  100. package/dist/chunk-KZBCOZIQ.cjs.map +1 -0
  101. package/dist/chunk-ME5JALGT.js +53 -0
  102. package/dist/chunk-ME5JALGT.js.map +1 -0
  103. package/dist/chunk-PVHDEPRE.cjs +56 -0
  104. package/dist/chunk-PVHDEPRE.cjs.map +1 -0
  105. package/dist/chunk-RTL23YOQ.js +178 -0
  106. package/dist/chunk-RTL23YOQ.js.map +1 -0
  107. package/dist/chunk-TQWI4UYO.js +1277 -0
  108. package/dist/chunk-TQWI4UYO.js.map +1 -0
  109. package/dist/chunk-VXDBDPDR.cjs +415 -0
  110. package/dist/chunk-VXDBDPDR.cjs.map +1 -0
  111. package/dist/chunk-XTKMUJWI.js +232 -0
  112. package/dist/chunk-XTKMUJWI.js.map +1 -0
  113. package/dist/chunk-ZKUGOWER.js +412 -0
  114. package/dist/chunk-ZKUGOWER.js.map +1 -0
  115. package/dist/index.cjs +843 -0
  116. package/dist/index.cjs.map +1 -0
  117. package/dist/index.d.cts +464 -0
  118. package/dist/index.d.ts +464 -0
  119. package/dist/index.js +778 -0
  120. package/dist/index.js.map +1 -0
  121. package/dist/integrations/pino.cjs +89 -0
  122. package/dist/integrations/pino.cjs.map +1 -0
  123. package/dist/integrations/pino.d.cts +65 -0
  124. package/dist/integrations/pino.d.ts +65 -0
  125. package/dist/integrations/pino.js +86 -0
  126. package/dist/integrations/pino.js.map +1 -0
  127. package/dist/langchain/index.cjs +535 -0
  128. package/dist/langchain/index.cjs.map +1 -0
  129. package/dist/langchain/index.d.cts +265 -0
  130. package/dist/langchain/index.d.ts +265 -0
  131. package/dist/langchain/index.js +528 -0
  132. package/dist/langchain/index.js.map +1 -0
  133. package/dist/langgraph/index.cjs +377 -0
  134. package/dist/langgraph/index.cjs.map +1 -0
  135. package/dist/langgraph/index.d.cts +324 -0
  136. package/dist/langgraph/index.d.ts +324 -0
  137. package/dist/langgraph/index.js +371 -0
  138. package/dist/langgraph/index.js.map +1 -0
  139. package/dist/openai/index.cjs +125 -0
  140. package/dist/openai/index.cjs.map +1 -0
  141. package/dist/openai/index.d.cts +136 -0
  142. package/dist/openai/index.d.ts +136 -0
  143. package/dist/openai/index.js +122 -0
  144. package/dist/openai/index.js.map +1 -0
  145. package/dist/openai-agents/index.cjs +689 -0
  146. package/dist/openai-agents/index.cjs.map +1 -0
  147. package/dist/openai-agents/index.d.cts +502 -0
  148. package/dist/openai-agents/index.d.ts +502 -0
  149. package/dist/openai-agents/index.js +678 -0
  150. package/dist/openai-agents/index.js.map +1 -0
  151. package/dist/spans-DZtMuBvc.d.cts +73 -0
  152. package/dist/spans-DZtMuBvc.d.ts +73 -0
  153. package/dist/tracing-BYAqjT5Q.d.cts +114 -0
  154. package/dist/tracing-rz9cWQ8d.d.ts +114 -0
  155. package/dist/vercel-ai/index.cjs +233 -0
  156. package/dist/vercel-ai/index.cjs.map +1 -0
  157. package/dist/vercel-ai/index.d.cts +93 -0
  158. package/dist/vercel-ai/index.d.ts +93 -0
  159. package/dist/vercel-ai/index.js +231 -0
  160. package/dist/vercel-ai/index.js.map +1 -0
  161. package/package.json +182 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,843 @@
1
+ 'use strict';
2
+
3
+ var chunk7YCENA54_cjs = require('./chunk-7YCENA54.cjs');
4
+ var chunkPVHDEPRE_cjs = require('./chunk-PVHDEPRE.cjs');
5
+ var chunk7EO7MQBA_cjs = require('./chunk-7EO7MQBA.cjs');
6
+ require('./chunk-KBWPNIH4.cjs');
7
+ var chunkFJUNILZT_cjs = require('./chunk-FJUNILZT.cjs');
8
+ var module$1 = require('module');
9
+ var instrumentationPg = require('@opentelemetry/instrumentation-pg');
10
+ var instrumentationMysql2 = require('@opentelemetry/instrumentation-mysql2');
11
+ var instrumentation = require('@opentelemetry/instrumentation');
12
+ var api = require('@opentelemetry/api');
13
+
14
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
15
+ chunkFJUNILZT_cjs.init_env();
16
+ var FULL_INSTALL_TARGETS = {
17
+ "@anthropic-ai/sdk": {
18
+ install: (mod) => chunk7YCENA54_cjs.instrumentAnthropic({ anthropicModule: mod })
19
+ }
20
+ };
21
+ var DETECT_ONLY_TARGETS = {
22
+ "@openai/agents": "wrapRunnerWithFullInstrumentation(runner) from '@morsehq-dev/sdk/openai-agents'",
23
+ "@langchain/langgraph": "new MorseCallbackHandler() from '@morsehq-dev/sdk/langgraph', passed via { callbacks: [...] }",
24
+ "@anthropic-ai/claude-agent-sdk": "wrapClaudeAgentSDKWithFullInstrumentation(client) from '@morsehq-dev/sdk/anthropic-agent-sdk'",
25
+ // MHQ-758: `ai`'s exports can't be patched in place (frozen ESM getters,
26
+ // no prototype to patch) — createTracedVercelAI() returns replacement
27
+ // functions instead. See `../vercel-ai/index.ts`'s module doc.
28
+ ai: "createTracedVercelAI() from '@morsehq-dev/sdk/vercel-ai' \u2014 use its returned streamText/generateText/generateObject in place of ai's own"
29
+ };
30
+ function isNodeRuntime() {
31
+ return typeof process !== "undefined" && !!process.versions?.node;
32
+ }
33
+ function getNodeRequire() {
34
+ if (!isNodeRuntime()) return null;
35
+ try {
36
+ return module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
37
+ } catch {
38
+ return null;
39
+ }
40
+ }
41
+ var firedFullInstall = /* @__PURE__ */ new Set();
42
+ var loggedDetectOnly = /* @__PURE__ */ new Set();
43
+ var lazyTargets = /* @__PURE__ */ new Set();
44
+ var hookInstalled = false;
45
+ var originalRequire = null;
46
+ function logger(message) {
47
+ console.info(message);
48
+ }
49
+ async function installFullTarget(name, mod) {
50
+ if (firedFullInstall.has(name)) return;
51
+ firedFullInstall.add(name);
52
+ const target = FULL_INSTALL_TARGETS[name];
53
+ if (!target) return;
54
+ try {
55
+ await target.install(mod);
56
+ } catch {
57
+ }
58
+ }
59
+ function logDetectOnlyIfPresent(nodeRequire, name) {
60
+ if (loggedDetectOnly.has(name)) return;
61
+ try {
62
+ nodeRequire.resolve(name);
63
+ } catch {
64
+ return;
65
+ }
66
+ loggedDetectOnly.add(name);
67
+ logger(
68
+ `morse: detected "${name}" \u2014 no zero-config path for this SDK yet. Call ${DETECT_ONLY_TARGETS[name]} to instrument it.`
69
+ );
70
+ }
71
+ function installLazyHook() {
72
+ if (hookInstalled) return;
73
+ originalRequire = module$1.Module.prototype.require;
74
+ const original = originalRequire;
75
+ module$1.Module.prototype.require = function patchedRequire(id) {
76
+ const result = original.call(this, id);
77
+ if (lazyTargets.has(id) && !firedFullInstall.has(id)) {
78
+ void installFullTarget(id, result);
79
+ }
80
+ return result;
81
+ };
82
+ hookInstalled = true;
83
+ }
84
+ function uninstallLazyHook() {
85
+ if (hookInstalled && originalRequire) {
86
+ module$1.Module.prototype.require = originalRequire;
87
+ }
88
+ hookInstalled = false;
89
+ originalRequire = null;
90
+ }
91
+ async function installAdapters() {
92
+ if (chunkFJUNILZT_cjs.isAutoDetectDisabled()) return;
93
+ const nodeRequire = getNodeRequire();
94
+ if (!nodeRequire) return;
95
+ const installPromises = [];
96
+ for (const name of Object.keys(FULL_INSTALL_TARGETS)) {
97
+ if (firedFullInstall.has(name)) continue;
98
+ let resolvedPath;
99
+ try {
100
+ resolvedPath = nodeRequire.resolve(name);
101
+ } catch {
102
+ continue;
103
+ }
104
+ if (resolvedPath in nodeRequire.cache) {
105
+ try {
106
+ const mod = nodeRequire(name);
107
+ installPromises.push(installFullTarget(name, mod));
108
+ } catch {
109
+ }
110
+ } else {
111
+ lazyTargets.add(name);
112
+ }
113
+ }
114
+ if (lazyTargets.size > 0) {
115
+ installLazyHook();
116
+ }
117
+ for (const name of Object.keys(DETECT_ONLY_TARGETS)) {
118
+ logDetectOnlyIfPresent(nodeRequire, name);
119
+ }
120
+ await Promise.all(installPromises);
121
+ }
122
+ function _resetForTesting3() {
123
+ uninstallLazyHook();
124
+ firedFullInstall.clear();
125
+ loggedDetectOnly.clear();
126
+ lazyTargets.clear();
127
+ }
128
+
129
+ // src/index.ts
130
+ chunkFJUNILZT_cjs.init_env();
131
+
132
+ // src/_internal/db-capture.ts
133
+ chunkFJUNILZT_cjs.init_env();
134
+ chunkFJUNILZT_cjs.init_otel_provider();
135
+ var SEMCONV_DB_SYSTEM_NAME = "db.system.name";
136
+ var SEMCONV_DB_QUERY_TEXT = "db.query.text";
137
+ var DB_SYSTEM_NAME_SQLITE = "sqlite";
138
+ var MAX_STATEMENT_CHARS = 2048;
139
+ var TRUNCATION_MARKER = "\u2026[truncated]";
140
+ function sqlVerb(sql) {
141
+ try {
142
+ const first = String(sql).trim().split(/\s+/, 1)[0];
143
+ return first ? first.toUpperCase() : "QUERY";
144
+ } catch {
145
+ return "QUERY";
146
+ }
147
+ }
148
+ function safeStatement(sql) {
149
+ let text;
150
+ try {
151
+ text = String(sql).trim();
152
+ } catch {
153
+ return void 0;
154
+ }
155
+ if (!text) return void 0;
156
+ if (text.length > MAX_STATEMENT_CHARS) {
157
+ return text.slice(0, MAX_STATEMENT_CHARS) + " " + TRUNCATION_MARKER;
158
+ }
159
+ return text;
160
+ }
161
+ var SYNC_STATEMENT_METHODS = ["run", "get", "all", "iterate"];
162
+ var BetterSqlite3Instrumentation = class extends instrumentation.InstrumentationBase {
163
+ constructor(config = {}) {
164
+ super("@morsehq/instrumentation-better-sqlite3", "0.1.0", config);
165
+ }
166
+ init() {
167
+ return [
168
+ new instrumentation.InstrumentationNodeModuleDefinition(
169
+ "better-sqlite3",
170
+ [">=7.0.0 <14"],
171
+ (moduleExports) => this._patch(moduleExports),
172
+ (moduleExports) => this._unpatch(moduleExports)
173
+ )
174
+ ];
175
+ }
176
+ _withSpan(sql, fn) {
177
+ const span2 = this.tracer.startSpan(sqlVerb(sql), { kind: api.SpanKind.CLIENT });
178
+ const stmt = safeStatement(sql);
179
+ span2.setAttribute(SEMCONV_DB_SYSTEM_NAME, DB_SYSTEM_NAME_SQLITE);
180
+ if (stmt) span2.setAttribute(SEMCONV_DB_QUERY_TEXT, stmt);
181
+ return api.context.with(api.trace.setSpan(api.context.active(), span2), () => {
182
+ try {
183
+ const result = fn();
184
+ span2.end();
185
+ return result;
186
+ } catch (err) {
187
+ span2.recordException(err);
188
+ span2.setStatus({ code: api.SpanStatusCode.ERROR, message: err?.message });
189
+ span2.end();
190
+ throw err;
191
+ }
192
+ });
193
+ }
194
+ /** Wrap one already-`prepare()`d statement's sync execution methods. */
195
+ _wrapStatementInstance(stmt) {
196
+ const sql = stmt?.source;
197
+ for (const method of SYNC_STATEMENT_METHODS) {
198
+ const original = stmt[method];
199
+ if (typeof original !== "function") continue;
200
+ const bound = original.bind(stmt);
201
+ stmt[method] = (...args) => this._withSpan(sql, () => bound(...args));
202
+ }
203
+ return stmt;
204
+ }
205
+ _patch(moduleExports) {
206
+ const DatabaseCtor = moduleExports;
207
+ const proto = DatabaseCtor?.prototype;
208
+ if (!proto) return moduleExports;
209
+ if (instrumentation.isWrapped(proto.prepare)) this._unwrap(proto, "prepare");
210
+ this._wrap(proto, "prepare", (original) => {
211
+ const wrapStatement = (stmt) => this._wrapStatementInstance(stmt);
212
+ return function(...args) {
213
+ const stmt = original.apply(this, args);
214
+ return wrapStatement(stmt);
215
+ };
216
+ });
217
+ if (instrumentation.isWrapped(proto.exec)) this._unwrap(proto, "exec");
218
+ this._wrap(proto, "exec", (original) => {
219
+ const withSpan = (sql, fn) => this._withSpan(sql, fn);
220
+ return function(...args) {
221
+ return withSpan(args[0], () => original.apply(this, args));
222
+ };
223
+ });
224
+ return moduleExports;
225
+ }
226
+ _unpatch(moduleExports) {
227
+ const proto = moduleExports?.prototype;
228
+ if (!proto) return;
229
+ if (instrumentation.isWrapped(proto.prepare)) this._unwrap(proto, "prepare");
230
+ if (instrumentation.isWrapped(proto.exec)) this._unwrap(proto, "exec");
231
+ }
232
+ };
233
+
234
+ // src/_internal/db-capture.ts
235
+ var unregister = null;
236
+ var registeredInstrumentations = null;
237
+ function buildDbInstrumentations() {
238
+ return [
239
+ new instrumentationPg.PgInstrumentation(),
240
+ new instrumentationMysql2.MySQL2Instrumentation(),
241
+ new BetterSqlite3Instrumentation()
242
+ ];
243
+ }
244
+ function registerDbInstrumentation() {
245
+ disableDbCapture();
246
+ try {
247
+ const instrumentations = buildDbInstrumentations();
248
+ const off = chunkFJUNILZT_cjs.getEngine().registerInstrumentations(instrumentations);
249
+ if (off === null) return false;
250
+ unregister = off;
251
+ registeredInstrumentations = instrumentations;
252
+ return true;
253
+ } catch {
254
+ unregister = null;
255
+ registeredInstrumentations = null;
256
+ return false;
257
+ }
258
+ }
259
+ function disableDbCapture() {
260
+ if (unregister !== null) {
261
+ try {
262
+ unregister();
263
+ } catch {
264
+ }
265
+ }
266
+ unregister = null;
267
+ registeredInstrumentations = null;
268
+ }
269
+ function maybeEnableDbCaptureFromEnv() {
270
+ if (chunkFJUNILZT_cjs.isDbCaptureEnabled()) {
271
+ registerDbInstrumentation();
272
+ }
273
+ }
274
+
275
+ // src/index.ts
276
+ chunkFJUNILZT_cjs.init_otel_provider();
277
+ chunkFJUNILZT_cjs.init_redaction();
278
+
279
+ // src/_internal/transport.ts
280
+ var SDK_VERSION = "0.4.0-rc.1" ;
281
+ var RETRY_AFTER_CAP_SECONDS = 30;
282
+ function parseRetryAfter(value) {
283
+ if (!value) return null;
284
+ const seconds = Number(value);
285
+ if (!Number.isFinite(seconds) || seconds < 0) return null;
286
+ return Math.min(seconds, RETRY_AFTER_CAP_SECONDS);
287
+ }
288
+ var quotaState = null;
289
+ function getQuotaState() {
290
+ return quotaState ? { ...quotaState } : null;
291
+ }
292
+ function _resetQuotaStateForTesting() {
293
+ quotaState = null;
294
+ }
295
+ function asString(value) {
296
+ return typeof value === "string" ? value : void 0;
297
+ }
298
+ function asNumber(value) {
299
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
300
+ }
301
+ function numberFromHeader(raw) {
302
+ if (raw === null) return void 0;
303
+ const n = Number(raw);
304
+ return Number.isFinite(n) ? n : void 0;
305
+ }
306
+ async function recordQuotaState(resp) {
307
+ try {
308
+ const state = {
309
+ kind: "unknown",
310
+ status: 429,
311
+ receivedAt: Date.now() / 1e3
312
+ };
313
+ let data = null;
314
+ try {
315
+ data = await resp.clone().json();
316
+ } catch {
317
+ data = null;
318
+ }
319
+ if (data !== null && typeof data === "object") {
320
+ const body = data;
321
+ const err = body.error;
322
+ if (err === "event_limit_exceeded") {
323
+ state.kind = "event_limit";
324
+ state.message = asString(body.message);
325
+ state.currentCount = asNumber(body.current_count);
326
+ state.limitCount = asNumber(body.limit_count);
327
+ state.planId = asString(body.plan_id);
328
+ state.periodStart = asString(body.period_start);
329
+ state.upgradeUrl = asString(body.upgrade_url);
330
+ state.sampleRateUrl = asString(body.sample_rate_url);
331
+ } else if (err !== null && typeof err === "object" && err.code === "RATE_LIMIT_INGEST") {
332
+ const errObj = err;
333
+ const details = errObj.details !== null && typeof errObj.details === "object" ? errObj.details : {};
334
+ state.kind = "rate_limit";
335
+ state.message = asString(errObj.message);
336
+ state.limitCount = asNumber(details.limit);
337
+ state.planId = asString(details.plan);
338
+ }
339
+ }
340
+ const quotaLimit = numberFromHeader(resp.headers.get("X-Morse-Quota-Limit"));
341
+ if (quotaLimit !== void 0) state.quotaLimit = quotaLimit;
342
+ const quotaRemaining = numberFromHeader(resp.headers.get("X-Morse-Quota-Remaining"));
343
+ if (quotaRemaining !== void 0) state.quotaRemaining = quotaRemaining;
344
+ const quotaReset = numberFromHeader(resp.headers.get("X-Morse-Quota-Reset"));
345
+ if (quotaReset !== void 0) state.quotaReset = quotaReset;
346
+ const retryAfter = parseRetryAfter(resp.headers.get("Retry-After"));
347
+ if (retryAfter !== null) state.retryAfterSeconds = retryAfter;
348
+ quotaState = state;
349
+ } catch {
350
+ }
351
+ }
352
+ var BatchTransport = class {
353
+ endpoint;
354
+ apiKey;
355
+ flushIntervalSeconds;
356
+ maxBatchSize;
357
+ maxQueueSize;
358
+ fetchTimeoutMs;
359
+ fetchImpl;
360
+ queue = [];
361
+ timer = null;
362
+ flushing = false;
363
+ closed = false;
364
+ inflight = null;
365
+ constructor(opts) {
366
+ this.endpoint = opts.endpoint;
367
+ this.apiKey = opts.apiKey;
368
+ this.flushIntervalSeconds = opts.flushIntervalSeconds ?? 2;
369
+ this.maxBatchSize = opts.maxBatchSize ?? 100;
370
+ this.maxQueueSize = opts.maxQueueSize ?? 1e4;
371
+ this.fetchTimeoutMs = opts.fetchTimeoutMs ?? 5e3;
372
+ this.fetchImpl = opts.fetchImpl ?? globalThis.fetch.bind(globalThis);
373
+ const intervalMs = Math.max(50, Math.round(this.flushIntervalSeconds * 1e3));
374
+ this.timer = setInterval(() => {
375
+ void this.tick();
376
+ }, intervalMs);
377
+ const t = this.timer;
378
+ if (typeof t?.unref === "function") {
379
+ t.unref();
380
+ }
381
+ }
382
+ /** Enqueue an event. Non-blocking. Returns false if the queue is full. */
383
+ track(event) {
384
+ if (this.closed) return false;
385
+ if (this.queue.length >= this.maxQueueSize) return false;
386
+ this.queue.push(event);
387
+ if (this.queue.length >= this.maxBatchSize) {
388
+ void this.tick();
389
+ }
390
+ return true;
391
+ }
392
+ /** Block until all currently-queued events have been sent. */
393
+ async flush() {
394
+ while (this.queue.length > 0) {
395
+ await this.tick();
396
+ }
397
+ if (this.inflight) {
398
+ try {
399
+ await this.inflight;
400
+ } catch {
401
+ }
402
+ }
403
+ }
404
+ /** Stop the background timer. After this call, `track()` is a no-op. */
405
+ async shutdown() {
406
+ if (this.closed) return;
407
+ this.closed = true;
408
+ if (this.timer !== null) {
409
+ clearInterval(this.timer);
410
+ this.timer = null;
411
+ }
412
+ await this.flush();
413
+ }
414
+ async tick() {
415
+ if (this.flushing) return;
416
+ if (this.queue.length === 0) return;
417
+ this.flushing = true;
418
+ try {
419
+ const batch = this.queue.splice(0, this.maxBatchSize);
420
+ this.inflight = this.sendBatch(batch);
421
+ await this.inflight;
422
+ this.inflight = null;
423
+ } finally {
424
+ this.flushing = false;
425
+ }
426
+ }
427
+ async sendBatch(batch) {
428
+ const traceEntries = [];
429
+ const runEntries = [];
430
+ const logEntries = [];
431
+ for (const event of batch) {
432
+ if (typeof event === "object" && event !== null && "traces" in event) {
433
+ const e = event;
434
+ if (Array.isArray(e.traces)) {
435
+ traceEntries.push(...e.traces);
436
+ }
437
+ } else if (typeof event === "object" && event !== null && "logs" in event) {
438
+ const e = event;
439
+ if (Array.isArray(e.logs)) {
440
+ logEntries.push(...e.logs);
441
+ }
442
+ } else {
443
+ runEntries.push(event);
444
+ }
445
+ }
446
+ if (traceEntries.length > 0) {
447
+ await this.post(this.endpoint, { traces: traceEntries });
448
+ }
449
+ if (runEntries.length > 0) {
450
+ await this.post(this.endpoint, { runs: runEntries });
451
+ }
452
+ if (logEntries.length > 0) {
453
+ await this.post(deriveLogsEndpoint(this.endpoint), { logs: logEntries });
454
+ }
455
+ }
456
+ async post(url, payload) {
457
+ const controller = new AbortController();
458
+ const timeoutId = setTimeout(() => controller.abort(), this.fetchTimeoutMs);
459
+ try {
460
+ const resp = await this.fetchImpl(url, {
461
+ method: "POST",
462
+ headers: {
463
+ Authorization: `Bearer ${this.apiKey}`,
464
+ "Content-Type": "application/json",
465
+ "User-Agent": `morse-typescript/${SDK_VERSION}`
466
+ },
467
+ body: JSON.stringify(payload),
468
+ signal: controller.signal
469
+ });
470
+ if (resp.status === 429) {
471
+ await recordQuotaState(resp);
472
+ }
473
+ if (!resp.ok) {
474
+ let bodySnippet = "";
475
+ try {
476
+ const text = await resp.text();
477
+ bodySnippet = text.slice(0, 200);
478
+ } catch {
479
+ }
480
+ chunk7EO7MQBA_cjs.report(new Error(`morse: batch POST returned ${resp.status} ${bodySnippet}`), {
481
+ fingerprint: "morse.transport.post.non_2xx",
482
+ extra: {
483
+ endpoint_host: hostnameOf(url),
484
+ sdk_version: SDK_VERSION
485
+ }
486
+ });
487
+ }
488
+ } catch (err) {
489
+ chunk7EO7MQBA_cjs.report(err, {
490
+ fingerprint: "morse.transport.post.network",
491
+ extra: {
492
+ endpoint_host: hostnameOf(url),
493
+ sdk_version: SDK_VERSION
494
+ }
495
+ });
496
+ } finally {
497
+ clearTimeout(timeoutId);
498
+ }
499
+ }
500
+ };
501
+ function hostnameOf(url) {
502
+ try {
503
+ return new URL(url).host;
504
+ } catch {
505
+ return "<invalid>";
506
+ }
507
+ }
508
+ function deriveLogsEndpoint(tracesEndpoint) {
509
+ try {
510
+ const u = new URL(tracesEndpoint);
511
+ u.pathname = "/api/v1/logs/ingest";
512
+ u.search = "";
513
+ u.hash = "";
514
+ return u.toString();
515
+ } catch {
516
+ return tracesEndpoint.replace(/\/api\/v1\/.*$/, "/api/v1/logs/ingest");
517
+ }
518
+ }
519
+
520
+ // src/index.ts
521
+ chunkFJUNILZT_cjs.init_tracing();
522
+ chunkFJUNILZT_cjs.init_spans();
523
+ chunkFJUNILZT_cjs.init_propagation();
524
+ var version = SDK_VERSION;
525
+ var singleton = null;
526
+ var transportFactory = (opts) => new BatchTransport(opts);
527
+ var noApiKeyWarningEmitted = false;
528
+ var lastLoggedEndpoint = null;
529
+ function logger2(level, message) {
530
+ const out = level === "warn" ? console.warn : console.info;
531
+ out.call(console, message);
532
+ }
533
+ function logDestinationOnce(endpoint) {
534
+ if (endpoint === lastLoggedEndpoint) return;
535
+ lastLoggedEndpoint = endpoint;
536
+ logger2(
537
+ "info",
538
+ `morse: Morse SDK initialized \u2014 sending to ${endpoint} (sdk version ${SDK_VERSION})`
539
+ );
540
+ }
541
+ function resolveEndpoint(explicit) {
542
+ if (explicit && explicit.length > 0) return explicit;
543
+ const fromEnv = chunkFJUNILZT_cjs.getEndpoint();
544
+ if (fromEnv) return fromEnv;
545
+ return chunkFJUNILZT_cjs.DEFAULT_ENDPOINT;
546
+ }
547
+ var OTLP_TRACES_PATH = "/api/v1/otlp/v1/traces";
548
+ function deriveOtlpEndpoint(tracesEndpoint) {
549
+ try {
550
+ const u = new URL(tracesEndpoint);
551
+ u.pathname = OTLP_TRACES_PATH;
552
+ u.search = "";
553
+ u.hash = "";
554
+ return u.toString();
555
+ } catch {
556
+ return tracesEndpoint.replace(/\/api\/v1\/.*$/, OTLP_TRACES_PATH);
557
+ }
558
+ }
559
+ function buildSingleton(opts, redaction) {
560
+ if (chunkFJUNILZT_cjs.isDisabled()) {
561
+ return null;
562
+ }
563
+ const apiKey = opts.apiKey ?? chunkFJUNILZT_cjs.getApiKey();
564
+ if (!apiKey) {
565
+ if (!noApiKeyWarningEmitted) {
566
+ logger2(
567
+ "warn",
568
+ "morse: not initialized \u2014 set MORSE_API_KEY or call morse.init({ apiKey }) (this warning prints once per process; SDK calls are silent no-ops)"
569
+ );
570
+ noApiKeyWarningEmitted = true;
571
+ }
572
+ return null;
573
+ }
574
+ const endpoint = resolveEndpoint(opts.endpoint);
575
+ const flushIntervalSeconds = opts.flushIntervalSeconds ?? chunkFJUNILZT_cjs.getFlushIntervalSeconds();
576
+ const transport = transportFactory({ apiKey, endpoint, flushIntervalSeconds });
577
+ chunkFJUNILZT_cjs.setTransport(transport);
578
+ chunkFJUNILZT_cjs.setRedactionConfig(redaction);
579
+ const explicitSource = chunkFJUNILZT_cjs.isValidInternalSource(opts.source) ? opts.source : void 0;
580
+ const resolvedSource = explicitSource ?? chunkFJUNILZT_cjs.getInternalSource() ?? null;
581
+ chunkFJUNILZT_cjs.setSource(resolvedSource);
582
+ logDestinationOnce(endpoint);
583
+ try {
584
+ chunkFJUNILZT_cjs.getEngine().configure({
585
+ endpoint: deriveOtlpEndpoint(endpoint),
586
+ apiKey,
587
+ sampleRate: chunkFJUNILZT_cjs.getSampleRate(),
588
+ scheduleDelayMillis: flushIntervalSeconds * 1e3,
589
+ maxQueueSize: chunkFJUNILZT_cjs.getMaxQueueSize(),
590
+ maxExportBatchSize: chunkFJUNILZT_cjs.getMaxBatchSize(),
591
+ maxFieldBytes: chunkFJUNILZT_cjs.getMaxFieldBytes(),
592
+ // 10s (not the exporter's un-overridden 30s ceiling): a genuine
593
+ // network blip still gets several retries with backoff; a fully dead
594
+ // endpoint fails within a bounded, shutdown-friendly window instead
595
+ // of the library's full 30s ceiling. Mirrors the Python SDK.
596
+ timeoutMillis: 1e4,
597
+ redactionConfig: redaction
598
+ });
599
+ } catch (err) {
600
+ chunk7EO7MQBA_cjs.report(err, { fingerprint: "morse.otel_provider.configure" });
601
+ }
602
+ void installAdapters().catch(() => {
603
+ });
604
+ try {
605
+ maybeEnableDbCaptureFromEnv();
606
+ } catch (err) {
607
+ chunk7EO7MQBA_cjs.report(err, { fingerprint: "morse.db_capture.register" });
608
+ }
609
+ return { apiKey, endpoint, transport, redaction };
610
+ }
611
+ function ensureInitialized() {
612
+ if (chunkFJUNILZT_cjs.isDisabled()) return null;
613
+ if (singleton !== null) return singleton;
614
+ singleton = buildSingleton({}, chunkFJUNILZT_cjs.buildRedactionConfig());
615
+ return singleton;
616
+ }
617
+ chunkPVHDEPRE_cjs._setEnsureInitialized(() => {
618
+ ensureInitialized();
619
+ });
620
+ function init(options = {}) {
621
+ if (chunkFJUNILZT_cjs.isDisabled()) {
622
+ logger2("info", "morse: MORSE_DISABLED=1 \u2014 SDK is a no-op");
623
+ return;
624
+ }
625
+ const redaction = chunkFJUNILZT_cjs.buildRedactionConfig(options.redaction);
626
+ try {
627
+ if (singleton !== null) {
628
+ void singleton.transport.shutdown();
629
+ singleton = null;
630
+ }
631
+ singleton = buildSingleton(options, redaction);
632
+ } catch (err) {
633
+ chunk7EO7MQBA_cjs.report(err, { fingerprint: "morse.init" });
634
+ }
635
+ }
636
+ var track = chunk7EO7MQBA_cjs.absorbErrorsSync(
637
+ (options) => {
638
+ const state = ensureInitialized();
639
+ if (!state) return;
640
+ const payload = {
641
+ agent_id: options.agentId,
642
+ ...options.runData
643
+ };
644
+ const redacted = chunkFJUNILZT_cjs.redactValue(payload, state.redaction);
645
+ state.transport.track(redacted);
646
+ },
647
+ { fingerprint: "morse.track" }
648
+ );
649
+ var batchTrack = chunk7EO7MQBA_cjs.absorbErrorsSync(
650
+ (runs) => {
651
+ const state = ensureInitialized();
652
+ if (!state) return;
653
+ for (const run2 of runs) {
654
+ const redacted = chunkFJUNILZT_cjs.redactValue(run2, state.redaction);
655
+ state.transport.track(redacted);
656
+ }
657
+ },
658
+ { fingerprint: "morse.batch_track" }
659
+ );
660
+ var record = chunk7EO7MQBA_cjs.absorbErrorsSync(
661
+ (rec) => {
662
+ const state = ensureInitialized();
663
+ if (!state) return;
664
+ const traceId = chunkFJUNILZT_cjs.generateTraceId();
665
+ const now = chunkFJUNILZT_cjs.nowIso();
666
+ const resolvedStatus = rec.errorMessage ? "failed" : rec.status ?? "completed";
667
+ const span2 = {
668
+ trace_id: traceId,
669
+ span_id: chunkFJUNILZT_cjs.generateSpanId(),
670
+ type: chunkFJUNILZT_cjs.SpanType.AGENT,
671
+ name: rec.agent,
672
+ started_at: now,
673
+ ended_at: now,
674
+ status: resolvedStatus,
675
+ duration_ms: rec.durationMs,
676
+ model: rec.model,
677
+ input_tokens: rec.inputTokens,
678
+ output_tokens: rec.outputTokens,
679
+ total_tokens: rec.totalTokens,
680
+ cost_usd: rec.cost,
681
+ error_message: rec.errorMessage,
682
+ metadata: rec.metadata
683
+ };
684
+ const traceFields = {
685
+ trace_id: traceId,
686
+ agent: rec.agent,
687
+ status: resolvedStatus,
688
+ started_at: now,
689
+ ended_at: now,
690
+ duration_ms: rec.durationMs,
691
+ error_message: rec.errorMessage,
692
+ success: rec.success,
693
+ outcome: rec.outcome
694
+ };
695
+ const entry = chunkFJUNILZT_cjs.buildTraceEntry(traceFields, [span2]);
696
+ const redacted = chunkFJUNILZT_cjs.redactValue(entry, state.redaction);
697
+ chunkFJUNILZT_cjs.sendTrace(redacted);
698
+ },
699
+ { fingerprint: "morse.record" }
700
+ );
701
+ function run(nameOrOpts, fn) {
702
+ const opts = typeof nameOrOpts === "string" ? { agentName: nameOrOpts } : nameOrOpts;
703
+ ensureInitialized();
704
+ return chunkFJUNILZT_cjs.runSync(opts, fn);
705
+ }
706
+ function runTraced(options, fn) {
707
+ ensureInitialized();
708
+ return chunkFJUNILZT_cjs.runAsync(options, fn);
709
+ }
710
+ function setContext2(dims) {
711
+ chunkFJUNILZT_cjs.setContext(dims);
712
+ }
713
+ function startSpan2(options) {
714
+ return chunkFJUNILZT_cjs.startSpan(options);
715
+ }
716
+ function span(options, fn) {
717
+ return chunkFJUNILZT_cjs.spanSync(options, fn);
718
+ }
719
+ function spanAsync2(options, fn) {
720
+ return chunkFJUNILZT_cjs.spanAsync(options, fn);
721
+ }
722
+ var flush = chunk7EO7MQBA_cjs.absorbErrorsAsync(
723
+ async () => {
724
+ if (singleton !== null) {
725
+ await singleton.transport.flush();
726
+ await chunkFJUNILZT_cjs.getEngine().flush();
727
+ }
728
+ },
729
+ { fingerprint: "morse.flush" }
730
+ );
731
+ var quotaState2 = chunk7EO7MQBA_cjs.absorbErrorsSync(
732
+ () => {
733
+ if (singleton === null) return null;
734
+ return getQuotaState();
735
+ },
736
+ { fingerprint: "morse.quota_state" }
737
+ );
738
+ var shutdown = chunk7EO7MQBA_cjs.absorbErrorsAsync(
739
+ async () => {
740
+ if (singleton !== null) {
741
+ await singleton.transport.shutdown();
742
+ await chunkFJUNILZT_cjs.getEngine().flush();
743
+ chunkFJUNILZT_cjs.getEngine().shutdown();
744
+ singleton = null;
745
+ chunkFJUNILZT_cjs.setTransport(null);
746
+ }
747
+ },
748
+ { fingerprint: "morse.shutdown" }
749
+ );
750
+ function _resetForTesting4() {
751
+ if (singleton !== null) {
752
+ void singleton.transport.shutdown();
753
+ singleton = null;
754
+ chunkFJUNILZT_cjs.setTransport(null);
755
+ }
756
+ chunkFJUNILZT_cjs.getEngine().resetForTesting();
757
+ noApiKeyWarningEmitted = false;
758
+ lastLoggedEndpoint = null;
759
+ chunkFJUNILZT_cjs.setSource(null);
760
+ chunkFJUNILZT_cjs._resetForTesting();
761
+ chunk7EO7MQBA_cjs._resetForTesting();
762
+ _resetForTesting3();
763
+ _resetQuotaStateForTesting();
764
+ transportFactory = (opts) => new BatchTransport(opts);
765
+ }
766
+ function _setTransportFactoryForTesting(factory) {
767
+ transportFactory = factory;
768
+ }
769
+ function _getLastTraceForTesting() {
770
+ return chunkFJUNILZT_cjs.getLastTrace();
771
+ }
772
+ function _getActiveTraceStateForTesting() {
773
+ return chunkFJUNILZT_cjs.getActiveTraceState();
774
+ }
775
+
776
+ Object.defineProperty(exports, "MAX_SEGMENT_CONTENT_BYTES", {
777
+ enumerable: true,
778
+ get: function () { return chunk7YCENA54_cjs.MAX_SEGMENT_CONTENT_BYTES; }
779
+ });
780
+ Object.defineProperty(exports, "extractAnthropicSegments", {
781
+ enumerable: true,
782
+ get: function () { return chunk7YCENA54_cjs.extractAnthropicSegments; }
783
+ });
784
+ Object.defineProperty(exports, "instrumentAnthropic", {
785
+ enumerable: true,
786
+ get: function () { return chunk7YCENA54_cjs.instrumentAnthropic; }
787
+ });
788
+ Object.defineProperty(exports, "isAnthropicWrapped", {
789
+ enumerable: true,
790
+ get: function () { return chunk7YCENA54_cjs.isAnthropicWrapped; }
791
+ });
792
+ Object.defineProperty(exports, "uninstallAnthropic", {
793
+ enumerable: true,
794
+ get: function () { return chunk7YCENA54_cjs.uninstallAnthropic; }
795
+ });
796
+ Object.defineProperty(exports, "wrapAnthropic", {
797
+ enumerable: true,
798
+ get: function () { return chunk7YCENA54_cjs.wrapAnthropic; }
799
+ });
800
+ Object.defineProperty(exports, "log", {
801
+ enumerable: true,
802
+ get: function () { return chunkPVHDEPRE_cjs.log; }
803
+ });
804
+ Object.defineProperty(exports, "W3C_TRACEPARENT_HEADER", {
805
+ enumerable: true,
806
+ get: function () { return chunkFJUNILZT_cjs.W3C_TRACEPARENT_HEADER; }
807
+ });
808
+ Object.defineProperty(exports, "extractTraceparent", {
809
+ enumerable: true,
810
+ get: function () { return chunkFJUNILZT_cjs.extractTraceparent; }
811
+ });
812
+ Object.defineProperty(exports, "formatTraceparent", {
813
+ enumerable: true,
814
+ get: function () { return chunkFJUNILZT_cjs.formatTraceparent; }
815
+ });
816
+ Object.defineProperty(exports, "injectIntoRequestInit", {
817
+ enumerable: true,
818
+ get: function () { return chunkFJUNILZT_cjs.injectIntoRequestInit; }
819
+ });
820
+ Object.defineProperty(exports, "injectTraceparent", {
821
+ enumerable: true,
822
+ get: function () { return chunkFJUNILZT_cjs.injectTraceparent; }
823
+ });
824
+ exports._getActiveTraceStateForTesting = _getActiveTraceStateForTesting;
825
+ exports._getLastTraceForTesting = _getLastTraceForTesting;
826
+ exports._resetForTesting = _resetForTesting4;
827
+ exports._setTransportFactoryForTesting = _setTransportFactoryForTesting;
828
+ exports.batchTrack = batchTrack;
829
+ exports.flush = flush;
830
+ exports.init = init;
831
+ exports.quotaState = quotaState2;
832
+ exports.record = record;
833
+ exports.run = run;
834
+ exports.runTraced = runTraced;
835
+ exports.setContext = setContext2;
836
+ exports.shutdown = shutdown;
837
+ exports.span = span;
838
+ exports.spanAsync = spanAsync2;
839
+ exports.startSpan = startSpan2;
840
+ exports.track = track;
841
+ exports.version = version;
842
+ //# sourceMappingURL=index.cjs.map
843
+ //# sourceMappingURL=index.cjs.map