@morphllm/morphsdk 0.2.197 → 0.2.198
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-WDLDKJHT.js → chunk-3XS5P5XH.js} +2 -2
- package/dist/{chunk-2HXELZI5.js → chunk-4DNEBVGV.js} +2 -2
- package/dist/chunk-4DNEBVGV.js.map +1 -0
- package/dist/{chunk-VJD6MF3M.js → chunk-4JUIEYAH.js} +4 -4
- package/dist/{chunk-LKFZBBTD.js → chunk-5TOJD2C5.js} +1 -1
- package/dist/chunk-5TOJD2C5.js.map +1 -0
- package/dist/{chunk-2BT4UGKH.js → chunk-6XFL2NER.js} +2 -2
- package/dist/{chunk-GE5MNVT7.js → chunk-CAFREMIT.js} +2 -2
- package/dist/{chunk-WN6YLBEH.js → chunk-D2RFP6R2.js} +4 -4
- package/dist/{chunk-CZ74CRGH.js → chunk-EMURAU6J.js} +4 -6
- package/dist/chunk-EMURAU6J.js.map +1 -0
- package/dist/{chunk-UOS3XKJD.js → chunk-FESO6TDQ.js} +2 -2
- package/dist/{chunk-PQCOBN7L.js → chunk-FUYX2MNM.js} +4 -4
- package/dist/chunk-FUYX2MNM.js.map +1 -0
- package/dist/{chunk-LRHJVSSD.js → chunk-GJ42MYUU.js} +2 -2
- package/dist/{chunk-ATAKRJQZ.js → chunk-IDMKQWQG.js} +1 -36
- package/dist/chunk-IDMKQWQG.js.map +1 -0
- package/dist/{chunk-JZJY2XFQ.js → chunk-KQKLQHJF.js} +2 -2
- package/dist/{chunk-OPNTDMHH.js → chunk-LN7GNFET.js} +4 -4
- package/dist/{chunk-ZA3UJRSE.js → chunk-O5264GI4.js} +2 -2
- package/dist/{chunk-TJUZAO7T.js → chunk-PEFXG5M6.js} +2 -2
- package/dist/{chunk-W34BUTVR.js → chunk-PIIXU2H3.js} +2 -2
- package/dist/{chunk-YVKRPVOM.js → chunk-PV6EF6NG.js} +2 -2
- package/dist/{chunk-7QOGUY4A.js → chunk-QKNGVBE2.js} +4 -4
- package/dist/{chunk-JU6TCHVI.js → chunk-SKN2L5CE.js} +2 -2
- package/dist/{chunk-SVD3YRWM.js → chunk-T6TXYTKH.js} +2 -2
- package/dist/{chunk-DW6ZIVCM.js → chunk-VBZ7BG47.js} +4 -4
- package/dist/{chunk-VGCPVDFP.js → chunk-WLMPQFER.js} +2 -2
- package/dist/{chunk-WFOGTZF6.js → chunk-XH6KJJDI.js} +2 -2
- package/dist/{chunk-2XDSHAB5.js → chunk-XK3PQZW6.js} +2 -2
- package/dist/{chunk-6YZCPCAY.js → chunk-XTFRHVCW.js} +2 -2
- package/dist/{chunk-FLWBVHDC.js → chunk-YD6TNDR4.js} +5 -5
- package/dist/{chunk-4FWK3CEH.js → chunk-YHZJYCOU.js} +23 -35
- package/dist/{chunk-4FWK3CEH.js.map → chunk-YHZJYCOU.js.map} +1 -1
- package/dist/{chunk-DHGXGVHC.js → chunk-YQ2G5YLI.js} +8 -8
- package/dist/{chunk-UZA2ODNU.js → chunk-YUH3MTP3.js} +2 -2
- package/dist/{chunk-BECYWCEZ.js → chunk-ZGERT23F.js} +2 -2
- package/dist/{chunk-DNL4DMMS.js → chunk-ZQNTXHBQ.js} +2 -2
- package/dist/{chunk-EGI642TV.js → chunk-ZU5YYGBJ.js} +3 -13
- package/dist/chunk-ZU5YYGBJ.js.map +1 -0
- package/dist/{client-B3fWTCcL.d.ts → client-DCeydotn.d.ts} +0 -6
- package/dist/client.cjs +5 -246
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.ts +1 -5
- package/dist/client.js +28 -30
- package/dist/core/client.cjs +2 -12
- package/dist/core/client.cjs.map +1 -1
- package/dist/core/client.d.ts +2 -2
- package/dist/core/client.js +4 -4
- package/dist/core/error.cjs +2 -12
- package/dist/core/error.cjs.map +1 -1
- package/dist/core/error.d.ts +1 -1
- package/dist/core/error.js +3 -3
- package/dist/core/index.cjs +2 -12
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.js +5 -5
- package/dist/core/resource.cjs.map +1 -1
- package/dist/core/resource.d.ts +1 -1
- package/dist/core/resource.js +1 -1
- package/dist/edge.cjs +2 -12
- package/dist/edge.cjs.map +1 -1
- package/dist/edge.js +8 -8
- package/dist/index.cjs +5 -252
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -5
- package/dist/index.js +30 -40
- package/dist/modelrouter/core.cjs +2 -12
- package/dist/modelrouter/core.cjs.map +1 -1
- package/dist/modelrouter/core.js +6 -6
- package/dist/modelrouter/index.cjs +2 -12
- package/dist/modelrouter/index.cjs.map +1 -1
- package/dist/modelrouter/index.js +6 -6
- package/dist/subagents/anthropic.cjs +2 -12
- package/dist/subagents/anthropic.cjs.map +1 -1
- package/dist/subagents/anthropic.js +11 -11
- package/dist/subagents/vercel.cjs +2 -12
- package/dist/subagents/vercel.cjs.map +1 -1
- package/dist/subagents/vercel.js +11 -11
- package/dist/tools/browser/anthropic.cjs +2 -12
- package/dist/tools/browser/anthropic.cjs.map +1 -1
- package/dist/tools/browser/anthropic.js +8 -8
- package/dist/tools/browser/core.cjs +2 -12
- package/dist/tools/browser/core.cjs.map +1 -1
- package/dist/tools/browser/core.js +7 -7
- package/dist/tools/browser/index.cjs +2 -12
- package/dist/tools/browser/index.cjs.map +1 -1
- package/dist/tools/browser/index.js +10 -10
- package/dist/tools/browser/openai.cjs +2 -12
- package/dist/tools/browser/openai.cjs.map +1 -1
- package/dist/tools/browser/openai.js +8 -8
- package/dist/tools/browser/profiles/core.cjs +2 -12
- package/dist/tools/browser/profiles/core.cjs.map +1 -1
- package/dist/tools/browser/profiles/core.js +3 -3
- package/dist/tools/browser/profiles/index.cjs +2 -12
- package/dist/tools/browser/profiles/index.cjs.map +1 -1
- package/dist/tools/browser/profiles/index.js +3 -3
- package/dist/tools/browser/vercel.cjs +2 -12
- package/dist/tools/browser/vercel.cjs.map +1 -1
- package/dist/tools/browser/vercel.js +8 -8
- package/dist/tools/codebase_search/anthropic.cjs +2 -12
- package/dist/tools/codebase_search/anthropic.cjs.map +1 -1
- package/dist/tools/codebase_search/anthropic.js +7 -7
- package/dist/tools/codebase_search/core.cjs +2 -12
- package/dist/tools/codebase_search/core.cjs.map +1 -1
- package/dist/tools/codebase_search/core.js +6 -6
- package/dist/tools/codebase_search/index.cjs +2 -12
- package/dist/tools/codebase_search/index.cjs.map +1 -1
- package/dist/tools/codebase_search/index.js +9 -9
- package/dist/tools/codebase_search/openai.cjs +2 -12
- package/dist/tools/codebase_search/openai.cjs.map +1 -1
- package/dist/tools/codebase_search/openai.js +7 -7
- package/dist/tools/codebase_search/vercel.cjs +2 -12
- package/dist/tools/codebase_search/vercel.cjs.map +1 -1
- package/dist/tools/codebase_search/vercel.js +7 -7
- package/dist/tools/compact/core.cjs +2 -12
- package/dist/tools/compact/core.cjs.map +1 -1
- package/dist/tools/compact/core.js +6 -6
- package/dist/tools/compact/index.cjs +2 -12
- package/dist/tools/compact/index.cjs.map +1 -1
- package/dist/tools/compact/index.js +7 -7
- package/dist/tools/fastapply/anthropic.cjs +2 -12
- package/dist/tools/fastapply/anthropic.cjs.map +1 -1
- package/dist/tools/fastapply/anthropic.js +8 -8
- package/dist/tools/fastapply/apply.cjs +2 -12
- package/dist/tools/fastapply/apply.cjs.map +1 -1
- package/dist/tools/fastapply/apply.js +2 -2
- package/dist/tools/fastapply/core.cjs +2 -12
- package/dist/tools/fastapply/core.cjs.map +1 -1
- package/dist/tools/fastapply/core.js +7 -7
- package/dist/tools/fastapply/index.cjs +2 -12
- package/dist/tools/fastapply/index.cjs.map +1 -1
- package/dist/tools/fastapply/index.js +10 -10
- package/dist/tools/fastapply/openai.cjs +2 -12
- package/dist/tools/fastapply/openai.cjs.map +1 -1
- package/dist/tools/fastapply/openai.js +8 -8
- package/dist/tools/fastapply/vercel.cjs +2 -12
- package/dist/tools/fastapply/vercel.cjs.map +1 -1
- package/dist/tools/fastapply/vercel.js +8 -8
- package/dist/tools/index.cjs +2 -12
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.js +10 -10
- package/dist/tools/utils/resilience.cjs +2 -12
- package/dist/tools/utils/resilience.cjs.map +1 -1
- package/dist/tools/utils/resilience.js +2 -2
- package/dist/tools/warp_grep/agent/runner.cjs +2 -12
- package/dist/tools/warp_grep/agent/runner.cjs.map +1 -1
- package/dist/tools/warp_grep/agent/runner.js +2 -2
- package/dist/tools/warp_grep/anthropic.cjs +2 -12
- package/dist/tools/warp_grep/anthropic.cjs.map +1 -1
- package/dist/tools/warp_grep/anthropic.js +11 -11
- package/dist/tools/warp_grep/client.cjs +2 -12
- package/dist/tools/warp_grep/client.cjs.map +1 -1
- package/dist/tools/warp_grep/client.js +10 -10
- package/dist/tools/warp_grep/gemini.cjs +2 -12
- package/dist/tools/warp_grep/gemini.cjs.map +1 -1
- package/dist/tools/warp_grep/gemini.js +10 -10
- package/dist/tools/warp_grep/harness.js +2 -2
- package/dist/tools/warp_grep/index.cjs +2 -12
- package/dist/tools/warp_grep/index.cjs.map +1 -1
- package/dist/tools/warp_grep/index.js +14 -14
- package/dist/tools/warp_grep/openai.cjs +2 -12
- package/dist/tools/warp_grep/openai.cjs.map +1 -1
- package/dist/tools/warp_grep/openai.js +11 -11
- package/dist/tools/warp_grep/providers/local.js +2 -2
- package/dist/tools/warp_grep/vercel.cjs +2 -12
- package/dist/tools/warp_grep/vercel.cjs.map +1 -1
- package/dist/tools/warp_grep/vercel.js +11 -11
- package/dist/tracing/core.cjs +2 -34
- package/dist/tracing/core.cjs.map +1 -1
- package/dist/tracing/core.d.ts +1 -2
- package/dist/tracing/core.js +2 -2
- package/dist/tracing/index.cjs +4 -42
- package/dist/tracing/index.cjs.map +1 -1
- package/dist/tracing/index.d.ts +0 -34
- package/dist/tracing/index.js +3 -10
- package/dist/tracing/interaction.cjs +0 -30
- package/dist/tracing/interaction.cjs.map +1 -1
- package/dist/tracing/interaction.js +1 -1
- package/dist/tracing/types.cjs.map +1 -1
- package/dist/tracing/types.d.ts +1 -27
- package/dist/version.cjs +2 -12
- package/dist/version.cjs.map +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -12
- package/dist/chunk-2HXELZI5.js.map +0 -1
- package/dist/chunk-ATAKRJQZ.js.map +0 -1
- package/dist/chunk-CZ74CRGH.js.map +0 -1
- package/dist/chunk-EGI642TV.js.map +0 -1
- package/dist/chunk-LKFZBBTD.js.map +0 -1
- package/dist/chunk-NKFAMQF2.js +0 -202
- package/dist/chunk-NKFAMQF2.js.map +0 -1
- package/dist/chunk-PQCOBN7L.js.map +0 -1
- package/dist/chunk-TCCZBGG5.js +0 -46
- package/dist/chunk-TCCZBGG5.js.map +0 -1
- package/dist/tools/reflex/core.cjs +0 -756
- package/dist/tools/reflex/core.cjs.map +0 -1
- package/dist/tools/reflex/core.d.ts +0 -59
- package/dist/tools/reflex/core.js +0 -16
- package/dist/tools/reflex/core.js.map +0 -1
- package/dist/tools/reflex/index.cjs +0 -756
- package/dist/tools/reflex/index.cjs.map +0 -1
- package/dist/tools/reflex/index.d.ts +0 -5
- package/dist/tools/reflex/index.js +0 -16
- package/dist/tools/reflex/index.js.map +0 -1
- package/dist/tools/reflex/types.cjs +0 -19
- package/dist/tools/reflex/types.cjs.map +0 -1
- package/dist/tools/reflex/types.d.ts +0 -171
- package/dist/tools/reflex/types.js +0 -1
- package/dist/tools/reflex/types.js.map +0 -1
- package/dist/tools/traces/core.cjs +0 -76
- package/dist/tools/traces/core.cjs.map +0 -1
- package/dist/tools/traces/core.d.ts +0 -24
- package/dist/tools/traces/core.js +0 -9
- package/dist/tools/traces/core.js.map +0 -1
- package/dist/tools/traces/index.cjs +0 -76
- package/dist/tools/traces/index.cjs.map +0 -1
- package/dist/tools/traces/index.d.ts +0 -5
- package/dist/tools/traces/index.js +0 -9
- package/dist/tools/traces/index.js.map +0 -1
- package/dist/tools/traces/types.cjs +0 -19
- package/dist/tools/traces/types.cjs.map +0 -1
- package/dist/tools/traces/types.d.ts +0 -56
- package/dist/tools/traces/types.js +0 -1
- package/dist/tools/traces/types.js.map +0 -1
- /package/dist/{chunk-WDLDKJHT.js.map → chunk-3XS5P5XH.js.map} +0 -0
- /package/dist/{chunk-VJD6MF3M.js.map → chunk-4JUIEYAH.js.map} +0 -0
- /package/dist/{chunk-2BT4UGKH.js.map → chunk-6XFL2NER.js.map} +0 -0
- /package/dist/{chunk-GE5MNVT7.js.map → chunk-CAFREMIT.js.map} +0 -0
- /package/dist/{chunk-WN6YLBEH.js.map → chunk-D2RFP6R2.js.map} +0 -0
- /package/dist/{chunk-UOS3XKJD.js.map → chunk-FESO6TDQ.js.map} +0 -0
- /package/dist/{chunk-LRHJVSSD.js.map → chunk-GJ42MYUU.js.map} +0 -0
- /package/dist/{chunk-JZJY2XFQ.js.map → chunk-KQKLQHJF.js.map} +0 -0
- /package/dist/{chunk-OPNTDMHH.js.map → chunk-LN7GNFET.js.map} +0 -0
- /package/dist/{chunk-ZA3UJRSE.js.map → chunk-O5264GI4.js.map} +0 -0
- /package/dist/{chunk-TJUZAO7T.js.map → chunk-PEFXG5M6.js.map} +0 -0
- /package/dist/{chunk-W34BUTVR.js.map → chunk-PIIXU2H3.js.map} +0 -0
- /package/dist/{chunk-YVKRPVOM.js.map → chunk-PV6EF6NG.js.map} +0 -0
- /package/dist/{chunk-7QOGUY4A.js.map → chunk-QKNGVBE2.js.map} +0 -0
- /package/dist/{chunk-JU6TCHVI.js.map → chunk-SKN2L5CE.js.map} +0 -0
- /package/dist/{chunk-SVD3YRWM.js.map → chunk-T6TXYTKH.js.map} +0 -0
- /package/dist/{chunk-DW6ZIVCM.js.map → chunk-VBZ7BG47.js.map} +0 -0
- /package/dist/{chunk-VGCPVDFP.js.map → chunk-WLMPQFER.js.map} +0 -0
- /package/dist/{chunk-WFOGTZF6.js.map → chunk-XH6KJJDI.js.map} +0 -0
- /package/dist/{chunk-2XDSHAB5.js.map → chunk-XK3PQZW6.js.map} +0 -0
- /package/dist/{chunk-6YZCPCAY.js.map → chunk-XTFRHVCW.js.map} +0 -0
- /package/dist/{chunk-FLWBVHDC.js.map → chunk-YD6TNDR4.js.map} +0 -0
- /package/dist/{chunk-DHGXGVHC.js.map → chunk-YQ2G5YLI.js.map} +0 -0
- /package/dist/{chunk-UZA2ODNU.js.map → chunk-YUH3MTP3.js.map} +0 -0
- /package/dist/{chunk-BECYWCEZ.js.map → chunk-ZGERT23F.js.map} +0 -0
- /package/dist/{chunk-DNL4DMMS.js.map → chunk-ZQNTXHBQ.js.map} +0 -0
|
@@ -5,26 +5,26 @@ import {
|
|
|
5
5
|
execute,
|
|
6
6
|
vercel_default,
|
|
7
7
|
warpGrepJsonSchema
|
|
8
|
-
} from "../../chunk-
|
|
8
|
+
} from "../../chunk-PEFXG5M6.js";
|
|
9
9
|
import "../../chunk-Q6QCHAMD.js";
|
|
10
10
|
import {
|
|
11
11
|
formatResult
|
|
12
|
-
} from "../../chunk-
|
|
12
|
+
} from "../../chunk-YQ2G5YLI.js";
|
|
13
|
+
import "../../chunk-MRMBFJR2.js";
|
|
13
14
|
import "../../chunk-A4D2CIIT.js";
|
|
14
15
|
import "../../chunk-63VHBANJ.js";
|
|
15
|
-
import "../../chunk-
|
|
16
|
-
import "../../chunk-MRMBFJR2.js";
|
|
16
|
+
import "../../chunk-3XS5P5XH.js";
|
|
17
17
|
import "../../chunk-IA5K2HTC.js";
|
|
18
18
|
import "../../chunk-CCJK3HTG.js";
|
|
19
19
|
import "../../chunk-FBRNUWEB.js";
|
|
20
|
-
import "../../chunk-
|
|
21
|
-
import "../../chunk-
|
|
22
|
-
import "../../chunk-
|
|
20
|
+
import "../../chunk-ZQNTXHBQ.js";
|
|
21
|
+
import "../../chunk-4JUIEYAH.js";
|
|
22
|
+
import "../../chunk-FUYX2MNM.js";
|
|
23
23
|
import "../../chunk-F3NCFNUX.js";
|
|
24
|
-
import "../../chunk-
|
|
25
|
-
import "../../chunk-
|
|
26
|
-
import "../../chunk-
|
|
27
|
-
import "../../chunk-
|
|
24
|
+
import "../../chunk-4DNEBVGV.js";
|
|
25
|
+
import "../../chunk-FESO6TDQ.js";
|
|
26
|
+
import "../../chunk-ZU5YYGBJ.js";
|
|
27
|
+
import "../../chunk-5TOJD2C5.js";
|
|
28
28
|
import "../../chunk-PZ5AY32C.js";
|
|
29
29
|
export {
|
|
30
30
|
createGitHubReadFileTool,
|
package/dist/tracing/core.cjs
CHANGED
|
@@ -67,34 +67,6 @@ function metadata(opts) {
|
|
|
67
67
|
return result;
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
-
// tracing/reflex.ts
|
|
71
|
-
var REFLEX_RUN_ATTRIBUTE = "morph.reflex.run";
|
|
72
|
-
var USER_TRANSFORM = "user_message";
|
|
73
|
-
var ASSISTANT_TRANSFORM = "assistant_message";
|
|
74
|
-
function normalizeEvals(evals) {
|
|
75
|
-
if (!evals) return [];
|
|
76
|
-
const out = [];
|
|
77
|
-
const seen = /* @__PURE__ */ new Set();
|
|
78
|
-
const add = (models, transform) => {
|
|
79
|
-
if (!Array.isArray(models)) return;
|
|
80
|
-
for (const raw of models) {
|
|
81
|
-
const model = typeof raw === "string" ? raw.trim() : "";
|
|
82
|
-
if (!model) continue;
|
|
83
|
-
const key = `${model} ${transform}`;
|
|
84
|
-
if (seen.has(key)) continue;
|
|
85
|
-
seen.add(key);
|
|
86
|
-
out.push({ model, transform });
|
|
87
|
-
}
|
|
88
|
-
};
|
|
89
|
-
add(evals.user, USER_TRANSFORM);
|
|
90
|
-
add(evals.assistant, ASSISTANT_TRANSFORM);
|
|
91
|
-
return out;
|
|
92
|
-
}
|
|
93
|
-
function serializeEvals(evals) {
|
|
94
|
-
const entries = normalizeEvals(evals);
|
|
95
|
-
return entries.length ? JSON.stringify(entries) : null;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
70
|
// tracing/interaction.ts
|
|
99
71
|
var ASSOC = "traceloop.association.properties.";
|
|
100
72
|
var ENTITY_INPUT = "traceloop.entity.input";
|
|
@@ -130,7 +102,6 @@ function createInteractionApi(initial, traceContent, onClose) {
|
|
|
130
102
|
let input = initial.input;
|
|
131
103
|
let workflowSpan = null;
|
|
132
104
|
let finished = false;
|
|
133
|
-
const reflexRun = serializeEvals(initial.evals);
|
|
134
105
|
const withAssoc = (fn) => traceloop.withAssociationProperties(associationProps(ctx, properties), fn);
|
|
135
106
|
const workflowName = () => ctx.event ?? "interaction";
|
|
136
107
|
function ensureWorkflowSpan() {
|
|
@@ -141,7 +112,6 @@ function createInteractionApi(initial, traceContent, onClose) {
|
|
|
141
112
|
span.setAttribute(ASSOC + k, v);
|
|
142
113
|
}
|
|
143
114
|
if (traceContent && input) span.setAttribute(ENTITY_INPUT, input);
|
|
144
|
-
if (reflexRun) span.setAttribute(REFLEX_RUN_ATTRIBUTE, reflexRun);
|
|
145
115
|
workflowSpan = span;
|
|
146
116
|
return span;
|
|
147
117
|
}
|
|
@@ -322,8 +292,7 @@ var MorphTracing = class {
|
|
|
322
292
|
disableBatching: config.disableBatching ?? !isProd,
|
|
323
293
|
traceContent: config.traceContent ?? true,
|
|
324
294
|
headers: config.headers,
|
|
325
|
-
debug
|
|
326
|
-
evals: config.evals
|
|
295
|
+
debug
|
|
327
296
|
};
|
|
328
297
|
if (config.disabled) {
|
|
329
298
|
log(debug, "disabled \u2014 no tracing initialized");
|
|
@@ -378,9 +347,8 @@ var MorphTracing = class {
|
|
|
378
347
|
*/
|
|
379
348
|
begin(ctx) {
|
|
380
349
|
if (!this.enabled) return createNoopInteraction(ctx);
|
|
381
|
-
const resolved = { ...ctx, evals: ctx.evals ?? this.cfg.evals };
|
|
382
350
|
const interaction = createInteractionApi(
|
|
383
|
-
|
|
351
|
+
ctx,
|
|
384
352
|
this.cfg.traceContent,
|
|
385
353
|
(eventId) => this.active.delete(eventId)
|
|
386
354
|
);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../tracing/core.ts","../../tracing/interaction.ts","../../tracing/otel.ts","../../tracing/reflex.ts"],"sourcesContent":["/**\n * Morph Tracing — core initialization.\n *\n * Thin Morph layer over OpenLLMetry / Traceloop. `morphTracing()` initializes\n * Traceloop with a JSON OTLP exporter pointed at Morph's ingest endpoint\n * (`${baseUrl}/v1/traces`, `Authorization: Bearer <apiKey>`) and returns a\n * `MorphTracing` handle for interactions and tools.\n *\n * We deliberately override Traceloop's default protobuf exporter with the\n * JSON-over-HTTP exporter so the ingest service can parse plain OTLP/JSON.\n */\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport * as traceloop from '@traceloop/node-server-sdk';\n\nimport {\n createInteractionApi,\n createNoopInteraction,\n type Interaction,\n type Tracer,\n} from './interaction.js';\nimport { metadata as buildMetadata } from './otel.js';\nimport type {\n EvalSelection,\n MetadataOptions,\n MorphTracingConfig,\n TraceContext,\n} from './types.js';\n\nconst DEFAULT_BASE_URL = 'https://api.morphllm.com';\n\nexport interface ResolvedConfig {\n apiKey: string;\n baseUrl: string;\n appName: string;\n disableBatching: boolean;\n traceContent: boolean;\n headers?: Record<string, string>;\n debug: boolean;\n evals?: EvalSelection;\n}\n\nfunction log(debug: boolean, ...args: unknown[]): void {\n if (debug) console.log('[morph-tracing]', ...args);\n}\n\n/**\n * Handle returned by {@link morphTracing}. Create interactions with `begin()`,\n * get a non-interactive `tracer()`, and flush/shutdown the exporter.\n */\nexport class MorphTracing {\n private readonly cfg: ResolvedConfig;\n private readonly active = new Map<string, Interaction>();\n readonly enabled: boolean;\n\n constructor(config: MorphTracingConfig = {}) {\n const debug = config.debug ?? process.env.MORPH_TRACING_DEBUG === '1';\n const apiKey = config.apiKey ?? process.env.MORPH_API_KEY ?? '';\n const baseUrlRaw =\n config.baseUrl ?? process.env.MORPH_TRACES_URL ?? DEFAULT_BASE_URL;\n const baseUrl = baseUrlRaw.replace(/\\/+$/, '');\n const isProd = process.env.NODE_ENV === 'production';\n\n this.cfg = {\n apiKey,\n baseUrl,\n appName: config.appName ?? process.env.npm_package_name ?? 'morph-app',\n disableBatching: config.disableBatching ?? !isProd,\n traceContent: config.traceContent ?? true,\n headers: config.headers,\n debug,\n evals: config.evals,\n };\n\n if (config.disabled) {\n log(debug, 'disabled — no tracing initialized');\n this.enabled = false;\n return;\n }\n if (!apiKey) {\n console.warn(\n '[morph-tracing] No API key (set MORPH_API_KEY or pass { apiKey }). Tracing disabled.',\n );\n this.enabled = false;\n return;\n }\n\n this.enabled = true;\n if (config.useExternalOtel) {\n // Customer drives their own NodeSDK; just register config, no SDK start.\n traceloop.initialize({\n baseUrl,\n apiKey,\n appName: this.cfg.appName,\n tracingEnabled: false,\n traceContent: this.cfg.traceContent,\n silenceInitializationMessage: true,\n });\n log(debug, 'external OTEL mode — add createSpanProcessor() to your NodeSDK');\n return;\n }\n\n const exporter = new OTLPTraceExporter({\n url: `${baseUrl}/v1/traces`,\n headers: { Authorization: `Bearer ${apiKey}`, ...this.cfg.headers },\n });\n\n traceloop.initialize({\n baseUrl,\n apiKey,\n appName: this.cfg.appName,\n exporter,\n disableBatch: this.cfg.disableBatching,\n traceContent: this.cfg.traceContent,\n instrumentModules: config.instrumentModules as NonNullable<\n Parameters<typeof traceloop.initialize>[0]\n >['instrumentModules'],\n tracingEnabled: true,\n traceloopSyncEnabled: false,\n silenceInitializationMessage: !debug,\n });\n log(\n debug,\n `initialized → ${baseUrl}/v1/traces (batching ${this.cfg.disableBatching ? 'off' : 'on'})`,\n );\n }\n\n /**\n * Begin a new traced interaction (a single user turn / agent run). On a\n * disabled instance this returns an inert no-op interaction — callbacks still\n * run, but no spans are created or shipped.\n */\n begin(ctx: TraceContext & { userId: string; event?: string }): Interaction {\n if (!this.enabled) return createNoopInteraction(ctx);\n // Per-interaction evals override the global default; omit both for none.\n const resolved = { ...ctx, evals: ctx.evals ?? this.cfg.evals };\n const interaction = createInteractionApi(resolved, this.cfg.traceContent, (eventId) =>\n this.active.delete(eventId),\n );\n this.active.set(interaction.getEventId()!, interaction);\n return interaction;\n }\n\n /** Look up an in-flight interaction by its eventId. */\n getActiveInteraction(eventId: string): Interaction | undefined {\n return this.active.get(eventId);\n }\n\n /**\n * Non-interactive tracer for batch jobs where you only care about\n * spans/token usage, not a user-facing interaction.\n */\n tracer(globalProperties: Record<string, string> = {}): Tracer {\n const ctx = { userId: globalProperties.userId ?? 'batch', properties: globalProperties };\n if (!this.enabled) return createNoopInteraction(ctx);\n return createInteractionApi(ctx, this.cfg.traceContent);\n }\n\n /** Build Vercel AI SDK telemetry metadata (see `@morphllm/morphsdk/tracing/otel`). */\n metadata(opts: MetadataOptions): Record<string, string> {\n return buildMetadata(opts);\n }\n\n /** Span processor for `useExternalOtel: true` integrations. */\n createSpanProcessor(\n options?: Parameters<typeof traceloop.createSpanProcessor>[0],\n ): ReturnType<typeof traceloop.createSpanProcessor> {\n // Traceloop's default exporter here is OTLP/protobuf, but Morph's ingest\n // parses OTLP/JSON only — supply the JSON exporter unless the caller\n // brings their own.\n const exporter =\n options?.exporter ??\n new OTLPTraceExporter({\n url: `${this.cfg.baseUrl}/v1/traces`,\n headers: { Authorization: `Bearer ${this.cfg.apiKey}`, ...this.cfg.headers },\n });\n return traceloop.createSpanProcessor({\n apiKey: this.cfg.apiKey,\n baseUrl: this.cfg.baseUrl,\n ...options,\n exporter,\n });\n }\n\n /** Flush any batched spans immediately. Safe to call when idle. */\n async forceFlush(): Promise<void> {\n if (!this.enabled) return;\n try {\n await traceloop.forceFlush();\n } catch (err) {\n log(this.cfg.debug, 'forceFlush error (ignored):', err);\n }\n }\n\n /** Flush and stop tracing. */\n async shutdown(): Promise<void> {\n await this.forceFlush();\n }\n}\n\n/**\n * Initialize Morph Tracing and auto-instrument supported AI SDKs.\n *\n * Requires the optional OpenTelemetry / Traceloop backends (see this module's\n * README). They install automatically with the SDK unless optional deps are\n * skipped; importing `/tracing` without them throws a module-not-found error\n * naming the missing package.\n */\nexport function morphTracing(config: MorphTracingConfig = {}): MorphTracing {\n return new MorphTracing(config);\n}\n","/**\n * Morph Tracing — interactions, tools, and manual spans.\n *\n * An `Interaction` is one user turn / agent run. It threads association\n * properties (user_id / convo_id / event_id) onto every span created inside it —\n * including the auto-instrumented LLM spans — so a whole conversation stitches\n * together in the Morph UI. Built on Traceloop's `withTask` / `withTool` and a\n * manual tracer for already-completed tool spans.\n */\nimport { context, SpanStatusCode, trace, type Span } from '@opentelemetry/api';\nimport * as traceloop from '@traceloop/node-server-sdk';\n\nimport { metadata as buildMetadata } from './otel.js';\nimport { REFLEX_RUN_ATTRIBUTE, serializeEvals } from './reflex.js';\nimport type {\n FinishOptions,\n SpanParams,\n ToolParams,\n ToolSpan,\n TrackToolParams,\n TraceContext,\n} from './types.js';\n\n// Traceloop semantic-convention attribute keys.\nconst ASSOC = 'traceloop.association.properties.';\nconst ENTITY_INPUT = 'traceloop.entity.input';\nconst ENTITY_OUTPUT = 'traceloop.entity.output';\nconst ENTITY_NAME = 'traceloop.entity.name';\nconst SPAN_KIND = 'traceloop.span.kind';\n\nfunction uuid(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n return 'xxxxxxxxxxxx4xxxyxxx'.replace(/[xy]/g, (ch) => {\n const r = (Math.random() * 16) | 0;\n return (ch === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n\nfunction asString(v: unknown): string {\n if (v == null) return '';\n return typeof v === 'string' ? v : JSON.stringify(v);\n}\n\nexport interface Interaction {\n getEventId(): string | undefined;\n setInput(input: string): void;\n setProperty(key: string, value: string): void;\n setProperties(props: Record<string, string>): void;\n /**\n * Run `fn` with this interaction's association properties active — required so\n * auto-instrumented OpenAI/Anthropic spans inherit user_id / convo_id / tags.\n */\n run<T>(fn: () => Promise<T> | T): Promise<T>;\n /** Run `fn` inside a traced task span; LLM calls within inherit attribution. */\n withSpan<T>(params: SpanParams | string, fn: () => Promise<T> | T): Promise<T>;\n /** Run `fn` inside a traced tool span. */\n withTool<T>(params: ToolParams | string, fn: () => Promise<T> | T): Promise<T>;\n /** Start a tool span you end manually. */\n startToolSpan(params: ToolParams | string): ToolSpan;\n /** Record an already-completed tool invocation. */\n trackTool(params: TrackToolParams): void;\n /** Metadata for the Vercel AI SDK `experimental_telemetry.metadata`. */\n vercelAiSdkMetadata(): Record<string, string>;\n /** End the interaction with its final output. */\n finish(opts: FinishOptions | string): Promise<void>;\n}\n\nexport type Tracer = Pick<Interaction, 'withSpan' | 'withTool' | 'startToolSpan' | 'trackTool'>;\n\n/** Build the association-property bag Traceloop propagates onto child spans. */\nfunction associationProps(\n ctx: TraceContext & { userId?: string },\n extra: Record<string, string>,\n): Record<string, string> {\n const props: Record<string, string> = { ...extra };\n if (ctx.userId) props.user_id = ctx.userId;\n if (ctx.convoId) props.convo_id = ctx.convoId;\n if (ctx.eventId) props.event_id = ctx.eventId;\n if (ctx.event) props.event_name = ctx.event;\n return props;\n}\n\nexport function createInteractionApi(\n initial: TraceContext & { userId?: string },\n traceContent: boolean,\n onClose?: (eventId: string) => void,\n): Interaction {\n const ctx: TraceContext & { userId?: string } = {\n ...initial,\n eventId: initial.eventId ?? uuid(),\n };\n const properties: Record<string, string> = { ...(initial.properties ?? {}) };\n let input = initial.input;\n let workflowSpan: Span | null = null;\n let finished = false;\n // Serialized once. Set as a raw attribute on the workflow span only — NOT an\n // association property, so it is not copied onto every child LLM span. Ingest\n // reads `morph.reflex.run` off the workflow-span to enqueue the evals.\n const reflexRun = serializeEvals(initial.evals);\n\n const withAssoc = <T>(fn: () => Promise<T> | T): Promise<T> | T =>\n traceloop.withAssociationProperties(associationProps(ctx, properties), fn);\n\n const workflowName = () => ctx.event ?? 'interaction';\n\n /** Open the interaction workflow span once; stays active until finish(). */\n function ensureWorkflowSpan(): Span {\n if (workflowSpan) return workflowSpan;\n const span = traceloop.getTraceloopTracer().startSpan(workflowName());\n span.setAttribute(SPAN_KIND, 'workflow');\n for (const [k, v] of Object.entries(associationProps(ctx, properties))) {\n span.setAttribute(ASSOC + k, v);\n }\n if (traceContent && input) span.setAttribute(ENTITY_INPUT, input);\n if (reflexRun) span.setAttribute(REFLEX_RUN_ATTRIBUTE, reflexRun);\n workflowSpan = span;\n return span;\n }\n\n /** Run fn with association props and the workflow span as the active parent. */\n function withWorkflowContext<T>(fn: () => Promise<T> | T): Promise<T> | T {\n return withAssoc(() => {\n const span = ensureWorkflowSpan();\n return context.with(trace.setSpan(context.active(), span), fn);\n });\n }\n\n /** Close the workflow span exactly once, applying final attributes. */\n function closeWorkflowSpan(apply: (span: Span) => void): void {\n if (finished) return;\n withAssoc(() => {\n const span = ensureWorkflowSpan();\n apply(span);\n span.end();\n });\n workflowSpan = null;\n finished = true;\n onClose?.(ctx.eventId!);\n }\n\n /** Record an exception + ERROR status on the workflow span, then close it. */\n function failWorkflowSpan(err: unknown): void {\n const e = err instanceof Error ? err : new Error(String(err));\n closeWorkflowSpan((span) => {\n span.recordException(e);\n span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });\n if (traceContent) span.setAttribute(ENTITY_OUTPUT, `ERROR: ${e.message}`);\n });\n }\n\n const toolName = (p: ToolParams | string) => (typeof p === 'string' ? p : p.name);\n\n function startToolSpan(params: ToolParams | string): ToolSpan {\n const name = toolName(params);\n const span: Span = traceloop.getTraceloopTracer().startSpan(name);\n span.setAttribute(SPAN_KIND, 'tool');\n span.setAttribute(ENTITY_NAME, name);\n for (const [k, v] of Object.entries(associationProps(ctx, properties))) {\n span.setAttribute(ASSOC + k, v);\n }\n if (typeof params !== 'string' && params.properties) {\n for (const [k, v] of Object.entries(params.properties)) span.setAttribute(k, v);\n }\n return {\n setInput(value: unknown) {\n if (traceContent) span.setAttribute(ENTITY_INPUT, asString(value));\n },\n setOutput(value: unknown) {\n if (traceContent) span.setAttribute(ENTITY_OUTPUT, asString(value));\n },\n setError(error: Error | string) {\n const e = typeof error === 'string' ? new Error(error) : error;\n span.recordException(e);\n span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });\n },\n end() {\n span.end();\n },\n };\n }\n\n return {\n getEventId: () => ctx.eventId,\n setInput(value: string) {\n input = value;\n },\n setProperty(key: string, value: string) {\n properties[key] = value;\n },\n setProperties(props: Record<string, string>) {\n Object.assign(properties, props);\n },\n vercelAiSdkMetadata() {\n return buildMetadata({\n userId: ctx.userId ?? 'unknown',\n convoId: ctx.convoId,\n eventName: ctx.event,\n eventId: ctx.eventId,\n properties,\n });\n },\n async run(fn) {\n try {\n return await Promise.resolve(withWorkflowContext(fn));\n } catch (err) {\n // Natively record the failure on the workflow span and ship it, so a\n // throwing interaction still lands in the trace as an errored span.\n failWorkflowSpan(err);\n throw err;\n }\n },\n withSpan(params, fn) {\n const name = typeof params === 'string' ? params : params.name;\n return Promise.resolve(withWorkflowContext(() => traceloop.withTask({ name }, fn)));\n },\n withTool(params, fn) {\n const name = toolName(params);\n const version = typeof params === 'string' ? undefined : params.version;\n return Promise.resolve(withWorkflowContext(() => traceloop.withTool({ name, version }, fn)));\n },\n startToolSpan,\n trackTool(params: TrackToolParams) {\n const span = startToolSpan({ name: params.name, properties: params.properties });\n if (params.input !== undefined) span.setInput(params.input);\n if (params.output !== undefined) span.setOutput(params.output);\n if (params.error) span.setError(params.error);\n span.end();\n },\n async finish(opts) {\n const output = typeof opts === 'string' ? opts : opts.output;\n if (typeof opts !== 'string' && opts.properties) Object.assign(properties, opts.properties);\n // No-op if run() already closed the span on error; otherwise end it now.\n // (Creates one if finish() is called alone, i.e. begin() → finish().)\n closeWorkflowSpan((span) => {\n if (traceContent) span.setAttribute(ENTITY_OUTPUT, output);\n });\n },\n };\n}\n\n/**\n * Inert Interaction for disabled instances. Preserves control flow — run() /\n * withTool() still execute their callback and rethrow errors — but never touches\n * the tracer. Required because the OTel provider is a process-wide singleton: a\n * disabled instance that created real spans would ship them through whichever\n * enabled instance registered the provider.\n */\nexport function createNoopInteraction(initial: TraceContext & { userId?: string }): Interaction {\n const ctx: TraceContext & { userId?: string } = {\n ...initial,\n eventId: initial.eventId ?? uuid(),\n };\n const properties: Record<string, string> = { ...(initial.properties ?? {}) };\n const noopToolSpan: ToolSpan = { setInput() {}, setOutput() {}, setError() {}, end() {} };\n\n return {\n getEventId: () => ctx.eventId,\n setInput() {},\n setProperty(key: string, value: string) {\n properties[key] = value;\n },\n setProperties(props: Record<string, string>) {\n Object.assign(properties, props);\n },\n vercelAiSdkMetadata() {\n return buildMetadata({\n userId: ctx.userId ?? 'unknown',\n convoId: ctx.convoId,\n eventName: ctx.event,\n eventId: ctx.eventId,\n properties,\n });\n },\n async run(fn) {\n return await fn();\n },\n async withSpan(_params, fn) {\n return await fn();\n },\n async withTool(_params, fn) {\n return await fn();\n },\n startToolSpan: () => noopToolSpan,\n trackTool() {},\n async finish() {},\n };\n}\n","/**\n * Morph Tracing — Vercel AI SDK helper.\n *\n * The Vercel AI SDK emits its own OpenTelemetry spans when you pass\n * `experimental_telemetry`. There is nothing to monkey-patch; instead you tag\n * each call with `metadata()` so Morph can attribute the resulting spans to a\n * user/conversation/event.\n *\n * @example\n * ```ts\n * import { generateText } from \"ai\";\n * import { metadata } from \"@morphllm/morphsdk/tracing/otel\";\n *\n * const res = await generateText({\n * model: openai(\"gpt-4o\"),\n * prompt: \"Hello!\",\n * experimental_telemetry: {\n * isEnabled: true,\n * metadata: metadata({ userId: \"user-123\", convoId: \"convo-456\" }),\n * },\n * });\n * ```\n */\nimport type { MetadataOptions } from './types.js';\n\n/**\n * Reserved metadata keys Morph owns. Custom `properties` can't overwrite these,\n * so attribution (user_id / convo_id / event_id) stays intact.\n *\n * The AI SDK stores metadata as `ai.telemetry.metadata.<key>`; Traceloop's span\n * processor copies them to `traceloop.association.properties.<key>`, which is\n * what ClickHouse views read. Use snake_case names (user_id, convo_id, …).\n */\nconst RESERVED_KEYS = new Set(['user_id', 'convo_id', 'event_id', 'event_name']);\n\nfunction uuid(): string {\n // Node 18+ and modern runtimes expose globalThis.crypto.randomUUID.\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n // Fallback: RFC4122-ish without crypto.\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => {\n const r = (Math.random() * 16) | 0;\n const v = ch === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Build the metadata object for the Vercel AI SDK's\n * `experimental_telemetry.metadata`. The values are propagated to every span the\n * AI SDK creates for that call. Generate a fresh `eventId` per call for grouping.\n */\nexport function metadata(opts: MetadataOptions): Record<string, string> {\n const result: Record<string, string> = {\n user_id: opts.userId,\n event_id: opts.eventId ?? uuid(),\n };\n if (opts.convoId) result.convo_id = opts.convoId;\n if (opts.eventName) result.event_name = opts.eventName;\n if (opts.properties) {\n for (const [key, value] of Object.entries(opts.properties)) {\n if (!RESERVED_KEYS.has(key)) result[key] = value;\n }\n }\n return result;\n}\n\nexport default { metadata };\n","/**\n * Morph Tracing — eval selection (which Reflexes to run on a trace).\n *\n * The public API is `evals` (see {@link EvalSelection}): `{ user, assistant }` choosing which role\n * each model classifies. We deliberately keep the public surface to plain nouns and hide the wire\n * detail: the selection is serialized onto a single\n * `morph.reflex.run` attribute on the interaction's workflow span (NOT an association property,\n * so it is not copied onto child LLM spans), and the per-role choice maps to the backend's\n * transform ids. Morph's ingest reads that attribute and runs the classifications async; results\n * land in the traces dashboard already labeled.\n */\nimport type { EvalSelection } from './types.js';\n\n/** Raw span attribute key carrying the serialized selection (internal wire detail). */\nexport const REFLEX_RUN_ATTRIBUTE = 'morph.reflex.run';\n\n// Public role → backend transform id. `user` classifies the user's message, `assistant` the\n// agent's output. (Whole-conversation evals are not exposed yet.)\nconst USER_TRANSFORM = 'user_message';\nconst ASSISTANT_TRANSFORM = 'assistant_message';\n\n/** One serialized entry on the wire: the model alias and the transform to run it on. */\nexport interface EvalRunEntry {\n model: string;\n transform: string;\n}\n\n/**\n * Normalize a public `evals` selection into deduped `{ model, transform }` wire entries.\n * `user` models run on the user turn, `assistant` models on the agent turn. Drops blank models;\n * preserves first-seen order. Exported for tests and so callers can see exactly what runs.\n */\nexport function normalizeEvals(evals: EvalSelection | undefined): EvalRunEntry[] {\n if (!evals) return [];\n const out: EvalRunEntry[] = [];\n const seen = new Set<string>();\n const add = (models: string[] | undefined, transform: string): void => {\n // Guard against a non-array (e.g. an untyped JS caller passing { user: \"jailbreak\" }) — iterating\n // a string would emit one bogus entry per character. Types forbid this; this is runtime defense.\n if (!Array.isArray(models)) return;\n for (const raw of models) {\n const model = typeof raw === 'string' ? raw.trim() : '';\n if (!model) continue;\n const key = `${model} ${transform}`;\n if (seen.has(key)) continue;\n seen.add(key);\n out.push({ model, transform });\n }\n };\n add(evals.user, USER_TRANSFORM);\n add(evals.assistant, ASSISTANT_TRANSFORM);\n return out;\n}\n\n/**\n * Serialize an `evals` selection to the `morph.reflex.run` attribute string, or `null` when\n * there is nothing to run (so the attribute is simply omitted and no classification is enqueued).\n */\nexport function serializeEvals(evals: EvalSelection | undefined): string | null {\n const entries = normalizeEvals(evals);\n return entries.length ? JSON.stringify(entries) : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,sCAAkC;AAClC,IAAAA,aAA2B;;;ACH3B,iBAA0D;AAC1D,gBAA2B;;;ACuB3B,IAAM,gBAAgB,oBAAI,IAAI,CAAC,WAAW,YAAY,YAAY,YAAY,CAAC;AAE/E,SAAS,OAAe;AAEtB,QAAM,IAAK,WAA0D;AACrE,MAAI,GAAG,WAAY,QAAO,EAAE,WAAW;AAEvC,SAAO,uCAAuC,QAAQ,SAAS,CAAC,OAAO;AACrE,UAAM,IAAK,KAAK,OAAO,IAAI,KAAM;AACjC,UAAM,IAAI,OAAO,MAAM,IAAK,IAAI,IAAO;AACvC,WAAO,EAAE,SAAS,EAAE;AAAA,EACtB,CAAC;AACH;AAOO,SAAS,SAAS,MAA+C;AACtE,QAAM,SAAiC;AAAA,IACrC,SAAS,KAAK;AAAA,IACd,UAAU,KAAK,WAAW,KAAK;AAAA,EACjC;AACA,MAAI,KAAK,QAAS,QAAO,WAAW,KAAK;AACzC,MA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,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,qBAAqB,SAA0C;AAC7D,WAAO,KAAK,OAAO,IAAI,OAAO;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OAAO,mBAA2C,CAAC,GAAW;AAC5D,UAAM,MAAM,EAAE,QAAQ,iBAAiB,UAAU,SAAS,YAAY,iBAAiB;AACvF,QAAI,CAAC,KAAK,QAAS,QAAO,sBAAsB,GAAG;AACnD,WAAO,qBAAqB,KAAK,KAAK,IAAI,YAAY;AAAA,EACxD;AAAA;AAAA,EAGA,SAAS,MAA+C;AACtD,WAAO,SAAc,IAAI;AAAA,EAC3B;AAAA;AAAA,EAGA,oBACE,SACkD;AAIlD,UAAM,WACJ,SAAS,YACT,IAAI,kDAAkB;AAAA,MACpB,KAAK,GAAG,KAAK,IAAI,OAAO;AAAA,MACxB,SAAS,EAAE,eAAe,UAAU,KAAK,IAAI,MAAM,IAAI,GAAG,KAAK,IAAI,QAAQ;AAAA,IAC7E,CAAC;AACH,WAAiB,+BAAoB;AAAA,MACnC,QAAQ,KAAK,IAAI;AAAA,MACjB,SAAS,KAAK,IAAI;AAAA,MAClB,GAAG;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA,EAGA,MAAM,aAA4B;AAChC,QAAI,CAAC,KAAK,QAAS;AACnB,QAAI;AACF,YAAgB,sBAAW;AAAA,IAC7B,SAAS,KAAK;AACZ,UAAI,KAAK,IAAI,OAAO,+BAA+B,GAAG;AAAA,IACxD;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,WAA0B;AAC9B,UAAM,KAAK,WAAW;AAAA,EACxB;AACF;AAUO,SAAS,aAAa,SAA6B,CAAC,GAAiB;AAC1E,SAAO,IAAI,aAAa,MAAM;AAChC;","names":["traceloop","uuid"]}
|
|
1
|
+
{"version":3,"sources":["../../tracing/core.ts","../../tracing/interaction.ts","../../tracing/otel.ts"],"sourcesContent":["/**\n * Morph Tracing — core initialization.\n *\n * Thin Morph layer over OpenLLMetry / Traceloop. `morphTracing()` initializes\n * Traceloop with a JSON OTLP exporter pointed at Morph's ingest endpoint\n * (`${baseUrl}/v1/traces`, `Authorization: Bearer <apiKey>`) and returns a\n * `MorphTracing` handle for interactions and tools.\n *\n * We deliberately override Traceloop's default protobuf exporter with the\n * JSON-over-HTTP exporter so the ingest service can parse plain OTLP/JSON.\n */\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport * as traceloop from '@traceloop/node-server-sdk';\n\nimport {\n createInteractionApi,\n createNoopInteraction,\n type Interaction,\n type Tracer,\n} from './interaction.js';\nimport { metadata as buildMetadata } from './otel.js';\nimport type {\n MetadataOptions,\n MorphTracingConfig,\n TraceContext,\n} from './types.js';\n\nconst DEFAULT_BASE_URL = 'https://api.morphllm.com';\n\nexport interface ResolvedConfig {\n apiKey: string;\n baseUrl: string;\n appName: string;\n disableBatching: boolean;\n traceContent: boolean;\n headers?: Record<string, string>;\n debug: boolean;\n}\n\nfunction log(debug: boolean, ...args: unknown[]): void {\n if (debug) console.log('[morph-tracing]', ...args);\n}\n\n/**\n * Handle returned by {@link morphTracing}. Create interactions with `begin()`,\n * get a non-interactive `tracer()`, and flush/shutdown the exporter.\n */\nexport class MorphTracing {\n private readonly cfg: ResolvedConfig;\n private readonly active = new Map<string, Interaction>();\n readonly enabled: boolean;\n\n constructor(config: MorphTracingConfig = {}) {\n const debug = config.debug ?? process.env.MORPH_TRACING_DEBUG === '1';\n const apiKey = config.apiKey ?? process.env.MORPH_API_KEY ?? '';\n const baseUrlRaw =\n config.baseUrl ?? process.env.MORPH_TRACES_URL ?? DEFAULT_BASE_URL;\n const baseUrl = baseUrlRaw.replace(/\\/+$/, '');\n const isProd = process.env.NODE_ENV === 'production';\n\n this.cfg = {\n apiKey,\n baseUrl,\n appName: config.appName ?? process.env.npm_package_name ?? 'morph-app',\n disableBatching: config.disableBatching ?? !isProd,\n traceContent: config.traceContent ?? true,\n headers: config.headers,\n debug,\n };\n\n if (config.disabled) {\n log(debug, 'disabled — no tracing initialized');\n this.enabled = false;\n return;\n }\n if (!apiKey) {\n console.warn(\n '[morph-tracing] No API key (set MORPH_API_KEY or pass { apiKey }). Tracing disabled.',\n );\n this.enabled = false;\n return;\n }\n\n this.enabled = true;\n if (config.useExternalOtel) {\n // Customer drives their own NodeSDK; just register config, no SDK start.\n traceloop.initialize({\n baseUrl,\n apiKey,\n appName: this.cfg.appName,\n tracingEnabled: false,\n traceContent: this.cfg.traceContent,\n silenceInitializationMessage: true,\n });\n log(debug, 'external OTEL mode — add createSpanProcessor() to your NodeSDK');\n return;\n }\n\n const exporter = new OTLPTraceExporter({\n url: `${baseUrl}/v1/traces`,\n headers: { Authorization: `Bearer ${apiKey}`, ...this.cfg.headers },\n });\n\n traceloop.initialize({\n baseUrl,\n apiKey,\n appName: this.cfg.appName,\n exporter,\n disableBatch: this.cfg.disableBatching,\n traceContent: this.cfg.traceContent,\n instrumentModules: config.instrumentModules as NonNullable<\n Parameters<typeof traceloop.initialize>[0]\n >['instrumentModules'],\n tracingEnabled: true,\n traceloopSyncEnabled: false,\n silenceInitializationMessage: !debug,\n });\n log(\n debug,\n `initialized → ${baseUrl}/v1/traces (batching ${this.cfg.disableBatching ? 'off' : 'on'})`,\n );\n }\n\n /**\n * Begin a new traced interaction (a single user turn / agent run). On a\n * disabled instance this returns an inert no-op interaction — callbacks still\n * run, but no spans are created or shipped.\n */\n begin(ctx: TraceContext & { userId: string; event?: string }): Interaction {\n if (!this.enabled) return createNoopInteraction(ctx);\n const interaction = createInteractionApi(ctx, this.cfg.traceContent, (eventId) =>\n this.active.delete(eventId),\n );\n this.active.set(interaction.getEventId()!, interaction);\n return interaction;\n }\n\n /** Look up an in-flight interaction by its eventId. */\n getActiveInteraction(eventId: string): Interaction | undefined {\n return this.active.get(eventId);\n }\n\n /**\n * Non-interactive tracer for batch jobs where you only care about\n * spans/token usage, not a user-facing interaction.\n */\n tracer(globalProperties: Record<string, string> = {}): Tracer {\n const ctx = { userId: globalProperties.userId ?? 'batch', properties: globalProperties };\n if (!this.enabled) return createNoopInteraction(ctx);\n return createInteractionApi(ctx, this.cfg.traceContent);\n }\n\n /** Build Vercel AI SDK telemetry metadata (see `@morphllm/morphsdk/tracing/otel`). */\n metadata(opts: MetadataOptions): Record<string, string> {\n return buildMetadata(opts);\n }\n\n /** Span processor for `useExternalOtel: true` integrations. */\n createSpanProcessor(\n options?: Parameters<typeof traceloop.createSpanProcessor>[0],\n ): ReturnType<typeof traceloop.createSpanProcessor> {\n // Traceloop's default exporter here is OTLP/protobuf, but Morph's ingest\n // parses OTLP/JSON only — supply the JSON exporter unless the caller\n // brings their own.\n const exporter =\n options?.exporter ??\n new OTLPTraceExporter({\n url: `${this.cfg.baseUrl}/v1/traces`,\n headers: { Authorization: `Bearer ${this.cfg.apiKey}`, ...this.cfg.headers },\n });\n return traceloop.createSpanProcessor({\n apiKey: this.cfg.apiKey,\n baseUrl: this.cfg.baseUrl,\n ...options,\n exporter,\n });\n }\n\n /** Flush any batched spans immediately. Safe to call when idle. */\n async forceFlush(): Promise<void> {\n if (!this.enabled) return;\n try {\n await traceloop.forceFlush();\n } catch (err) {\n log(this.cfg.debug, 'forceFlush error (ignored):', err);\n }\n }\n\n /** Flush and stop tracing. */\n async shutdown(): Promise<void> {\n await this.forceFlush();\n }\n}\n\n/**\n * Initialize Morph Tracing and auto-instrument supported AI SDKs.\n *\n * Requires the optional OpenTelemetry / Traceloop backends (see this module's\n * README). They install automatically with the SDK unless optional deps are\n * skipped; importing `/tracing` without them throws a module-not-found error\n * naming the missing package.\n */\nexport function morphTracing(config: MorphTracingConfig = {}): MorphTracing {\n return new MorphTracing(config);\n}\n","/**\n * Morph Tracing — interactions, tools, and manual spans.\n *\n * An `Interaction` is one user turn / agent run. It threads association\n * properties (user_id / convo_id / event_id) onto every span created inside it —\n * including the auto-instrumented LLM spans — so a whole conversation stitches\n * together in the Morph UI. Built on Traceloop's `withTask` / `withTool` and a\n * manual tracer for already-completed tool spans.\n */\nimport { context, SpanStatusCode, trace, type Span } from '@opentelemetry/api';\nimport * as traceloop from '@traceloop/node-server-sdk';\n\nimport { metadata as buildMetadata } from './otel.js';\nimport type {\n FinishOptions,\n SpanParams,\n ToolParams,\n ToolSpan,\n TrackToolParams,\n TraceContext,\n} from './types.js';\n\n// Traceloop semantic-convention attribute keys.\nconst ASSOC = 'traceloop.association.properties.';\nconst ENTITY_INPUT = 'traceloop.entity.input';\nconst ENTITY_OUTPUT = 'traceloop.entity.output';\nconst ENTITY_NAME = 'traceloop.entity.name';\nconst SPAN_KIND = 'traceloop.span.kind';\n\nfunction uuid(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n return 'xxxxxxxxxxxx4xxxyxxx'.replace(/[xy]/g, (ch) => {\n const r = (Math.random() * 16) | 0;\n return (ch === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n\nfunction asString(v: unknown): string {\n if (v == null) return '';\n return typeof v === 'string' ? v : JSON.stringify(v);\n}\n\nexport interface Interaction {\n getEventId(): string | undefined;\n setInput(input: string): void;\n setProperty(key: string, value: string): void;\n setProperties(props: Record<string, string>): void;\n /**\n * Run `fn` with this interaction's association properties active — required so\n * auto-instrumented OpenAI/Anthropic spans inherit user_id / convo_id / tags.\n */\n run<T>(fn: () => Promise<T> | T): Promise<T>;\n /** Run `fn` inside a traced task span; LLM calls within inherit attribution. */\n withSpan<T>(params: SpanParams | string, fn: () => Promise<T> | T): Promise<T>;\n /** Run `fn` inside a traced tool span. */\n withTool<T>(params: ToolParams | string, fn: () => Promise<T> | T): Promise<T>;\n /** Start a tool span you end manually. */\n startToolSpan(params: ToolParams | string): ToolSpan;\n /** Record an already-completed tool invocation. */\n trackTool(params: TrackToolParams): void;\n /** Metadata for the Vercel AI SDK `experimental_telemetry.metadata`. */\n vercelAiSdkMetadata(): Record<string, string>;\n /** End the interaction with its final output. */\n finish(opts: FinishOptions | string): Promise<void>;\n}\n\nexport type Tracer = Pick<Interaction, 'withSpan' | 'withTool' | 'startToolSpan' | 'trackTool'>;\n\n/** Build the association-property bag Traceloop propagates onto child spans. */\nfunction associationProps(\n ctx: TraceContext & { userId?: string },\n extra: Record<string, string>,\n): Record<string, string> {\n const props: Record<string, string> = { ...extra };\n if (ctx.userId) props.user_id = ctx.userId;\n if (ctx.convoId) props.convo_id = ctx.convoId;\n if (ctx.eventId) props.event_id = ctx.eventId;\n if (ctx.event) props.event_name = ctx.event;\n return props;\n}\n\nexport function createInteractionApi(\n initial: TraceContext & { userId?: string },\n traceContent: boolean,\n onClose?: (eventId: string) => void,\n): Interaction {\n const ctx: TraceContext & { userId?: string } = {\n ...initial,\n eventId: initial.eventId ?? uuid(),\n };\n const properties: Record<string, string> = { ...(initial.properties ?? {}) };\n let input = initial.input;\n let workflowSpan: Span | null = null;\n let finished = false;\n\n const withAssoc = <T>(fn: () => Promise<T> | T): Promise<T> | T =>\n traceloop.withAssociationProperties(associationProps(ctx, properties), fn);\n\n const workflowName = () => ctx.event ?? 'interaction';\n\n /** Open the interaction workflow span once; stays active until finish(). */\n function ensureWorkflowSpan(): Span {\n if (workflowSpan) return workflowSpan;\n const span = traceloop.getTraceloopTracer().startSpan(workflowName());\n span.setAttribute(SPAN_KIND, 'workflow');\n for (const [k, v] of Object.entries(associationProps(ctx, properties))) {\n span.setAttribute(ASSOC + k, v);\n }\n if (traceContent && input) span.setAttribute(ENTITY_INPUT, input);\n workflowSpan = span;\n return span;\n }\n\n /** Run fn with association props and the workflow span as the active parent. */\n function withWorkflowContext<T>(fn: () => Promise<T> | T): Promise<T> | T {\n return withAssoc(() => {\n const span = ensureWorkflowSpan();\n return context.with(trace.setSpan(context.active(), span), fn);\n });\n }\n\n /** Close the workflow span exactly once, applying final attributes. */\n function closeWorkflowSpan(apply: (span: Span) => void): void {\n if (finished) return;\n withAssoc(() => {\n const span = ensureWorkflowSpan();\n apply(span);\n span.end();\n });\n workflowSpan = null;\n finished = true;\n onClose?.(ctx.eventId!);\n }\n\n /** Record an exception + ERROR status on the workflow span, then close it. */\n function failWorkflowSpan(err: unknown): void {\n const e = err instanceof Error ? err : new Error(String(err));\n closeWorkflowSpan((span) => {\n span.recordException(e);\n span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });\n if (traceContent) span.setAttribute(ENTITY_OUTPUT, `ERROR: ${e.message}`);\n });\n }\n\n const toolName = (p: ToolParams | string) => (typeof p === 'string' ? p : p.name);\n\n function startToolSpan(params: ToolParams | string): ToolSpan {\n const name = toolName(params);\n const span: Span = traceloop.getTraceloopTracer().startSpan(name);\n span.setAttribute(SPAN_KIND, 'tool');\n span.setAttribute(ENTITY_NAME, name);\n for (const [k, v] of Object.entries(associationProps(ctx, properties))) {\n span.setAttribute(ASSOC + k, v);\n }\n if (typeof params !== 'string' && params.properties) {\n for (const [k, v] of Object.entries(params.properties)) span.setAttribute(k, v);\n }\n return {\n setInput(value: unknown) {\n if (traceContent) span.setAttribute(ENTITY_INPUT, asString(value));\n },\n setOutput(value: unknown) {\n if (traceContent) span.setAttribute(ENTITY_OUTPUT, asString(value));\n },\n setError(error: Error | string) {\n const e = typeof error === 'string' ? new Error(error) : error;\n span.recordException(e);\n span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });\n },\n end() {\n span.end();\n },\n };\n }\n\n return {\n getEventId: () => ctx.eventId,\n setInput(value: string) {\n input = value;\n },\n setProperty(key: string, value: string) {\n properties[key] = value;\n },\n setProperties(props: Record<string, string>) {\n Object.assign(properties, props);\n },\n vercelAiSdkMetadata() {\n return buildMetadata({\n userId: ctx.userId ?? 'unknown',\n convoId: ctx.convoId,\n eventName: ctx.event,\n eventId: ctx.eventId,\n properties,\n });\n },\n async run(fn) {\n try {\n return await Promise.resolve(withWorkflowContext(fn));\n } catch (err) {\n // Natively record the failure on the workflow span and ship it, so a\n // throwing interaction still lands in the trace as an errored span.\n failWorkflowSpan(err);\n throw err;\n }\n },\n withSpan(params, fn) {\n const name = typeof params === 'string' ? params : params.name;\n return Promise.resolve(withWorkflowContext(() => traceloop.withTask({ name }, fn)));\n },\n withTool(params, fn) {\n const name = toolName(params);\n const version = typeof params === 'string' ? undefined : params.version;\n return Promise.resolve(withWorkflowContext(() => traceloop.withTool({ name, version }, fn)));\n },\n startToolSpan,\n trackTool(params: TrackToolParams) {\n const span = startToolSpan({ name: params.name, properties: params.properties });\n if (params.input !== undefined) span.setInput(params.input);\n if (params.output !== undefined) span.setOutput(params.output);\n if (params.error) span.setError(params.error);\n span.end();\n },\n async finish(opts) {\n const output = typeof opts === 'string' ? opts : opts.output;\n if (typeof opts !== 'string' && opts.properties) Object.assign(properties, opts.properties);\n // No-op if run() already closed the span on error; otherwise end it now.\n // (Creates one if finish() is called alone, i.e. begin() → finish().)\n closeWorkflowSpan((span) => {\n if (traceContent) span.setAttribute(ENTITY_OUTPUT, output);\n });\n },\n };\n}\n\n/**\n * Inert Interaction for disabled instances. Preserves control flow — run() /\n * withTool() still execute their callback and rethrow errors — but never touches\n * the tracer. Required because the OTel provider is a process-wide singleton: a\n * disabled instance that created real spans would ship them through whichever\n * enabled instance registered the provider.\n */\nexport function createNoopInteraction(initial: TraceContext & { userId?: string }): Interaction {\n const ctx: TraceContext & { userId?: string } = {\n ...initial,\n eventId: initial.eventId ?? uuid(),\n };\n const properties: Record<string, string> = { ...(initial.properties ?? {}) };\n const noopToolSpan: ToolSpan = { setInput() {}, setOutput() {}, setError() {}, end() {} };\n\n return {\n getEventId: () => ctx.eventId,\n setInput() {},\n setProperty(key: string, value: string) {\n properties[key] = value;\n },\n setProperties(props: Record<string, string>) {\n Object.assign(properties, props);\n },\n vercelAiSdkMetadata() {\n return buildMetadata({\n userId: ctx.userId ?? 'unknown',\n convoId: ctx.convoId,\n eventName: ctx.event,\n eventId: ctx.eventId,\n properties,\n });\n },\n async run(fn) {\n return await fn();\n },\n async withSpan(_params, fn) {\n return await fn();\n },\n async withTool(_params, fn) {\n return await fn();\n },\n startToolSpan: () => noopToolSpan,\n trackTool() {},\n async finish() {},\n };\n}\n","/**\n * Morph Tracing — Vercel AI SDK helper.\n *\n * The Vercel AI SDK emits its own OpenTelemetry spans when you pass\n * `experimental_telemetry`. There is nothing to monkey-patch; instead you tag\n * each call with `metadata()` so Morph can attribute the resulting spans to a\n * user/conversation/event.\n *\n * @example\n * ```ts\n * import { generateText } from \"ai\";\n * import { metadata } from \"@morphllm/morphsdk/tracing/otel\";\n *\n * const res = await generateText({\n * model: openai(\"gpt-4o\"),\n * prompt: \"Hello!\",\n * experimental_telemetry: {\n * isEnabled: true,\n * metadata: metadata({ userId: \"user-123\", convoId: \"convo-456\" }),\n * },\n * });\n * ```\n */\nimport type { MetadataOptions } from './types.js';\n\n/**\n * Reserved metadata keys Morph owns. Custom `properties` can't overwrite these,\n * so attribution (user_id / convo_id / event_id) stays intact.\n *\n * The AI SDK stores metadata as `ai.telemetry.metadata.<key>`; Traceloop's span\n * processor copies them to `traceloop.association.properties.<key>`, which is\n * what ClickHouse views read. Use snake_case names (user_id, convo_id, …).\n */\nconst RESERVED_KEYS = new Set(['user_id', 'convo_id', 'event_id', 'event_name']);\n\nfunction uuid(): string {\n // Node 18+ and modern runtimes expose globalThis.crypto.randomUUID.\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n // Fallback: RFC4122-ish without crypto.\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => {\n const r = (Math.random() * 16) | 0;\n const v = ch === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Build the metadata object for the Vercel AI SDK's\n * `experimental_telemetry.metadata`. The values are propagated to every span the\n * AI SDK creates for that call. Generate a fresh `eventId` per call for grouping.\n */\nexport function metadata(opts: MetadataOptions): Record<string, string> {\n const result: Record<string, string> = {\n user_id: opts.userId,\n event_id: opts.eventId ?? uuid(),\n };\n if (opts.convoId) result.convo_id = opts.convoId;\n if (opts.eventName) result.event_name = opts.eventName;\n if (opts.properties) {\n for (const [key, value] of Object.entries(opts.properties)) {\n if (!RESERVED_KEYS.has(key)) result[key] = value;\n }\n }\n return result;\n}\n\nexport default { metadata };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,sCAAkC;AAClC,IAAAA,aAA2B;;;ACH3B,iBAA0D;AAC1D,gBAA2B;;;ACuB3B,IAAM,gBAAgB,oBAAI,IAAI,CAAC,WAAW,YAAY,YAAY,YAAY,CAAC;AAE/E,SAAS,OAAe;AAEtB,QAAM,IAAK,WAA0D;AACrE,MAAI,GAAG,WAAY,QAAO,EAAE,WAAW;AAEvC,SAAO,uCAAuC,QAAQ,SAAS,CAAC,OAAO;AACrE,UAAM,IAAK,KAAK,OAAO,IAAI,KAAM;AACjC,UAAM,IAAI,OAAO,MAAM,IAAK,IAAI,IAAO;AACvC,WAAO,EAAE,SAAS,EAAE;AAAA,EACtB,CAAC;AACH;AAOO,SAAS,SAAS,MAA+C;AACtE,QAAM,SAAiC;AAAA,IACrC,SAAS,KAAK;AAAA,IACd,UAAU,KAAK,WAAW,KAAK;AAAA,EACjC;AACA,MAAI,KAAK,QAAS,QAAO,WAAW,KAAK;AACzC,MAAI,KAAK,UAAW,QAAO,aAAa,KAAK;AAC7C,MAAI,KAAK,YAAY;AACnB,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,UAAU,GAAG;AAC1D,UAAI,CAAC,cAAc,IAAI,GAAG,EAAG,QAAO,GAAG,IAAI;AAAA,IAC7C;AAAA,EACF;AACA,SAAO;AACT;;;AD1CA,IAAM,QAAQ;AACd,IAAM,eAAe;AACrB,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,YAAY;AAElB,SAASC,QAAe;AACtB,QAAM,IAAK,WAA0D;AACrE,MAAI,GAAG,WAAY,QAAO,EAAE,WAAW;AACvC,SAAO,uBAAuB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AAA;AAAA;AAAA,EAMA,OAAO,mBAA2C,CAAC,GAAW;AAC5D,UAAM,MAAM,EAAE,QAAQ,iBAAiB,UAAU,SAAS,YAAY,iBAAiB;AACvF,QAAI,CAAC,KAAK,QAAS,QAAO,sBAAsB,GAAG;AACnD,WAAO,qBAAqB,KAAK,KAAK,IAAI,YAAY;AAAA,EACxD;AAAA;AAAA,EAGA,SAAS,MAA+C;AACtD,WAAO,SAAc,IAAI;AAAA,EAC3B;AAAA;AAAA,EAGA,oBACE,SACkD;AAIlD,UAAM,WACJ,SAAS,YACT,IAAI,kDAAkB;AAAA,MACpB,KAAK,GAAG,KAAK,IAAI,OAAO;AAAA,MACxB,SAAS,EAAE,eAAe,UAAU,KAAK,IAAI,MAAM,IAAI,GAAG,KAAK,IAAI,QAAQ;AAAA,IAC7E,CAAC;AACH,WAAiB,+BAAoB;AAAA,MACnC,QAAQ,KAAK,IAAI;AAAA,MACjB,SAAS,KAAK,IAAI;AAAA,MAClB,GAAG;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA,EAGA,MAAM,aAA4B;AAChC,QAAI,CAAC,KAAK,QAAS;AACnB,QAAI;AACF,YAAgB,sBAAW;AAAA,IAC7B,SAAS,KAAK;AACZ,UAAI,KAAK,IAAI,OAAO,+BAA+B,GAAG;AAAA,IACxD;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,WAA0B;AAC9B,UAAM,KAAK,WAAW;AAAA,EACxB;AACF;AAUO,SAAS,aAAa,SAA6B,CAAC,GAAiB;AAC1E,SAAO,IAAI,aAAa,MAAM;AAChC;","names":["traceloop","uuid"]}
|
package/dist/tracing/core.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as traceloop from '@traceloop/node-server-sdk';
|
|
2
2
|
import { Interaction, Tracer } from './interaction.js';
|
|
3
|
-
import {
|
|
3
|
+
import { MorphTracingConfig, TraceContext, MetadataOptions } from './types.js';
|
|
4
4
|
|
|
5
5
|
interface ResolvedConfig {
|
|
6
6
|
apiKey: string;
|
|
@@ -10,7 +10,6 @@ interface ResolvedConfig {
|
|
|
10
10
|
traceContent: boolean;
|
|
11
11
|
headers?: Record<string, string>;
|
|
12
12
|
debug: boolean;
|
|
13
|
-
evals?: EvalSelection;
|
|
14
13
|
}
|
|
15
14
|
/**
|
|
16
15
|
* Handle returned by {@link morphTracing}. Create interactions with `begin()`,
|
package/dist/tracing/core.js
CHANGED
package/dist/tracing/index.cjs
CHANGED
|
@@ -31,12 +31,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
31
31
|
var tracing_exports = {};
|
|
32
32
|
__export(tracing_exports, {
|
|
33
33
|
MorphTracing: () => MorphTracing,
|
|
34
|
-
REFLEX_RUN_ATTRIBUTE: () => REFLEX_RUN_ATTRIBUTE,
|
|
35
34
|
metadata: () => metadata,
|
|
36
35
|
morphTracing: () => morphTracing,
|
|
37
|
-
|
|
38
|
-
otel: () => otel_exports,
|
|
39
|
-
serializeEvals: () => serializeEvals
|
|
36
|
+
otel: () => otel_exports
|
|
40
37
|
});
|
|
41
38
|
module.exports = __toCommonJS(tracing_exports);
|
|
42
39
|
|
|
@@ -80,34 +77,6 @@ function metadata(opts) {
|
|
|
80
77
|
}
|
|
81
78
|
var otel_default = { metadata };
|
|
82
79
|
|
|
83
|
-
// tracing/reflex.ts
|
|
84
|
-
var REFLEX_RUN_ATTRIBUTE = "morph.reflex.run";
|
|
85
|
-
var USER_TRANSFORM = "user_message";
|
|
86
|
-
var ASSISTANT_TRANSFORM = "assistant_message";
|
|
87
|
-
function normalizeEvals(evals) {
|
|
88
|
-
if (!evals) return [];
|
|
89
|
-
const out = [];
|
|
90
|
-
const seen = /* @__PURE__ */ new Set();
|
|
91
|
-
const add = (models, transform) => {
|
|
92
|
-
if (!Array.isArray(models)) return;
|
|
93
|
-
for (const raw of models) {
|
|
94
|
-
const model = typeof raw === "string" ? raw.trim() : "";
|
|
95
|
-
if (!model) continue;
|
|
96
|
-
const key = `${model} ${transform}`;
|
|
97
|
-
if (seen.has(key)) continue;
|
|
98
|
-
seen.add(key);
|
|
99
|
-
out.push({ model, transform });
|
|
100
|
-
}
|
|
101
|
-
};
|
|
102
|
-
add(evals.user, USER_TRANSFORM);
|
|
103
|
-
add(evals.assistant, ASSISTANT_TRANSFORM);
|
|
104
|
-
return out;
|
|
105
|
-
}
|
|
106
|
-
function serializeEvals(evals) {
|
|
107
|
-
const entries = normalizeEvals(evals);
|
|
108
|
-
return entries.length ? JSON.stringify(entries) : null;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
80
|
// tracing/interaction.ts
|
|
112
81
|
var ASSOC = "traceloop.association.properties.";
|
|
113
82
|
var ENTITY_INPUT = "traceloop.entity.input";
|
|
@@ -143,7 +112,6 @@ function createInteractionApi(initial, traceContent, onClose) {
|
|
|
143
112
|
let input = initial.input;
|
|
144
113
|
let workflowSpan = null;
|
|
145
114
|
let finished = false;
|
|
146
|
-
const reflexRun = serializeEvals(initial.evals);
|
|
147
115
|
const withAssoc = (fn) => traceloop.withAssociationProperties(associationProps(ctx, properties), fn);
|
|
148
116
|
const workflowName = () => ctx.event ?? "interaction";
|
|
149
117
|
function ensureWorkflowSpan() {
|
|
@@ -154,7 +122,6 @@ function createInteractionApi(initial, traceContent, onClose) {
|
|
|
154
122
|
span.setAttribute(ASSOC + k, v);
|
|
155
123
|
}
|
|
156
124
|
if (traceContent && input) span.setAttribute(ENTITY_INPUT, input);
|
|
157
|
-
if (reflexRun) span.setAttribute(REFLEX_RUN_ATTRIBUTE, reflexRun);
|
|
158
125
|
workflowSpan = span;
|
|
159
126
|
return span;
|
|
160
127
|
}
|
|
@@ -335,8 +302,7 @@ var MorphTracing = class {
|
|
|
335
302
|
disableBatching: config.disableBatching ?? !isProd,
|
|
336
303
|
traceContent: config.traceContent ?? true,
|
|
337
304
|
headers: config.headers,
|
|
338
|
-
debug
|
|
339
|
-
evals: config.evals
|
|
305
|
+
debug
|
|
340
306
|
};
|
|
341
307
|
if (config.disabled) {
|
|
342
308
|
log(debug, "disabled \u2014 no tracing initialized");
|
|
@@ -391,9 +357,8 @@ var MorphTracing = class {
|
|
|
391
357
|
*/
|
|
392
358
|
begin(ctx) {
|
|
393
359
|
if (!this.enabled) return createNoopInteraction(ctx);
|
|
394
|
-
const resolved = { ...ctx, evals: ctx.evals ?? this.cfg.evals };
|
|
395
360
|
const interaction = createInteractionApi(
|
|
396
|
-
|
|
361
|
+
ctx,
|
|
397
362
|
this.cfg.traceContent,
|
|
398
363
|
(eventId) => this.active.delete(eventId)
|
|
399
364
|
);
|
|
@@ -450,11 +415,8 @@ function morphTracing(config = {}) {
|
|
|
450
415
|
// Annotate the CommonJS export names for ESM import in node:
|
|
451
416
|
0 && (module.exports = {
|
|
452
417
|
MorphTracing,
|
|
453
|
-
REFLEX_RUN_ATTRIBUTE,
|
|
454
418
|
metadata,
|
|
455
419
|
morphTracing,
|
|
456
|
-
|
|
457
|
-
otel,
|
|
458
|
-
serializeEvals
|
|
420
|
+
otel
|
|
459
421
|
});
|
|
460
422
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../tracing/index.ts","../../tracing/core.ts","../../tracing/interaction.ts","../../tracing/otel.ts","../../tracing/reflex.ts"],"sourcesContent":["/**\n * Morph Tracing — instrument the top AI SDKs and ship traces to Morph.\n *\n * @example\n * ```ts\n * import { morphTracing } from \"@morphllm/morphsdk/tracing\";\n *\n * const morph = morphTracing({ apiKey: process.env.MORPH_API_KEY });\n * // OpenAI / Anthropic / Vercel AI SDK calls are now traced automatically.\n *\n * const it = morph.begin({ userId: \"u1\", convoId: \"c1\", event: \"chat\" });\n * it.setInput(\"what's the weather?\");\n * const answer = await it.withTool({ name: \"get_weather\" }, () => getWeather());\n * await it.finish({ output: answer });\n * ```\n *\n * For the Vercel AI SDK, also see `@morphllm/morphsdk/tracing/otel`'s `metadata()` helper.\n */\nexport { morphTracing, MorphTracing } from './core.js';\nexport type { Interaction, Tracer } from './interaction.js';\nexport { metadata } from './otel.js';\nexport {\n REFLEX_RUN_ATTRIBUTE,\n normalizeEvals,\n serializeEvals,\n} from './reflex.js';\nexport type { EvalRunEntry } from './reflex.js';\nexport type {\n MorphTracingConfig,\n InstrumentModules,\n TraceContext,\n EvalSelection,\n SpanParams,\n ToolParams,\n ToolSpan,\n TrackToolParams,\n FinishOptions,\n MetadataOptions,\n} from './types.js';\n\nexport * as otel from './otel.js';\n","/**\n * Morph Tracing — core initialization.\n *\n * Thin Morph layer over OpenLLMetry / Traceloop. `morphTracing()` initializes\n * Traceloop with a JSON OTLP exporter pointed at Morph's ingest endpoint\n * (`${baseUrl}/v1/traces`, `Authorization: Bearer <apiKey>`) and returns a\n * `MorphTracing` handle for interactions and tools.\n *\n * We deliberately override Traceloop's default protobuf exporter with the\n * JSON-over-HTTP exporter so the ingest service can parse plain OTLP/JSON.\n */\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport * as traceloop from '@traceloop/node-server-sdk';\n\nimport {\n createInteractionApi,\n createNoopInteraction,\n type Interaction,\n type Tracer,\n} from './interaction.js';\nimport { metadata as buildMetadata } from './otel.js';\nimport type {\n EvalSelection,\n MetadataOptions,\n MorphTracingConfig,\n TraceContext,\n} from './types.js';\n\nconst DEFAULT_BASE_URL = 'https://api.morphllm.com';\n\nexport interface ResolvedConfig {\n apiKey: string;\n baseUrl: string;\n appName: string;\n disableBatching: boolean;\n traceContent: boolean;\n headers?: Record<string, string>;\n debug: boolean;\n evals?: EvalSelection;\n}\n\nfunction log(debug: boolean, ...args: unknown[]): void {\n if (debug) console.log('[morph-tracing]', ...args);\n}\n\n/**\n * Handle returned by {@link morphTracing}. Create interactions with `begin()`,\n * get a non-interactive `tracer()`, and flush/shutdown the exporter.\n */\nexport class MorphTracing {\n private readonly cfg: ResolvedConfig;\n private readonly active = new Map<string, Interaction>();\n readonly enabled: boolean;\n\n constructor(config: MorphTracingConfig = {}) {\n const debug = config.debug ?? process.env.MORPH_TRACING_DEBUG === '1';\n const apiKey = config.apiKey ?? process.env.MORPH_API_KEY ?? '';\n const baseUrlRaw =\n config.baseUrl ?? process.env.MORPH_TRACES_URL ?? DEFAULT_BASE_URL;\n const baseUrl = baseUrlRaw.replace(/\\/+$/, '');\n const isProd = process.env.NODE_ENV === 'production';\n\n this.cfg = {\n apiKey,\n baseUrl,\n appName: config.appName ?? process.env.npm_package_name ?? 'morph-app',\n disableBatching: config.disableBatching ?? !isProd,\n traceContent: config.traceContent ?? true,\n headers: config.headers,\n debug,\n evals: config.evals,\n };\n\n if (config.disabled) {\n log(debug, 'disabled — no tracing initialized');\n this.enabled = false;\n return;\n }\n if (!apiKey) {\n console.warn(\n '[morph-tracing] No API key (set MORPH_API_KEY or pass { apiKey }). Tracing disabled.',\n );\n this.enabled = false;\n return;\n }\n\n this.enabled = true;\n if (config.useExternalOtel) {\n // Customer drives their own NodeSDK; just register config, no SDK start.\n traceloop.initialize({\n baseUrl,\n apiKey,\n appName: this.cfg.appName,\n tracingEnabled: false,\n traceContent: this.cfg.traceContent,\n silenceInitializationMessage: true,\n });\n log(debug, 'external OTEL mode — add createSpanProcessor() to your NodeSDK');\n return;\n }\n\n const exporter = new OTLPTraceExporter({\n url: `${baseUrl}/v1/traces`,\n headers: { Authorization: `Bearer ${apiKey}`, ...this.cfg.headers },\n });\n\n traceloop.initialize({\n baseUrl,\n apiKey,\n appName: this.cfg.appName,\n exporter,\n disableBatch: this.cfg.disableBatching,\n traceContent: this.cfg.traceContent,\n instrumentModules: config.instrumentModules as NonNullable<\n Parameters<typeof traceloop.initialize>[0]\n >['instrumentModules'],\n tracingEnabled: true,\n traceloopSyncEnabled: false,\n silenceInitializationMessage: !debug,\n });\n log(\n debug,\n `initialized → ${baseUrl}/v1/traces (batching ${this.cfg.disableBatching ? 'off' : 'on'})`,\n );\n }\n\n /**\n * Begin a new traced interaction (a single user turn / agent run). On a\n * disabled instance this returns an inert no-op interaction — callbacks still\n * run, but no spans are created or shipped.\n */\n begin(ctx: TraceContext & { userId: string; event?: string }): Interaction {\n if (!this.enabled) return createNoopInteraction(ctx);\n // Per-interaction evals override the global default; omit both for none.\n const resolved = { ...ctx, evals: ctx.evals ?? this.cfg.evals };\n const interaction = createInteractionApi(resolved, this.cfg.traceContent, (eventId) =>\n this.active.delete(eventId),\n );\n this.active.set(interaction.getEventId()!, interaction);\n return interaction;\n }\n\n /** Look up an in-flight interaction by its eventId. */\n getActiveInteraction(eventId: string): Interaction | undefined {\n return this.active.get(eventId);\n }\n\n /**\n * Non-interactive tracer for batch jobs where you only care about\n * spans/token usage, not a user-facing interaction.\n */\n tracer(globalProperties: Record<string, string> = {}): Tracer {\n const ctx = { userId: globalProperties.userId ?? 'batch', properties: globalProperties };\n if (!this.enabled) return createNoopInteraction(ctx);\n return createInteractionApi(ctx, this.cfg.traceContent);\n }\n\n /** Build Vercel AI SDK telemetry metadata (see `@morphllm/morphsdk/tracing/otel`). */\n metadata(opts: MetadataOptions): Record<string, string> {\n return buildMetadata(opts);\n }\n\n /** Span processor for `useExternalOtel: true` integrations. */\n createSpanProcessor(\n options?: Parameters<typeof traceloop.createSpanProcessor>[0],\n ): ReturnType<typeof traceloop.createSpanProcessor> {\n // Traceloop's default exporter here is OTLP/protobuf, but Morph's ingest\n // parses OTLP/JSON only — supply the JSON exporter unless the caller\n // brings their own.\n const exporter =\n options?.exporter ??\n new OTLPTraceExporter({\n url: `${this.cfg.baseUrl}/v1/traces`,\n headers: { Authorization: `Bearer ${this.cfg.apiKey}`, ...this.cfg.headers },\n });\n return traceloop.createSpanProcessor({\n apiKey: this.cfg.apiKey,\n baseUrl: this.cfg.baseUrl,\n ...options,\n exporter,\n });\n }\n\n /** Flush any batched spans immediately. Safe to call when idle. */\n async forceFlush(): Promise<void> {\n if (!this.enabled) return;\n try {\n await traceloop.forceFlush();\n } catch (err) {\n log(this.cfg.debug, 'forceFlush error (ignored):', err);\n }\n }\n\n /** Flush and stop tracing. */\n async shutdown(): Promise<void> {\n await this.forceFlush();\n }\n}\n\n/**\n * Initialize Morph Tracing and auto-instrument supported AI SDKs.\n *\n * Requires the optional OpenTelemetry / Traceloop backends (see this module's\n * README). They install automatically with the SDK unless optional deps are\n * skipped; importing `/tracing` without them throws a module-not-found error\n * naming the missing package.\n */\nexport function morphTracing(config: MorphTracingConfig = {}): MorphTracing {\n return new MorphTracing(config);\n}\n","/**\n * Morph Tracing — interactions, tools, and manual spans.\n *\n * An `Interaction` is one user turn / agent run. It threads association\n * properties (user_id / convo_id / event_id) onto every span created inside it —\n * including the auto-instrumented LLM spans — so a whole conversation stitches\n * together in the Morph UI. Built on Traceloop's `withTask` / `withTool` and a\n * manual tracer for already-completed tool spans.\n */\nimport { context, SpanStatusCode, trace, type Span } from '@opentelemetry/api';\nimport * as traceloop from '@traceloop/node-server-sdk';\n\nimport { metadata as buildMetadata } from './otel.js';\nimport { REFLEX_RUN_ATTRIBUTE, serializeEvals } from './reflex.js';\nimport type {\n FinishOptions,\n SpanParams,\n ToolParams,\n ToolSpan,\n TrackToolParams,\n TraceContext,\n} from './types.js';\n\n// Traceloop semantic-convention attribute keys.\nconst ASSOC = 'traceloop.association.properties.';\nconst ENTITY_INPUT = 'traceloop.entity.input';\nconst ENTITY_OUTPUT = 'traceloop.entity.output';\nconst ENTITY_NAME = 'traceloop.entity.name';\nconst SPAN_KIND = 'traceloop.span.kind';\n\nfunction uuid(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n return 'xxxxxxxxxxxx4xxxyxxx'.replace(/[xy]/g, (ch) => {\n const r = (Math.random() * 16) | 0;\n return (ch === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n\nfunction asString(v: unknown): string {\n if (v == null) return '';\n return typeof v === 'string' ? v : JSON.stringify(v);\n}\n\nexport interface Interaction {\n getEventId(): string | undefined;\n setInput(input: string): void;\n setProperty(key: string, value: string): void;\n setProperties(props: Record<string, string>): void;\n /**\n * Run `fn` with this interaction's association properties active — required so\n * auto-instrumented OpenAI/Anthropic spans inherit user_id / convo_id / tags.\n */\n run<T>(fn: () => Promise<T> | T): Promise<T>;\n /** Run `fn` inside a traced task span; LLM calls within inherit attribution. */\n withSpan<T>(params: SpanParams | string, fn: () => Promise<T> | T): Promise<T>;\n /** Run `fn` inside a traced tool span. */\n withTool<T>(params: ToolParams | string, fn: () => Promise<T> | T): Promise<T>;\n /** Start a tool span you end manually. */\n startToolSpan(params: ToolParams | string): ToolSpan;\n /** Record an already-completed tool invocation. */\n trackTool(params: TrackToolParams): void;\n /** Metadata for the Vercel AI SDK `experimental_telemetry.metadata`. */\n vercelAiSdkMetadata(): Record<string, string>;\n /** End the interaction with its final output. */\n finish(opts: FinishOptions | string): Promise<void>;\n}\n\nexport type Tracer = Pick<Interaction, 'withSpan' | 'withTool' | 'startToolSpan' | 'trackTool'>;\n\n/** Build the association-property bag Traceloop propagates onto child spans. */\nfunction associationProps(\n ctx: TraceContext & { userId?: string },\n extra: Record<string, string>,\n): Record<string, string> {\n const props: Record<string, string> = { ...extra };\n if (ctx.userId) props.user_id = ctx.userId;\n if (ctx.convoId) props.convo_id = ctx.convoId;\n if (ctx.eventId) props.event_id = ctx.eventId;\n if (ctx.event) props.event_name = ctx.event;\n return props;\n}\n\nexport function createInteractionApi(\n initial: TraceContext & { userId?: string },\n traceContent: boolean,\n onClose?: (eventId: string) => void,\n): Interaction {\n const ctx: TraceContext & { userId?: string } = {\n ...initial,\n eventId: initial.eventId ?? uuid(),\n };\n const properties: Record<string, string> = { ...(initial.properties ?? {}) };\n let input = initial.input;\n let workflowSpan: Span | null = null;\n let finished = false;\n // Serialized once. Set as a raw attribute on the workflow span only — NOT an\n // association property, so it is not copied onto every child LLM span. Ingest\n // reads `morph.reflex.run` off the workflow-span to enqueue the evals.\n const reflexRun = serializeEvals(initial.evals);\n\n const withAssoc = <T>(fn: () => Promise<T> | T): Promise<T> | T =>\n traceloop.withAssociationProperties(associationProps(ctx, properties), fn);\n\n const workflowName = () => ctx.event ?? 'interaction';\n\n /** Open the interaction workflow span once; stays active until finish(). */\n function ensureWorkflowSpan(): Span {\n if (workflowSpan) return workflowSpan;\n const span = traceloop.getTraceloopTracer().startSpan(workflowName());\n span.setAttribute(SPAN_KIND, 'workflow');\n for (const [k, v] of Object.entries(associationProps(ctx, properties))) {\n span.setAttribute(ASSOC + k, v);\n }\n if (traceContent && input) span.setAttribute(ENTITY_INPUT, input);\n if (reflexRun) span.setAttribute(REFLEX_RUN_ATTRIBUTE, reflexRun);\n workflowSpan = span;\n return span;\n }\n\n /** Run fn with association props and the workflow span as the active parent. */\n function withWorkflowContext<T>(fn: () => Promise<T> | T): Promise<T> | T {\n return withAssoc(() => {\n const span = ensureWorkflowSpan();\n return context.with(trace.setSpan(context.active(), span), fn);\n });\n }\n\n /** Close the workflow span exactly once, applying final attributes. */\n function closeWorkflowSpan(apply: (span: Span) => void): void {\n if (finished) return;\n withAssoc(() => {\n const span = ensureWorkflowSpan();\n apply(span);\n span.end();\n });\n workflowSpan = null;\n finished = true;\n onClose?.(ctx.eventId!);\n }\n\n /** Record an exception + ERROR status on the workflow span, then close it. */\n function failWorkflowSpan(err: unknown): void {\n const e = err instanceof Error ? err : new Error(String(err));\n closeWorkflowSpan((span) => {\n span.recordException(e);\n span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });\n if (traceContent) span.setAttribute(ENTITY_OUTPUT, `ERROR: ${e.message}`);\n });\n }\n\n const toolName = (p: ToolParams | string) => (typeof p === 'string' ? p : p.name);\n\n function startToolSpan(params: ToolParams | string): ToolSpan {\n const name = toolName(params);\n const span: Span = traceloop.getTraceloopTracer().startSpan(name);\n span.setAttribute(SPAN_KIND, 'tool');\n span.setAttribute(ENTITY_NAME, name);\n for (const [k, v] of Object.entries(associationProps(ctx, properties))) {\n span.setAttribute(ASSOC + k, v);\n }\n if (typeof params !== 'string' && params.properties) {\n for (const [k, v] of Object.entries(params.properties)) span.setAttribute(k, v);\n }\n return {\n setInput(value: unknown) {\n if (traceContent) span.setAttribute(ENTITY_INPUT, asString(value));\n },\n setOutput(value: unknown) {\n if (traceContent) span.setAttribute(ENTITY_OUTPUT, asString(value));\n },\n setError(error: Error | string) {\n const e = typeof error === 'string' ? new Error(error) : error;\n span.recordException(e);\n span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });\n },\n end() {\n span.end();\n },\n };\n }\n\n return {\n getEventId: () => ctx.eventId,\n setInput(value: string) {\n input = value;\n },\n setProperty(key: string, value: string) {\n properties[key] = value;\n },\n setProperties(props: Record<string, string>) {\n Object.assign(properties, props);\n },\n vercelAiSdkMetadata() {\n return buildMetadata({\n userId: ctx.userId ?? 'unknown',\n convoId: ctx.convoId,\n eventName: ctx.event,\n eventId: ctx.eventId,\n properties,\n });\n },\n async run(fn) {\n try {\n return await Promise.resolve(withWorkflowContext(fn));\n } catch (err) {\n // Natively record the failure on the workflow span and ship it, so a\n // throwing interaction still lands in the trace as an errored span.\n failWorkflowSpan(err);\n throw err;\n }\n },\n withSpan(params, fn) {\n const name = typeof params === 'string' ? params : params.name;\n return Promise.resolve(withWorkflowContext(() => traceloop.withTask({ name }, fn)));\n },\n withTool(params, fn) {\n const name = toolName(params);\n const version = typeof params === 'string' ? undefined : params.version;\n return Promise.resolve(withWorkflowContext(() => traceloop.withTool({ name, version }, fn)));\n },\n startToolSpan,\n trackTool(params: TrackToolParams) {\n const span = startToolSpan({ name: params.name, properties: params.properties });\n if (params.input !== undefined) span.setInput(params.input);\n if (params.output !== undefined) span.setOutput(params.output);\n if (params.error) span.setError(params.error);\n span.end();\n },\n async finish(opts) {\n const output = typeof opts === 'string' ? opts : opts.output;\n if (typeof opts !== 'string' && opts.properties) Object.assign(properties, opts.properties);\n // No-op if run() already closed the span on error; otherwise end it now.\n // (Creates one if finish() is called alone, i.e. begin() → finish().)\n closeWorkflowSpan((span) => {\n if (traceContent) span.setAttribute(ENTITY_OUTPUT, output);\n });\n },\n };\n}\n\n/**\n * Inert Interaction for disabled instances. Preserves control flow — run() /\n * withTool() still execute their callback and rethrow errors — but never touches\n * the tracer. Required because the OTel provider is a process-wide singleton: a\n * disabled instance that created real spans would ship them through whichever\n * enabled instance registered the provider.\n */\nexport function createNoopInteraction(initial: TraceContext & { userId?: string }): Interaction {\n const ctx: TraceContext & { userId?: string } = {\n ...initial,\n eventId: initial.eventId ?? uuid(),\n };\n const properties: Record<string, string> = { ...(initial.properties ?? {}) };\n const noopToolSpan: ToolSpan = { setInput() {}, setOutput() {}, setError() {}, end() {} };\n\n return {\n getEventId: () => ctx.eventId,\n setInput() {},\n setProperty(key: string, value: string) {\n properties[key] = value;\n },\n setProperties(props: Record<string, string>) {\n Object.assign(properties, props);\n },\n vercelAiSdkMetadata() {\n return buildMetadata({\n userId: ctx.userId ?? 'unknown',\n convoId: ctx.convoId,\n eventName: ctx.event,\n eventId: ctx.eventId,\n properties,\n });\n },\n async run(fn) {\n return await fn();\n },\n async withSpan(_params, fn) {\n return await fn();\n },\n async withTool(_params, fn) {\n return await fn();\n },\n startToolSpan: () => noopToolSpan,\n trackTool() {},\n async finish() {},\n };\n}\n","/**\n * Morph Tracing — Vercel AI SDK helper.\n *\n * The Vercel AI SDK emits its own OpenTelemetry spans when you pass\n * `experimental_telemetry`. There is nothing to monkey-patch; instead you tag\n * each call with `metadata()` so Morph can attribute the resulting spans to a\n * user/conversation/event.\n *\n * @example\n * ```ts\n * import { generateText } from \"ai\";\n * import { metadata } from \"@morphllm/morphsdk/tracing/otel\";\n *\n * const res = await generateText({\n * model: openai(\"gpt-4o\"),\n * prompt: \"Hello!\",\n * experimental_telemetry: {\n * isEnabled: true,\n * metadata: metadata({ userId: \"user-123\", convoId: \"convo-456\" }),\n * },\n * });\n * ```\n */\nimport type { MetadataOptions } from './types.js';\n\n/**\n * Reserved metadata keys Morph owns. Custom `properties` can't overwrite these,\n * so attribution (user_id / convo_id / event_id) stays intact.\n *\n * The AI SDK stores metadata as `ai.telemetry.metadata.<key>`; Traceloop's span\n * processor copies them to `traceloop.association.properties.<key>`, which is\n * what ClickHouse views read. Use snake_case names (user_id, convo_id, …).\n */\nconst RESERVED_KEYS = new Set(['user_id', 'convo_id', 'event_id', 'event_name']);\n\nfunction uuid(): string {\n // Node 18+ and modern runtimes expose globalThis.crypto.randomUUID.\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n // Fallback: RFC4122-ish without crypto.\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => {\n const r = (Math.random() * 16) | 0;\n const v = ch === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Build the metadata object for the Vercel AI SDK's\n * `experimental_telemetry.metadata`. The values are propagated to every span the\n * AI SDK creates for that call. Generate a fresh `eventId` per call for grouping.\n */\nexport function metadata(opts: MetadataOptions): Record<string, string> {\n const result: Record<string, string> = {\n user_id: opts.userId,\n event_id: opts.eventId ?? uuid(),\n };\n if (opts.convoId) result.convo_id = opts.convoId;\n if (opts.eventName) result.event_name = opts.eventName;\n if (opts.properties) {\n for (const [key, value] of Object.entries(opts.properties)) {\n if (!RESERVED_KEYS.has(key)) result[key] = value;\n }\n }\n return result;\n}\n\nexport default { metadata };\n","/**\n * Morph Tracing — eval selection (which Reflexes to run on a trace).\n *\n * The public API is `evals` (see {@link EvalSelection}): `{ user, assistant }` choosing which role\n * each model classifies. We deliberately keep the public surface to plain nouns and hide the wire\n * detail: the selection is serialized onto a single\n * `morph.reflex.run` attribute on the interaction's workflow span (NOT an association property,\n * so it is not copied onto child LLM spans), and the per-role choice maps to the backend's\n * transform ids. Morph's ingest reads that attribute and runs the classifications async; results\n * land in the traces dashboard already labeled.\n */\nimport type { EvalSelection } from './types.js';\n\n/** Raw span attribute key carrying the serialized selection (internal wire detail). */\nexport const REFLEX_RUN_ATTRIBUTE = 'morph.reflex.run';\n\n// Public role → backend transform id. `user` classifies the user's message, `assistant` the\n// agent's output. (Whole-conversation evals are not exposed yet.)\nconst USER_TRANSFORM = 'user_message';\nconst ASSISTANT_TRANSFORM = 'assistant_message';\n\n/** One serialized entry on the wire: the model alias and the transform to run it on. */\nexport interface EvalRunEntry {\n model: string;\n transform: string;\n}\n\n/**\n * Normalize a public `evals` selection into deduped `{ model, transform }` wire entries.\n * `user` models run on the user turn, `assistant` models on the agent turn. Drops blank models;\n * preserves first-seen order. Exported for tests and so callers can see exactly what runs.\n */\nexport function normalizeEvals(evals: EvalSelection | undefined): EvalRunEntry[] {\n if (!evals) return [];\n const out: EvalRunEntry[] = [];\n const seen = new Set<string>();\n const add = (models: string[] | undefined, transform: string): void => {\n // Guard against a non-array (e.g. an untyped JS caller passing { user: \"jailbreak\" }) — iterating\n // a string would emit one bogus entry per character. Types forbid this; this is runtime defense.\n if (!Array.isArray(models)) return;\n for (const raw of models) {\n const model = typeof raw === 'string' ? raw.trim() : '';\n if (!model) continue;\n const key = `${model} ${transform}`;\n if (seen.has(key)) continue;\n seen.add(key);\n out.push({ model, transform });\n }\n };\n add(evals.user, USER_TRANSFORM);\n add(evals.assistant, ASSISTANT_TRANSFORM);\n return out;\n}\n\n/**\n * Serialize an `evals` selection to the `morph.reflex.run` attribute string, or `null` when\n * there is nothing to run (so the attribute is simply omitted and no classification is enqueued).\n */\nexport function serializeEvals(evals: EvalSelection | undefined): string | null {\n const entries = normalizeEvals(evals);\n return entries.length ? JSON.stringify(entries) : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWA,sCAAkC;AAClC,IAAAA,aAA2B;;;ACH3B,iBAA0D;AAC1D,gBAA2B;;;ACV3B;AAAA;AAAA;AAAA;AAAA;AAiCA,IAAM,gBAAgB,oBAAI,IAAI,CAAC,WAAW,YAAY,YAAY,YAAY,CAAC;AAE/E,SAAS,OAAe;AAEt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GA,MAAM,aAA4B;AAChC,QAAI,CAAC,KAAK,QAAS;AACnB,QAAI;AACF,YAAgB,sBAAW;AAAA,IAC7B,SAAS,KAAK;AACZ,UAAI,KAAK,IAAI,OAAO,+BAA+B,GAAG;AAAA,IACxD;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,WAA0B;AAC9B,UAAM,KAAK,WAAW;AAAA,EACxB;AACF;AAUO,SAAS,aAAa,SAA6B,CAAC,GAAiB;AAC1E,SAAO,IAAI,aAAa,MAAM;AAChC;","names":["traceloop","uuid"]}
|
|
1
|
+
{"version":3,"sources":["../../tracing/index.ts","../../tracing/core.ts","../../tracing/interaction.ts","../../tracing/otel.ts"],"sourcesContent":["/**\n * Morph Tracing — instrument the top AI SDKs and ship traces to Morph.\n *\n * @example\n * ```ts\n * import { morphTracing } from \"@morphllm/morphsdk/tracing\";\n *\n * const morph = morphTracing({ apiKey: process.env.MORPH_API_KEY });\n * // OpenAI / Anthropic / Vercel AI SDK calls are now traced automatically.\n *\n * const it = morph.begin({ userId: \"u1\", convoId: \"c1\", event: \"chat\" });\n * it.setInput(\"what's the weather?\");\n * const answer = await it.withTool({ name: \"get_weather\" }, () => getWeather());\n * await it.finish({ output: answer });\n * ```\n *\n * For the Vercel AI SDK, also see `@morphllm/morphsdk/tracing/otel`'s `metadata()` helper.\n */\nexport { morphTracing, MorphTracing } from './core.js';\nexport type { Interaction, Tracer } from './interaction.js';\nexport { metadata } from './otel.js';\nexport type {\n MorphTracingConfig,\n InstrumentModules,\n TraceContext,\n SpanParams,\n ToolParams,\n ToolSpan,\n TrackToolParams,\n FinishOptions,\n MetadataOptions,\n} from './types.js';\n\nexport * as otel from './otel.js';\n","/**\n * Morph Tracing — core initialization.\n *\n * Thin Morph layer over OpenLLMetry / Traceloop. `morphTracing()` initializes\n * Traceloop with a JSON OTLP exporter pointed at Morph's ingest endpoint\n * (`${baseUrl}/v1/traces`, `Authorization: Bearer <apiKey>`) and returns a\n * `MorphTracing` handle for interactions and tools.\n *\n * We deliberately override Traceloop's default protobuf exporter with the\n * JSON-over-HTTP exporter so the ingest service can parse plain OTLP/JSON.\n */\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport * as traceloop from '@traceloop/node-server-sdk';\n\nimport {\n createInteractionApi,\n createNoopInteraction,\n type Interaction,\n type Tracer,\n} from './interaction.js';\nimport { metadata as buildMetadata } from './otel.js';\nimport type {\n MetadataOptions,\n MorphTracingConfig,\n TraceContext,\n} from './types.js';\n\nconst DEFAULT_BASE_URL = 'https://api.morphllm.com';\n\nexport interface ResolvedConfig {\n apiKey: string;\n baseUrl: string;\n appName: string;\n disableBatching: boolean;\n traceContent: boolean;\n headers?: Record<string, string>;\n debug: boolean;\n}\n\nfunction log(debug: boolean, ...args: unknown[]): void {\n if (debug) console.log('[morph-tracing]', ...args);\n}\n\n/**\n * Handle returned by {@link morphTracing}. Create interactions with `begin()`,\n * get a non-interactive `tracer()`, and flush/shutdown the exporter.\n */\nexport class MorphTracing {\n private readonly cfg: ResolvedConfig;\n private readonly active = new Map<string, Interaction>();\n readonly enabled: boolean;\n\n constructor(config: MorphTracingConfig = {}) {\n const debug = config.debug ?? process.env.MORPH_TRACING_DEBUG === '1';\n const apiKey = config.apiKey ?? process.env.MORPH_API_KEY ?? '';\n const baseUrlRaw =\n config.baseUrl ?? process.env.MORPH_TRACES_URL ?? DEFAULT_BASE_URL;\n const baseUrl = baseUrlRaw.replace(/\\/+$/, '');\n const isProd = process.env.NODE_ENV === 'production';\n\n this.cfg = {\n apiKey,\n baseUrl,\n appName: config.appName ?? process.env.npm_package_name ?? 'morph-app',\n disableBatching: config.disableBatching ?? !isProd,\n traceContent: config.traceContent ?? true,\n headers: config.headers,\n debug,\n };\n\n if (config.disabled) {\n log(debug, 'disabled — no tracing initialized');\n this.enabled = false;\n return;\n }\n if (!apiKey) {\n console.warn(\n '[morph-tracing] No API key (set MORPH_API_KEY or pass { apiKey }). Tracing disabled.',\n );\n this.enabled = false;\n return;\n }\n\n this.enabled = true;\n if (config.useExternalOtel) {\n // Customer drives their own NodeSDK; just register config, no SDK start.\n traceloop.initialize({\n baseUrl,\n apiKey,\n appName: this.cfg.appName,\n tracingEnabled: false,\n traceContent: this.cfg.traceContent,\n silenceInitializationMessage: true,\n });\n log(debug, 'external OTEL mode — add createSpanProcessor() to your NodeSDK');\n return;\n }\n\n const exporter = new OTLPTraceExporter({\n url: `${baseUrl}/v1/traces`,\n headers: { Authorization: `Bearer ${apiKey}`, ...this.cfg.headers },\n });\n\n traceloop.initialize({\n baseUrl,\n apiKey,\n appName: this.cfg.appName,\n exporter,\n disableBatch: this.cfg.disableBatching,\n traceContent: this.cfg.traceContent,\n instrumentModules: config.instrumentModules as NonNullable<\n Parameters<typeof traceloop.initialize>[0]\n >['instrumentModules'],\n tracingEnabled: true,\n traceloopSyncEnabled: false,\n silenceInitializationMessage: !debug,\n });\n log(\n debug,\n `initialized → ${baseUrl}/v1/traces (batching ${this.cfg.disableBatching ? 'off' : 'on'})`,\n );\n }\n\n /**\n * Begin a new traced interaction (a single user turn / agent run). On a\n * disabled instance this returns an inert no-op interaction — callbacks still\n * run, but no spans are created or shipped.\n */\n begin(ctx: TraceContext & { userId: string; event?: string }): Interaction {\n if (!this.enabled) return createNoopInteraction(ctx);\n const interaction = createInteractionApi(ctx, this.cfg.traceContent, (eventId) =>\n this.active.delete(eventId),\n );\n this.active.set(interaction.getEventId()!, interaction);\n return interaction;\n }\n\n /** Look up an in-flight interaction by its eventId. */\n getActiveInteraction(eventId: string): Interaction | undefined {\n return this.active.get(eventId);\n }\n\n /**\n * Non-interactive tracer for batch jobs where you only care about\n * spans/token usage, not a user-facing interaction.\n */\n tracer(globalProperties: Record<string, string> = {}): Tracer {\n const ctx = { userId: globalProperties.userId ?? 'batch', properties: globalProperties };\n if (!this.enabled) return createNoopInteraction(ctx);\n return createInteractionApi(ctx, this.cfg.traceContent);\n }\n\n /** Build Vercel AI SDK telemetry metadata (see `@morphllm/morphsdk/tracing/otel`). */\n metadata(opts: MetadataOptions): Record<string, string> {\n return buildMetadata(opts);\n }\n\n /** Span processor for `useExternalOtel: true` integrations. */\n createSpanProcessor(\n options?: Parameters<typeof traceloop.createSpanProcessor>[0],\n ): ReturnType<typeof traceloop.createSpanProcessor> {\n // Traceloop's default exporter here is OTLP/protobuf, but Morph's ingest\n // parses OTLP/JSON only — supply the JSON exporter unless the caller\n // brings their own.\n const exporter =\n options?.exporter ??\n new OTLPTraceExporter({\n url: `${this.cfg.baseUrl}/v1/traces`,\n headers: { Authorization: `Bearer ${this.cfg.apiKey}`, ...this.cfg.headers },\n });\n return traceloop.createSpanProcessor({\n apiKey: this.cfg.apiKey,\n baseUrl: this.cfg.baseUrl,\n ...options,\n exporter,\n });\n }\n\n /** Flush any batched spans immediately. Safe to call when idle. */\n async forceFlush(): Promise<void> {\n if (!this.enabled) return;\n try {\n await traceloop.forceFlush();\n } catch (err) {\n log(this.cfg.debug, 'forceFlush error (ignored):', err);\n }\n }\n\n /** Flush and stop tracing. */\n async shutdown(): Promise<void> {\n await this.forceFlush();\n }\n}\n\n/**\n * Initialize Morph Tracing and auto-instrument supported AI SDKs.\n *\n * Requires the optional OpenTelemetry / Traceloop backends (see this module's\n * README). They install automatically with the SDK unless optional deps are\n * skipped; importing `/tracing` without them throws a module-not-found error\n * naming the missing package.\n */\nexport function morphTracing(config: MorphTracingConfig = {}): MorphTracing {\n return new MorphTracing(config);\n}\n","/**\n * Morph Tracing — interactions, tools, and manual spans.\n *\n * An `Interaction` is one user turn / agent run. It threads association\n * properties (user_id / convo_id / event_id) onto every span created inside it —\n * including the auto-instrumented LLM spans — so a whole conversation stitches\n * together in the Morph UI. Built on Traceloop's `withTask` / `withTool` and a\n * manual tracer for already-completed tool spans.\n */\nimport { context, SpanStatusCode, trace, type Span } from '@opentelemetry/api';\nimport * as traceloop from '@traceloop/node-server-sdk';\n\nimport { metadata as buildMetadata } from './otel.js';\nimport type {\n FinishOptions,\n SpanParams,\n ToolParams,\n ToolSpan,\n TrackToolParams,\n TraceContext,\n} from './types.js';\n\n// Traceloop semantic-convention attribute keys.\nconst ASSOC = 'traceloop.association.properties.';\nconst ENTITY_INPUT = 'traceloop.entity.input';\nconst ENTITY_OUTPUT = 'traceloop.entity.output';\nconst ENTITY_NAME = 'traceloop.entity.name';\nconst SPAN_KIND = 'traceloop.span.kind';\n\nfunction uuid(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n return 'xxxxxxxxxxxx4xxxyxxx'.replace(/[xy]/g, (ch) => {\n const r = (Math.random() * 16) | 0;\n return (ch === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n\nfunction asString(v: unknown): string {\n if (v == null) return '';\n return typeof v === 'string' ? v : JSON.stringify(v);\n}\n\nexport interface Interaction {\n getEventId(): string | undefined;\n setInput(input: string): void;\n setProperty(key: string, value: string): void;\n setProperties(props: Record<string, string>): void;\n /**\n * Run `fn` with this interaction's association properties active — required so\n * auto-instrumented OpenAI/Anthropic spans inherit user_id / convo_id / tags.\n */\n run<T>(fn: () => Promise<T> | T): Promise<T>;\n /** Run `fn` inside a traced task span; LLM calls within inherit attribution. */\n withSpan<T>(params: SpanParams | string, fn: () => Promise<T> | T): Promise<T>;\n /** Run `fn` inside a traced tool span. */\n withTool<T>(params: ToolParams | string, fn: () => Promise<T> | T): Promise<T>;\n /** Start a tool span you end manually. */\n startToolSpan(params: ToolParams | string): ToolSpan;\n /** Record an already-completed tool invocation. */\n trackTool(params: TrackToolParams): void;\n /** Metadata for the Vercel AI SDK `experimental_telemetry.metadata`. */\n vercelAiSdkMetadata(): Record<string, string>;\n /** End the interaction with its final output. */\n finish(opts: FinishOptions | string): Promise<void>;\n}\n\nexport type Tracer = Pick<Interaction, 'withSpan' | 'withTool' | 'startToolSpan' | 'trackTool'>;\n\n/** Build the association-property bag Traceloop propagates onto child spans. */\nfunction associationProps(\n ctx: TraceContext & { userId?: string },\n extra: Record<string, string>,\n): Record<string, string> {\n const props: Record<string, string> = { ...extra };\n if (ctx.userId) props.user_id = ctx.userId;\n if (ctx.convoId) props.convo_id = ctx.convoId;\n if (ctx.eventId) props.event_id = ctx.eventId;\n if (ctx.event) props.event_name = ctx.event;\n return props;\n}\n\nexport function createInteractionApi(\n initial: TraceContext & { userId?: string },\n traceContent: boolean,\n onClose?: (eventId: string) => void,\n): Interaction {\n const ctx: TraceContext & { userId?: string } = {\n ...initial,\n eventId: initial.eventId ?? uuid(),\n };\n const properties: Record<string, string> = { ...(initial.properties ?? {}) };\n let input = initial.input;\n let workflowSpan: Span | null = null;\n let finished = false;\n\n const withAssoc = <T>(fn: () => Promise<T> | T): Promise<T> | T =>\n traceloop.withAssociationProperties(associationProps(ctx, properties), fn);\n\n const workflowName = () => ctx.event ?? 'interaction';\n\n /** Open the interaction workflow span once; stays active until finish(). */\n function ensureWorkflowSpan(): Span {\n if (workflowSpan) return workflowSpan;\n const span = traceloop.getTraceloopTracer().startSpan(workflowName());\n span.setAttribute(SPAN_KIND, 'workflow');\n for (const [k, v] of Object.entries(associationProps(ctx, properties))) {\n span.setAttribute(ASSOC + k, v);\n }\n if (traceContent && input) span.setAttribute(ENTITY_INPUT, input);\n workflowSpan = span;\n return span;\n }\n\n /** Run fn with association props and the workflow span as the active parent. */\n function withWorkflowContext<T>(fn: () => Promise<T> | T): Promise<T> | T {\n return withAssoc(() => {\n const span = ensureWorkflowSpan();\n return context.with(trace.setSpan(context.active(), span), fn);\n });\n }\n\n /** Close the workflow span exactly once, applying final attributes. */\n function closeWorkflowSpan(apply: (span: Span) => void): void {\n if (finished) return;\n withAssoc(() => {\n const span = ensureWorkflowSpan();\n apply(span);\n span.end();\n });\n workflowSpan = null;\n finished = true;\n onClose?.(ctx.eventId!);\n }\n\n /** Record an exception + ERROR status on the workflow span, then close it. */\n function failWorkflowSpan(err: unknown): void {\n const e = err instanceof Error ? err : new Error(String(err));\n closeWorkflowSpan((span) => {\n span.recordException(e);\n span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });\n if (traceContent) span.setAttribute(ENTITY_OUTPUT, `ERROR: ${e.message}`);\n });\n }\n\n const toolName = (p: ToolParams | string) => (typeof p === 'string' ? p : p.name);\n\n function startToolSpan(params: ToolParams | string): ToolSpan {\n const name = toolName(params);\n const span: Span = traceloop.getTraceloopTracer().startSpan(name);\n span.setAttribute(SPAN_KIND, 'tool');\n span.setAttribute(ENTITY_NAME, name);\n for (const [k, v] of Object.entries(associationProps(ctx, properties))) {\n span.setAttribute(ASSOC + k, v);\n }\n if (typeof params !== 'string' && params.properties) {\n for (const [k, v] of Object.entries(params.properties)) span.setAttribute(k, v);\n }\n return {\n setInput(value: unknown) {\n if (traceContent) span.setAttribute(ENTITY_INPUT, asString(value));\n },\n setOutput(value: unknown) {\n if (traceContent) span.setAttribute(ENTITY_OUTPUT, asString(value));\n },\n setError(error: Error | string) {\n const e = typeof error === 'string' ? new Error(error) : error;\n span.recordException(e);\n span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });\n },\n end() {\n span.end();\n },\n };\n }\n\n return {\n getEventId: () => ctx.eventId,\n setInput(value: string) {\n input = value;\n },\n setProperty(key: string, value: string) {\n properties[key] = value;\n },\n setProperties(props: Record<string, string>) {\n Object.assign(properties, props);\n },\n vercelAiSdkMetadata() {\n return buildMetadata({\n userId: ctx.userId ?? 'unknown',\n convoId: ctx.convoId,\n eventName: ctx.event,\n eventId: ctx.eventId,\n properties,\n });\n },\n async run(fn) {\n try {\n return await Promise.resolve(withWorkflowContext(fn));\n } catch (err) {\n // Natively record the failure on the workflow span and ship it, so a\n // throwing interaction still lands in the trace as an errored span.\n failWorkflowSpan(err);\n throw err;\n }\n },\n withSpan(params, fn) {\n const name = typeof params === 'string' ? params : params.name;\n return Promise.resolve(withWorkflowContext(() => traceloop.withTask({ name }, fn)));\n },\n withTool(params, fn) {\n const name = toolName(params);\n const version = typeof params === 'string' ? undefined : params.version;\n return Promise.resolve(withWorkflowContext(() => traceloop.withTool({ name, version }, fn)));\n },\n startToolSpan,\n trackTool(params: TrackToolParams) {\n const span = startToolSpan({ name: params.name, properties: params.properties });\n if (params.input !== undefined) span.setInput(params.input);\n if (params.output !== undefined) span.setOutput(params.output);\n if (params.error) span.setError(params.error);\n span.end();\n },\n async finish(opts) {\n const output = typeof opts === 'string' ? opts : opts.output;\n if (typeof opts !== 'string' && opts.properties) Object.assign(properties, opts.properties);\n // No-op if run() already closed the span on error; otherwise end it now.\n // (Creates one if finish() is called alone, i.e. begin() → finish().)\n closeWorkflowSpan((span) => {\n if (traceContent) span.setAttribute(ENTITY_OUTPUT, output);\n });\n },\n };\n}\n\n/**\n * Inert Interaction for disabled instances. Preserves control flow — run() /\n * withTool() still execute their callback and rethrow errors — but never touches\n * the tracer. Required because the OTel provider is a process-wide singleton: a\n * disabled instance that created real spans would ship them through whichever\n * enabled instance registered the provider.\n */\nexport function createNoopInteraction(initial: TraceContext & { userId?: string }): Interaction {\n const ctx: TraceContext & { userId?: string } = {\n ...initial,\n eventId: initial.eventId ?? uuid(),\n };\n const properties: Record<string, string> = { ...(initial.properties ?? {}) };\n const noopToolSpan: ToolSpan = { setInput() {}, setOutput() {}, setError() {}, end() {} };\n\n return {\n getEventId: () => ctx.eventId,\n setInput() {},\n setProperty(key: string, value: string) {\n properties[key] = value;\n },\n setProperties(props: Record<string, string>) {\n Object.assign(properties, props);\n },\n vercelAiSdkMetadata() {\n return buildMetadata({\n userId: ctx.userId ?? 'unknown',\n convoId: ctx.convoId,\n eventName: ctx.event,\n eventId: ctx.eventId,\n properties,\n });\n },\n async run(fn) {\n return await fn();\n },\n async withSpan(_params, fn) {\n return await fn();\n },\n async withTool(_params, fn) {\n return await fn();\n },\n startToolSpan: () => noopToolSpan,\n trackTool() {},\n async finish() {},\n };\n}\n","/**\n * Morph Tracing — Vercel AI SDK helper.\n *\n * The Vercel AI SDK emits its own OpenTelemetry spans when you pass\n * `experimental_telemetry`. There is nothing to monkey-patch; instead you tag\n * each call with `metadata()` so Morph can attribute the resulting spans to a\n * user/conversation/event.\n *\n * @example\n * ```ts\n * import { generateText } from \"ai\";\n * import { metadata } from \"@morphllm/morphsdk/tracing/otel\";\n *\n * const res = await generateText({\n * model: openai(\"gpt-4o\"),\n * prompt: \"Hello!\",\n * experimental_telemetry: {\n * isEnabled: true,\n * metadata: metadata({ userId: \"user-123\", convoId: \"convo-456\" }),\n * },\n * });\n * ```\n */\nimport type { MetadataOptions } from './types.js';\n\n/**\n * Reserved metadata keys Morph owns. Custom `properties` can't overwrite these,\n * so attribution (user_id / convo_id / event_id) stays intact.\n *\n * The AI SDK stores metadata as `ai.telemetry.metadata.<key>`; Traceloop's span\n * processor copies them to `traceloop.association.properties.<key>`, which is\n * what ClickHouse views read. Use snake_case names (user_id, convo_id, …).\n */\nconst RESERVED_KEYS = new Set(['user_id', 'convo_id', 'event_id', 'event_name']);\n\nfunction uuid(): string {\n // Node 18+ and modern runtimes expose globalThis.crypto.randomUUID.\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n // Fallback: RFC4122-ish without crypto.\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => {\n const r = (Math.random() * 16) | 0;\n const v = ch === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Build the metadata object for the Vercel AI SDK's\n * `experimental_telemetry.metadata`. The values are propagated to every span the\n * AI SDK creates for that call. Generate a fresh `eventId` per call for grouping.\n */\nexport function metadata(opts: MetadataOptions): Record<string, string> {\n const result: Record<string, string> = {\n user_id: opts.userId,\n event_id: opts.eventId ?? uuid(),\n };\n if (opts.convoId) result.convo_id = opts.convoId;\n if (opts.eventName) result.event_name = opts.eventName;\n if (opts.properties) {\n for (const [key, value] of Object.entries(opts.properties)) {\n if (!RESERVED_KEYS.has(key)) result[key] = value;\n }\n }\n return result;\n}\n\nexport default { metadata };\n"],"mappings":";;;;;;;;;;;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iBAAiB,UAAU,SAAS,YAAY,iBAAiB;AACvF,QAAI,CAAC,KAAK,QAAS,QAAO,sBAAsB,GAAG;AACnD,WAAO,qBAAqB,KAAK,KAAK,IAAI,YAAY;AAAA,EACxD;AAAA;AAAA,EAGA,SAAS,MAA+C;AACtD,WAAO,SAAc,IAAI;AAAA,EAC3B;AAAA;AAAA,EAGA,oBACE,SACkD;AAIlD,UAAM,WACJ,SAAS,YACT,IAAI,kDAAkB;AAAA,MACpB,KAAK,GAAG,KAAK,IAAI,OAAO;AAAA,MACxB,SAAS,EAAE,eAAe,UAAU,KAAK,IAAI,MAAM,IAAI,GAAG,KAAK,IAAI,QAAQ;AAAA,IAC7E,CAAC;AACH,WAAiB,+BAAoB;AAAA,MACnC,QAAQ,KAAK,IAAI;AAAA,MACjB,SAAS,KAAK,IAAI;AAAA,MAClB,GAAG;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA,EAGA,MAAM,aAA4B;AAChC,QAAI,CAAC,KAAK,QAAS;AACnB,QAAI;AACF,YAAgB,sBAAW;AAAA,IAC7B,SAAS,KAAK;AACZ,UAAI,KAAK,IAAI,OAAO,+BAA+B,GAAG;AAAA,IACxD;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,WAA0B;AAC9B,UAAM,KAAK,WAAW;AAAA,EACxB;AACF;AAUO,SAAS,aAAa,SAA6B,CAAC,GAAiB;AAC1E,SAAO,IAAI,aAAa,MAAM;AAChC;","names":["traceloop","uuid"]}
|
package/dist/tracing/index.d.ts
CHANGED
|
@@ -1,39 +1,5 @@
|
|
|
1
1
|
export { MorphTracing, morphTracing } from './core.js';
|
|
2
2
|
export { Interaction, Tracer } from './interaction.js';
|
|
3
3
|
export { m as metadata, o as otel } from '../otel-CG0uqXjp.js';
|
|
4
|
-
import { EvalSelection } from './types.js';
|
|
5
4
|
export { FinishOptions, InstrumentModules, MetadataOptions, MorphTracingConfig, SpanParams, ToolParams, ToolSpan, TraceContext, TrackToolParams } from './types.js';
|
|
6
5
|
import '@traceloop/node-server-sdk';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Morph Tracing — eval selection (which Reflexes to run on a trace).
|
|
10
|
-
*
|
|
11
|
-
* The public API is `evals` (see {@link EvalSelection}): `{ user, assistant }` choosing which role
|
|
12
|
-
* each model classifies. We deliberately keep the public surface to plain nouns and hide the wire
|
|
13
|
-
* detail: the selection is serialized onto a single
|
|
14
|
-
* `morph.reflex.run` attribute on the interaction's workflow span (NOT an association property,
|
|
15
|
-
* so it is not copied onto child LLM spans), and the per-role choice maps to the backend's
|
|
16
|
-
* transform ids. Morph's ingest reads that attribute and runs the classifications async; results
|
|
17
|
-
* land in the traces dashboard already labeled.
|
|
18
|
-
*/
|
|
19
|
-
|
|
20
|
-
/** Raw span attribute key carrying the serialized selection (internal wire detail). */
|
|
21
|
-
declare const REFLEX_RUN_ATTRIBUTE = "morph.reflex.run";
|
|
22
|
-
/** One serialized entry on the wire: the model alias and the transform to run it on. */
|
|
23
|
-
interface EvalRunEntry {
|
|
24
|
-
model: string;
|
|
25
|
-
transform: string;
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Normalize a public `evals` selection into deduped `{ model, transform }` wire entries.
|
|
29
|
-
* `user` models run on the user turn, `assistant` models on the agent turn. Drops blank models;
|
|
30
|
-
* preserves first-seen order. Exported for tests and so callers can see exactly what runs.
|
|
31
|
-
*/
|
|
32
|
-
declare function normalizeEvals(evals: EvalSelection | undefined): EvalRunEntry[];
|
|
33
|
-
/**
|
|
34
|
-
* Serialize an `evals` selection to the `morph.reflex.run` attribute string, or `null` when
|
|
35
|
-
* there is nothing to run (so the attribute is simply omitted and no classification is enqueued).
|
|
36
|
-
*/
|
|
37
|
-
declare function serializeEvals(evals: EvalSelection | undefined): string | null;
|
|
38
|
-
|
|
39
|
-
export { type EvalRunEntry, EvalSelection, REFLEX_RUN_ATTRIBUTE, normalizeEvals, serializeEvals };
|
package/dist/tracing/index.js
CHANGED
|
@@ -1,12 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
MorphTracing,
|
|
3
3
|
morphTracing
|
|
4
|
-
} from "../chunk-
|
|
5
|
-
import
|
|
6
|
-
REFLEX_RUN_ATTRIBUTE,
|
|
7
|
-
normalizeEvals,
|
|
8
|
-
serializeEvals
|
|
9
|
-
} from "../chunk-ATAKRJQZ.js";
|
|
4
|
+
} from "../chunk-EMURAU6J.js";
|
|
5
|
+
import "../chunk-IDMKQWQG.js";
|
|
10
6
|
import {
|
|
11
7
|
metadata,
|
|
12
8
|
otel_exports
|
|
@@ -14,11 +10,8 @@ import {
|
|
|
14
10
|
import "../chunk-PZ5AY32C.js";
|
|
15
11
|
export {
|
|
16
12
|
MorphTracing,
|
|
17
|
-
REFLEX_RUN_ATTRIBUTE,
|
|
18
13
|
metadata,
|
|
19
14
|
morphTracing,
|
|
20
|
-
|
|
21
|
-
otel_exports as otel,
|
|
22
|
-
serializeEvals
|
|
15
|
+
otel_exports as otel
|
|
23
16
|
};
|
|
24
17
|
//# sourceMappingURL=index.js.map
|