@morsehq-dev/sdk 0.4.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +294 -0
  3. package/dist/anthropic/index.cjs +39 -0
  4. package/dist/anthropic/index.cjs.map +1 -0
  5. package/dist/anthropic/index.d.cts +213 -0
  6. package/dist/anthropic/index.d.ts +213 -0
  7. package/dist/anthropic/index.js +6 -0
  8. package/dist/anthropic/index.js.map +1 -0
  9. package/dist/anthropic-agent-sdk/index.cjs +744 -0
  10. package/dist/anthropic-agent-sdk/index.cjs.map +1 -0
  11. package/dist/anthropic-agent-sdk/index.d.cts +371 -0
  12. package/dist/anthropic-agent-sdk/index.d.ts +371 -0
  13. package/dist/anthropic-agent-sdk/index.js +735 -0
  14. package/dist/anthropic-agent-sdk/index.js.map +1 -0
  15. package/dist/browser/anthropic/index.cjs +39 -0
  16. package/dist/browser/anthropic/index.cjs.map +1 -0
  17. package/dist/browser/anthropic/index.js +6 -0
  18. package/dist/browser/anthropic/index.js.map +1 -0
  19. package/dist/browser/anthropic-agent-sdk/index.cjs +744 -0
  20. package/dist/browser/anthropic-agent-sdk/index.cjs.map +1 -0
  21. package/dist/browser/anthropic-agent-sdk/index.js +735 -0
  22. package/dist/browser/anthropic-agent-sdk/index.js.map +1 -0
  23. package/dist/browser/chunk-3643DC7K.cjs +365 -0
  24. package/dist/browser/chunk-3643DC7K.cjs.map +1 -0
  25. package/dist/browser/chunk-4FALQMOZ.js +232 -0
  26. package/dist/browser/chunk-4FALQMOZ.js.map +1 -0
  27. package/dist/browser/chunk-5J2QBK75.js +884 -0
  28. package/dist/browser/chunk-5J2QBK75.js.map +1 -0
  29. package/dist/browser/chunk-7MSXWGAH.js +53 -0
  30. package/dist/browser/chunk-7MSXWGAH.js.map +1 -0
  31. package/dist/browser/chunk-A24L5N5N.js +596 -0
  32. package/dist/browser/chunk-A24L5N5N.js.map +1 -0
  33. package/dist/browser/chunk-B7DEUDP6.cjs +177 -0
  34. package/dist/browser/chunk-B7DEUDP6.cjs.map +1 -0
  35. package/dist/browser/chunk-F6CJACNH.cjs +604 -0
  36. package/dist/browser/chunk-F6CJACNH.cjs.map +1 -0
  37. package/dist/browser/chunk-JBOYFQSB.js +412 -0
  38. package/dist/browser/chunk-JBOYFQSB.js.map +1 -0
  39. package/dist/browser/chunk-KRBADE6R.cjs +183 -0
  40. package/dist/browser/chunk-KRBADE6R.cjs.map +1 -0
  41. package/dist/browser/chunk-MCJYZH6W.cjs +415 -0
  42. package/dist/browser/chunk-MCJYZH6W.cjs.map +1 -0
  43. package/dist/browser/chunk-NQG2IAQS.js +178 -0
  44. package/dist/browser/chunk-NQG2IAQS.js.map +1 -0
  45. package/dist/browser/chunk-O4HG3OSK.cjs +929 -0
  46. package/dist/browser/chunk-O4HG3OSK.cjs.map +1 -0
  47. package/dist/browser/chunk-QWRQJO57.js +363 -0
  48. package/dist/browser/chunk-QWRQJO57.js.map +1 -0
  49. package/dist/browser/chunk-SWQOPFE4.cjs +234 -0
  50. package/dist/browser/chunk-SWQOPFE4.cjs.map +1 -0
  51. package/dist/browser/chunk-TYDG747E.js +171 -0
  52. package/dist/browser/chunk-TYDG747E.js.map +1 -0
  53. package/dist/browser/chunk-TZRSDDFP.cjs +56 -0
  54. package/dist/browser/chunk-TZRSDDFP.cjs.map +1 -0
  55. package/dist/browser/index.cjs +587 -0
  56. package/dist/browser/index.cjs.map +1 -0
  57. package/dist/browser/index.js +522 -0
  58. package/dist/browser/index.js.map +1 -0
  59. package/dist/browser/integrations/pino.cjs +89 -0
  60. package/dist/browser/integrations/pino.cjs.map +1 -0
  61. package/dist/browser/integrations/pino.js +86 -0
  62. package/dist/browser/integrations/pino.js.map +1 -0
  63. package/dist/browser/langchain/index.cjs +535 -0
  64. package/dist/browser/langchain/index.cjs.map +1 -0
  65. package/dist/browser/langchain/index.js +528 -0
  66. package/dist/browser/langchain/index.js.map +1 -0
  67. package/dist/browser/langgraph/index.cjs +377 -0
  68. package/dist/browser/langgraph/index.cjs.map +1 -0
  69. package/dist/browser/langgraph/index.js +371 -0
  70. package/dist/browser/langgraph/index.js.map +1 -0
  71. package/dist/browser/openai/index.cjs +125 -0
  72. package/dist/browser/openai/index.cjs.map +1 -0
  73. package/dist/browser/openai/index.js +122 -0
  74. package/dist/browser/openai/index.js.map +1 -0
  75. package/dist/browser/openai-agents/index.cjs +689 -0
  76. package/dist/browser/openai-agents/index.cjs.map +1 -0
  77. package/dist/browser/openai-agents/index.js +678 -0
  78. package/dist/browser/openai-agents/index.js.map +1 -0
  79. package/dist/browser/vercel-ai/index.cjs +233 -0
  80. package/dist/browser/vercel-ai/index.cjs.map +1 -0
  81. package/dist/browser/vercel-ai/index.js +231 -0
  82. package/dist/browser/vercel-ai/index.js.map +1 -0
  83. package/dist/chunk-4R4SHGOK.js +363 -0
  84. package/dist/chunk-4R4SHGOK.js.map +1 -0
  85. package/dist/chunk-7EO7MQBA.cjs +183 -0
  86. package/dist/chunk-7EO7MQBA.cjs.map +1 -0
  87. package/dist/chunk-7YCENA54.cjs +604 -0
  88. package/dist/chunk-7YCENA54.cjs.map +1 -0
  89. package/dist/chunk-CKFOGDUF.js +596 -0
  90. package/dist/chunk-CKFOGDUF.js.map +1 -0
  91. package/dist/chunk-FJUNILZT.cjs +1324 -0
  92. package/dist/chunk-FJUNILZT.cjs.map +1 -0
  93. package/dist/chunk-HDAFUKQ3.js +171 -0
  94. package/dist/chunk-HDAFUKQ3.js.map +1 -0
  95. package/dist/chunk-KBWPNIH4.cjs +234 -0
  96. package/dist/chunk-KBWPNIH4.cjs.map +1 -0
  97. package/dist/chunk-KJEO52QS.cjs +365 -0
  98. package/dist/chunk-KJEO52QS.cjs.map +1 -0
  99. package/dist/chunk-KZBCOZIQ.cjs +177 -0
  100. package/dist/chunk-KZBCOZIQ.cjs.map +1 -0
  101. package/dist/chunk-ME5JALGT.js +53 -0
  102. package/dist/chunk-ME5JALGT.js.map +1 -0
  103. package/dist/chunk-PVHDEPRE.cjs +56 -0
  104. package/dist/chunk-PVHDEPRE.cjs.map +1 -0
  105. package/dist/chunk-RTL23YOQ.js +178 -0
  106. package/dist/chunk-RTL23YOQ.js.map +1 -0
  107. package/dist/chunk-TQWI4UYO.js +1277 -0
  108. package/dist/chunk-TQWI4UYO.js.map +1 -0
  109. package/dist/chunk-VXDBDPDR.cjs +415 -0
  110. package/dist/chunk-VXDBDPDR.cjs.map +1 -0
  111. package/dist/chunk-XTKMUJWI.js +232 -0
  112. package/dist/chunk-XTKMUJWI.js.map +1 -0
  113. package/dist/chunk-ZKUGOWER.js +412 -0
  114. package/dist/chunk-ZKUGOWER.js.map +1 -0
  115. package/dist/index.cjs +843 -0
  116. package/dist/index.cjs.map +1 -0
  117. package/dist/index.d.cts +464 -0
  118. package/dist/index.d.ts +464 -0
  119. package/dist/index.js +778 -0
  120. package/dist/index.js.map +1 -0
  121. package/dist/integrations/pino.cjs +89 -0
  122. package/dist/integrations/pino.cjs.map +1 -0
  123. package/dist/integrations/pino.d.cts +65 -0
  124. package/dist/integrations/pino.d.ts +65 -0
  125. package/dist/integrations/pino.js +86 -0
  126. package/dist/integrations/pino.js.map +1 -0
  127. package/dist/langchain/index.cjs +535 -0
  128. package/dist/langchain/index.cjs.map +1 -0
  129. package/dist/langchain/index.d.cts +265 -0
  130. package/dist/langchain/index.d.ts +265 -0
  131. package/dist/langchain/index.js +528 -0
  132. package/dist/langchain/index.js.map +1 -0
  133. package/dist/langgraph/index.cjs +377 -0
  134. package/dist/langgraph/index.cjs.map +1 -0
  135. package/dist/langgraph/index.d.cts +324 -0
  136. package/dist/langgraph/index.d.ts +324 -0
  137. package/dist/langgraph/index.js +371 -0
  138. package/dist/langgraph/index.js.map +1 -0
  139. package/dist/openai/index.cjs +125 -0
  140. package/dist/openai/index.cjs.map +1 -0
  141. package/dist/openai/index.d.cts +136 -0
  142. package/dist/openai/index.d.ts +136 -0
  143. package/dist/openai/index.js +122 -0
  144. package/dist/openai/index.js.map +1 -0
  145. package/dist/openai-agents/index.cjs +689 -0
  146. package/dist/openai-agents/index.cjs.map +1 -0
  147. package/dist/openai-agents/index.d.cts +502 -0
  148. package/dist/openai-agents/index.d.ts +502 -0
  149. package/dist/openai-agents/index.js +678 -0
  150. package/dist/openai-agents/index.js.map +1 -0
  151. package/dist/spans-DZtMuBvc.d.cts +73 -0
  152. package/dist/spans-DZtMuBvc.d.ts +73 -0
  153. package/dist/tracing-BYAqjT5Q.d.cts +114 -0
  154. package/dist/tracing-rz9cWQ8d.d.ts +114 -0
  155. package/dist/vercel-ai/index.cjs +233 -0
  156. package/dist/vercel-ai/index.cjs.map +1 -0
  157. package/dist/vercel-ai/index.d.cts +93 -0
  158. package/dist/vercel-ai/index.d.ts +93 -0
  159. package/dist/vercel-ai/index.js +231 -0
  160. package/dist/vercel-ai/index.js.map +1 -0
  161. package/package.json +182 -0
@@ -0,0 +1,744 @@
1
+ 'use strict';
2
+
3
+ var chunk7YCENA54_cjs = require('../chunk-7YCENA54.cjs');
4
+ var chunkVXDBDPDR_cjs = require('../chunk-VXDBDPDR.cjs');
5
+ var chunkKZBCOZIQ_cjs = require('../chunk-KZBCOZIQ.cjs');
6
+ var chunk7EO7MQBA_cjs = require('../chunk-7EO7MQBA.cjs');
7
+ var chunkKBWPNIH4_cjs = require('../chunk-KBWPNIH4.cjs');
8
+ var chunkFJUNILZT_cjs = require('../chunk-FJUNILZT.cjs');
9
+
10
+ // src/anthropic-agent-sdk/client-wrapper.ts
11
+ chunkFJUNILZT_cjs.init_tracing();
12
+ var WRAPPED_CLIENT = /* @__PURE__ */ Symbol.for("morse.anthropic-agent-sdk.wrapped");
13
+ var INSTALL_SENTINEL = /* @__PURE__ */ Symbol.for("morse.anthropic-agent-sdk.installed");
14
+ var ORIGINALS_SENTINEL = /* @__PURE__ */ Symbol.for("morse.anthropic-agent-sdk.originals");
15
+ function wrapClaudeAgentSDK(client, options = {}) {
16
+ if (!client || typeof client !== "object") return client;
17
+ if (client[WRAPPED_CLIENT]) return client;
18
+ const originalQuery = client.query?.bind(client);
19
+ if (typeof originalQuery !== "function") return client;
20
+ const patchedQuery = buildPatchedQuery(
21
+ originalQuery,
22
+ options
23
+ );
24
+ const wrapper = new Proxy(client, {
25
+ get(target, prop, receiver) {
26
+ if (prop === WRAPPED_CLIENT) return true;
27
+ if (prop === "query") return patchedQuery;
28
+ const value = Reflect.get(target, prop, receiver);
29
+ if (typeof value === "function") {
30
+ return value.bind(target);
31
+ }
32
+ return value;
33
+ }
34
+ });
35
+ return wrapper;
36
+ }
37
+ var instrumentClaudeAgentSDK = chunk7EO7MQBA_cjs.absorbErrorsAsync(
38
+ async (clientOrOptions = void 0, maybeOptions = {}) => {
39
+ if (clientOrOptions && isClient(clientOrOptions)) {
40
+ const opts2 = maybeOptions ?? {};
41
+ return wrapClaudeAgentSDK(clientOrOptions, opts2);
42
+ }
43
+ const opts = clientOrOptions ?? {};
44
+ const mod = await loadClaudeAgentSDKModule(opts.claudeAgentSdkModule);
45
+ if (!mod) return false;
46
+ const installed = mod[INSTALL_SENTINEL] === true;
47
+ if (installed) return true;
48
+ const carrier = findClientPrototypeCarrier(mod);
49
+ if (!carrier) return false;
50
+ const originalQuery = carrier.prototype.query;
51
+ if (typeof originalQuery !== "function") return false;
52
+ const patchedQuery = buildPatchedQuery(function(prompt, callOptions) {
53
+ return originalQuery.call(this, prompt, callOptions);
54
+ }, opts);
55
+ carrier.prototype.query = patchedQuery;
56
+ mod[ORIGINALS_SENTINEL] = {
57
+ protoQuery: originalQuery,
58
+ protoCarrier: carrier
59
+ };
60
+ mod[INSTALL_SENTINEL] = true;
61
+ return true;
62
+ },
63
+ { fingerprint: "morse.adapters.anthropic-agent-sdk.install" }
64
+ );
65
+ var uninstallClaudeAgentSDK = chunk7EO7MQBA_cjs.absorbErrorsSync(
66
+ (claudeAgentSdkModule) => {
67
+ if (!claudeAgentSdkModule || typeof claudeAgentSdkModule !== "object") return;
68
+ const mod = claudeAgentSdkModule;
69
+ if (!mod[INSTALL_SENTINEL]) return;
70
+ const originals = mod[ORIGINALS_SENTINEL];
71
+ if (originals?.protoCarrier && originals.protoQuery !== void 0) {
72
+ originals.protoCarrier.prototype.query = originals.protoQuery;
73
+ }
74
+ mod[ORIGINALS_SENTINEL] = void 0;
75
+ mod[INSTALL_SENTINEL] = false;
76
+ },
77
+ { fingerprint: "morse.adapters.anthropic-agent-sdk.uninstall" }
78
+ );
79
+ function isClaudeAgentSDKWrapped(client) {
80
+ if (!client || typeof client !== "object") return false;
81
+ return client[WRAPPED_CLIENT] === true;
82
+ }
83
+ function isClient(x) {
84
+ if (!x || typeof x !== "object") return false;
85
+ const q = x.query;
86
+ return typeof q === "function";
87
+ }
88
+ async function loadClaudeAgentSDKModule(explicit) {
89
+ if (explicit && typeof explicit === "object") return explicit;
90
+ try {
91
+ return await Function("m", "return import(m)")("@anthropic-ai/claude-agent-sdk");
92
+ } catch {
93
+ return null;
94
+ }
95
+ }
96
+ function findClientPrototypeCarrier(mod) {
97
+ if (!mod || typeof mod !== "object") return null;
98
+ const m = mod;
99
+ const candidates = [
100
+ m.ClaudeSDKClient,
101
+ m.default?.ClaudeSDKClient
102
+ ];
103
+ for (const c of candidates) {
104
+ if (c && typeof c === "function" && c.prototype && typeof c.prototype.query === "function") {
105
+ return c;
106
+ }
107
+ }
108
+ return null;
109
+ }
110
+ function buildPatchedQuery(original, options) {
111
+ const defaultAgentName = options.defaultAgentName ?? "claude-agent-sdk";
112
+ const defaultModel = options.defaultModel;
113
+ return function patchedQuery(prompt, callOptions) {
114
+ const boundOriginal = (p, o) => original.call(this, p, o);
115
+ const model = (callOptions && typeof callOptions.model === "string" ? callOptions.model : void 0) ?? defaultModel;
116
+ async function* iterateInTrace() {
117
+ const handle = chunkKZBCOZIQ_cjs.emitAgentSpan({
118
+ adapter: "anthropic-agent-sdk",
119
+ agentName: defaultAgentName,
120
+ model
121
+ });
122
+ let iter;
123
+ try {
124
+ const ret = boundOriginal(prompt, callOptions);
125
+ iter = ret instanceof Promise ? await ret : ret;
126
+ } catch (err) {
127
+ handle?.end(err);
128
+ throw err;
129
+ }
130
+ try {
131
+ for await (const event of iter) {
132
+ yield event;
133
+ }
134
+ } catch (err) {
135
+ handle?.end(err);
136
+ throw err;
137
+ }
138
+ handle?.end();
139
+ }
140
+ if (chunkFJUNILZT_cjs.getActiveTraceState() !== null) {
141
+ return iterateInTrace();
142
+ }
143
+ return (async function* outerTrace() {
144
+ const queue = [];
145
+ let notify = null;
146
+ const waitForItem = () => new Promise((resolve) => {
147
+ if (queue.length > 0) {
148
+ resolve();
149
+ } else {
150
+ notify = () => {
151
+ notify = null;
152
+ resolve();
153
+ };
154
+ }
155
+ });
156
+ const runPromise = chunkFJUNILZT_cjs.runAsync({ agentName: defaultAgentName }, async (runHandle) => {
157
+ try {
158
+ for await (const event of iterateInTrace()) {
159
+ queue.push({ kind: "value", value: event });
160
+ notify?.();
161
+ }
162
+ runHandle.setOutcome(true);
163
+ } catch (err) {
164
+ queue.push({ kind: "error", error: err });
165
+ notify?.();
166
+ throw err;
167
+ } finally {
168
+ queue.push({ kind: "end" });
169
+ notify?.();
170
+ }
171
+ return null;
172
+ });
173
+ runPromise.catch(() => {
174
+ });
175
+ while (true) {
176
+ if (queue.length === 0) await waitForItem();
177
+ const item = queue.shift();
178
+ if (!item) continue;
179
+ if (item.kind === "value") {
180
+ yield item.value;
181
+ } else if (item.kind === "error") {
182
+ throw item.error;
183
+ } else {
184
+ return;
185
+ }
186
+ }
187
+ })();
188
+ };
189
+ }
190
+
191
+ // src/_agent-sdk-common/context-propagation.ts
192
+ chunkFJUNILZT_cjs.init_tracing();
193
+ var captureParentForFanOut = chunk7EO7MQBA_cjs.absorbErrorsSync(
194
+ () => {
195
+ const state = chunkFJUNILZT_cjs.getActiveTraceState();
196
+ if (state === null) return null;
197
+ const top = state.spanStack[state.spanStack.length - 1];
198
+ if (!top) return null;
199
+ return {
200
+ parentSpanId: top.span_id,
201
+ traceId: state.traceId
202
+ };
203
+ },
204
+ { fingerprint: "agent-sdk-common.captureParentForFanOut" }
205
+ );
206
+ var emitWithPinnedParent = chunk7EO7MQBA_cjs.absorbErrorsSync(
207
+ (opts) => {
208
+ const state = chunkFJUNILZT_cjs.getActiveTraceState();
209
+ if (state === null) return null;
210
+ const snap = opts.snapshot;
211
+ if (!snap || snap.traceId !== state.traceId) return null;
212
+ const handle = chunkFJUNILZT_cjs.startSpan({
213
+ name: opts.name,
214
+ type: opts.type,
215
+ metadata: opts.metadata
216
+ });
217
+ if (handle === null) return null;
218
+ handle.span.parent_span_id = snap.parentSpanId;
219
+ return handle;
220
+ },
221
+ { fingerprint: "agent-sdk-common.emitWithPinnedParent" }
222
+ );
223
+ function findSpanById(state, spanId) {
224
+ for (let i = state.spanStack.length - 1; i >= 0; i--) {
225
+ const s = state.spanStack[i];
226
+ if (s && s.span_id === spanId) return s;
227
+ }
228
+ for (let i = state.completedSpans.length - 1; i >= 0; i--) {
229
+ const s = state.completedSpans[i];
230
+ if (s && s.span_id === spanId) return s;
231
+ }
232
+ return void 0;
233
+ }
234
+ var emitAsToolSibling = chunk7EO7MQBA_cjs.absorbErrorsSync(
235
+ (opts) => {
236
+ const state = chunkFJUNILZT_cjs.getActiveTraceState();
237
+ if (state === null) return null;
238
+ const tool = findSpanById(state, opts.toolSpanId);
239
+ if (!tool) return null;
240
+ const handle = chunkFJUNILZT_cjs.startSpan({
241
+ name: opts.name,
242
+ type: opts.type,
243
+ metadata: opts.metadata
244
+ });
245
+ if (handle === null) return null;
246
+ handle.span.parent_span_id = tool.parent_span_id;
247
+ return handle;
248
+ },
249
+ { fingerprint: "agent-sdk-common.emitAsToolSibling" }
250
+ );
251
+ chunk7EO7MQBA_cjs.absorbErrorsSync(
252
+ () => {
253
+ const state = chunkFJUNILZT_cjs.getActiveTraceState();
254
+ if (state === null) return null;
255
+ return {
256
+ traceId: state.traceId,
257
+ spanStack: state.spanStack.slice(),
258
+ completedSpans: state.completedSpans.slice()
259
+ };
260
+ },
261
+ { fingerprint: "agent-sdk-common.inspectTraceState" }
262
+ );
263
+
264
+ // src/anthropic-agent-sdk/hook-instrumentation.ts
265
+ function isHookEvent(payload) {
266
+ if (payload === null || typeof payload !== "object") return false;
267
+ const obj = payload;
268
+ if (typeof obj.name !== "string" || obj.name.length === 0) return false;
269
+ const kind = obj.kind;
270
+ if (kind !== "pre_tool" && kind !== "post_tool" && kind !== "on_error") return false;
271
+ return true;
272
+ }
273
+ var _handleHookEvent = (payload, options) => {
274
+ if (!isHookEvent(payload)) return;
275
+ const { name, kind } = payload;
276
+ const durationMs = typeof payload.duration_ms === "number" && Number.isFinite(payload.duration_ms) ? payload.duration_ms : void 0;
277
+ const toolUseId = typeof payload.tool_use_id === "string" && payload.tool_use_id.length > 0 ? payload.tool_use_id : void 0;
278
+ const lookup = options?.toolSpanLookup;
279
+ const toolSpanId = toolUseId !== void 0 && typeof lookup === "function" ? lookup(toolUseId) : null;
280
+ if (toolSpanId !== null && toolSpanId !== void 0 && toolSpanId.length > 0) {
281
+ const hookMeta = { name, kind };
282
+ if (durationMs !== void 0) hookMeta.duration_ms = durationMs;
283
+ const handle = emitAsToolSibling({
284
+ name: `anthropic-agent-sdk.hook.${kind}.${name}`,
285
+ type: "tool",
286
+ metadata: {
287
+ adapter: "anthropic-agent-sdk",
288
+ tool_kind: "hook",
289
+ hook: hookMeta
290
+ },
291
+ toolSpanId
292
+ });
293
+ if (handle !== null && handle !== void 0) {
294
+ handle.end();
295
+ return;
296
+ }
297
+ }
298
+ const fallback = chunkKZBCOZIQ_cjs.emitHookSpan({
299
+ adapter: "anthropic-agent-sdk",
300
+ hookName: name,
301
+ hookKind: kind,
302
+ durationMs
303
+ });
304
+ if (fallback !== null && fallback !== void 0) {
305
+ fallback.end();
306
+ }
307
+ };
308
+ var handleHookEvent = chunk7EO7MQBA_cjs.absorbErrorsSync(_handleHookEvent, {
309
+ fingerprint: "morse.anthropic-agent-sdk.hook-instrumentation.handle"
310
+ });
311
+ function installHookInstrumentation(client, options) {
312
+ if (client === null || typeof client !== "object" || typeof client.on !== "function") {
313
+ return () => {
314
+ };
315
+ }
316
+ const listener = (payload) => {
317
+ handleHookEvent(payload, options);
318
+ };
319
+ try {
320
+ client.on("hook", listener);
321
+ } catch {
322
+ return () => {
323
+ };
324
+ }
325
+ return () => {
326
+ try {
327
+ if (typeof client.off === "function") {
328
+ client.off("hook", listener);
329
+ }
330
+ } catch {
331
+ }
332
+ };
333
+ }
334
+
335
+ // src/anthropic-agent-sdk/llm-instrumentation.ts
336
+ function readInputTokens(usage) {
337
+ if (usage === void 0 || usage === null || typeof usage !== "object") return void 0;
338
+ const base = typeof usage.input_tokens === "number" && Number.isFinite(usage.input_tokens) ? usage.input_tokens : 0;
339
+ const cacheWrite = typeof usage.cache_creation_input_tokens === "number" && Number.isFinite(usage.cache_creation_input_tokens) ? usage.cache_creation_input_tokens : 0;
340
+ const cacheRead = typeof usage.cache_read_input_tokens === "number" && Number.isFinite(usage.cache_read_input_tokens) ? usage.cache_read_input_tokens : 0;
341
+ if (usage.input_tokens === void 0 && usage.cache_creation_input_tokens === void 0 && usage.cache_read_input_tokens === void 0) {
342
+ return void 0;
343
+ }
344
+ return base + cacheWrite + cacheRead;
345
+ }
346
+ function readOutputTokens(usage) {
347
+ if (usage === void 0 || usage === null || typeof usage !== "object") return void 0;
348
+ if (typeof usage.output_tokens === "number" && Number.isFinite(usage.output_tokens)) {
349
+ return usage.output_tokens;
350
+ }
351
+ return void 0;
352
+ }
353
+ function readCacheWriteTokens(usage) {
354
+ if (usage === void 0 || usage === null || typeof usage !== "object") return void 0;
355
+ if (typeof usage.cache_creation_input_tokens === "number" && Number.isFinite(usage.cache_creation_input_tokens) && usage.cache_creation_input_tokens > 0) {
356
+ return usage.cache_creation_input_tokens;
357
+ }
358
+ return void 0;
359
+ }
360
+ function readCachedInputTokens(usage) {
361
+ if (usage === void 0 || usage === null || typeof usage !== "object") return void 0;
362
+ if (typeof usage.cache_read_input_tokens === "number" && Number.isFinite(usage.cache_read_input_tokens) && usage.cache_read_input_tokens > 0) {
363
+ return usage.cache_read_input_tokens;
364
+ }
365
+ return void 0;
366
+ }
367
+ function applyCost(handle, model, inputTokens, outputTokens, cacheWriteTokens, cachedInputTokens) {
368
+ if (handle.span.cost_usd !== void 0) return;
369
+ if (inputTokens === void 0 && outputTokens === void 0) return;
370
+ const cost = chunkKBWPNIH4_cjs.calculateCost({
371
+ inputTokens: inputTokens ?? 0,
372
+ outputTokens: outputTokens ?? 0,
373
+ model,
374
+ cachedInputTokens: cachedInputTokens ?? 0,
375
+ cacheWriteTokens: cacheWriteTokens ?? 0
376
+ });
377
+ if (cost !== void 0) handle.span.cost_usd = cost;
378
+ }
379
+ function safe(fn) {
380
+ try {
381
+ fn();
382
+ } catch {
383
+ }
384
+ }
385
+ async function* instrumentLlmCalls(events, options) {
386
+ let openSpan = null;
387
+ const fallbackModel = options?.fallbackModel;
388
+ const requestParams = options?.requestParams;
389
+ try {
390
+ for await (const event of events) {
391
+ const eventType = typeof event?.type === "string" ? event.type : "";
392
+ if (eventType === "assistant" && event.message) {
393
+ safe(() => {
394
+ if (openSpan !== null) {
395
+ openSpan.end();
396
+ openSpan = null;
397
+ }
398
+ const reportedModel = typeof event.message?.model === "string" && event.message.model.length > 0 ? event.message.model : void 0;
399
+ const model = reportedModel ?? fallbackModel;
400
+ if (!model) return;
401
+ const handle = chunkKZBCOZIQ_cjs.emitLlmSpan({ adapter: "anthropic-agent-sdk", model });
402
+ if (!handle) return;
403
+ const usage = event.message?.usage;
404
+ const inputTokens = readInputTokens(usage);
405
+ const outputTokens = readOutputTokens(usage);
406
+ const cacheWriteTokens = readCacheWriteTokens(usage);
407
+ const cachedInputTokens = readCachedInputTokens(usage);
408
+ if (inputTokens !== void 0) handle.span.input_tokens = inputTokens;
409
+ if (outputTokens !== void 0) handle.span.output_tokens = outputTokens;
410
+ if (cacheWriteTokens !== void 0) handle.span.cache_write_tokens = cacheWriteTokens;
411
+ if (cachedInputTokens !== void 0) handle.span.cached_input_tokens = cachedInputTokens;
412
+ if (inputTokens !== void 0 && outputTokens !== void 0) {
413
+ handle.span.total_tokens = inputTokens + outputTokens;
414
+ }
415
+ applyCost(handle, model, inputTokens, outputTokens, cacheWriteTokens, cachedInputTokens);
416
+ if (requestParams !== void 0) {
417
+ try {
418
+ const segments = chunk7YCENA54_cjs.extractAnthropicSegments(
419
+ requestParams,
420
+ event.message
421
+ );
422
+ if (Array.isArray(segments) && segments.length > 0) {
423
+ handle.span.context_segments = segments;
424
+ }
425
+ } catch {
426
+ }
427
+ }
428
+ handle.end();
429
+ });
430
+ } else if (eventType === "message_start") {
431
+ safe(() => {
432
+ if (openSpan !== null) {
433
+ openSpan.end(new Error("morse: message_start without preceding message_stop"));
434
+ openSpan = null;
435
+ }
436
+ const reportedModel = typeof event.message?.model === "string" && event.message.model.length > 0 ? event.message.model : void 0;
437
+ const model = reportedModel ?? fallbackModel;
438
+ if (model === void 0 || model.length === 0) {
439
+ return;
440
+ }
441
+ openSpan = chunkKZBCOZIQ_cjs.emitLlmSpan({
442
+ adapter: "anthropic-agent-sdk",
443
+ model
444
+ });
445
+ });
446
+ } else if (eventType === "message_stop") {
447
+ if (openSpan !== null) {
448
+ const handle = openSpan;
449
+ openSpan = null;
450
+ safe(() => {
451
+ const usage = event.message?.usage;
452
+ const inputTokens = readInputTokens(usage);
453
+ const outputTokens = readOutputTokens(usage);
454
+ const cacheWriteTokens = readCacheWriteTokens(usage);
455
+ const cachedInputTokens = readCachedInputTokens(usage);
456
+ if (inputTokens !== void 0) {
457
+ handle.span.input_tokens = inputTokens;
458
+ }
459
+ if (outputTokens !== void 0) {
460
+ handle.span.output_tokens = outputTokens;
461
+ }
462
+ if (cacheWriteTokens !== void 0) {
463
+ handle.span.cache_write_tokens = cacheWriteTokens;
464
+ }
465
+ if (cachedInputTokens !== void 0) {
466
+ handle.span.cached_input_tokens = cachedInputTokens;
467
+ }
468
+ if (inputTokens !== void 0 && outputTokens !== void 0) {
469
+ handle.span.total_tokens = inputTokens + outputTokens;
470
+ }
471
+ if (handle.span.model) {
472
+ applyCost(
473
+ handle,
474
+ handle.span.model,
475
+ inputTokens,
476
+ outputTokens,
477
+ cacheWriteTokens,
478
+ cachedInputTokens
479
+ );
480
+ }
481
+ if (requestParams !== void 0) {
482
+ try {
483
+ const segments = chunk7YCENA54_cjs.extractAnthropicSegments(
484
+ requestParams,
485
+ event.message
486
+ );
487
+ if (Array.isArray(segments) && segments.length > 0) {
488
+ handle.span.context_segments = segments;
489
+ }
490
+ } catch {
491
+ }
492
+ }
493
+ handle.end();
494
+ });
495
+ }
496
+ }
497
+ yield event;
498
+ }
499
+ } finally {
500
+ if (openSpan !== null) {
501
+ const handle = openSpan;
502
+ openSpan = null;
503
+ safe(() => {
504
+ handle.end(new Error("morse: iterator ended before message_stop"));
505
+ });
506
+ }
507
+ }
508
+ }
509
+
510
+ // src/anthropic-agent-sdk/tool-and-subagent.ts
511
+ var ADAPTER = "anthropic-agent-sdk";
512
+ var TASK_TOOL_NAME = "Task";
513
+ function safeCloseFailed(handle, message) {
514
+ try {
515
+ handle.end(new Error(message));
516
+ } catch {
517
+ }
518
+ }
519
+ function safeCloseOk(handle) {
520
+ try {
521
+ handle.end();
522
+ } catch {
523
+ }
524
+ }
525
+ async function* instrumentTools(events, options) {
526
+ const open = /* @__PURE__ */ new Map();
527
+ let fanOutSnapshot = null;
528
+ let openSubagentCount = 0;
529
+ const inputOpts = options?.toolInputMaxBytes ? { maxBytes: options.toolInputMaxBytes } : void 0;
530
+ const outputOpts = options?.toolOutputMaxBytes ? { maxBytes: options.toolOutputMaxBytes } : void 0;
531
+ const extractContentBlocks = (event) => {
532
+ const msg = event.message;
533
+ const content = msg?.content;
534
+ return Array.isArray(content) ? content : [];
535
+ };
536
+ const handleToolUse = (event) => {
537
+ const toolUseId = typeof event.tool_use_id === "string" ? event.tool_use_id : null;
538
+ const name = typeof event.name === "string" ? event.name : null;
539
+ if (toolUseId === null || name === null) return;
540
+ if (open.has(toolUseId)) return;
541
+ if (name === TASK_TOOL_NAME) {
542
+ if (fanOutSnapshot === null) {
543
+ fanOutSnapshot = captureParentForFanOut();
544
+ }
545
+ const input = event.input && typeof event.input === "object" ? event.input : {};
546
+ const description = typeof input.description === "string" && input.description.length > 0 ? input.description : `subagent_${toolUseId}`;
547
+ const taskPrompt = typeof input.prompt === "string" ? input.prompt : void 0;
548
+ const metadata = {
549
+ adapter: ADAPTER,
550
+ spawn_kind: "subagent",
551
+ parent_agent_name: "anthropic-agent-sdk",
552
+ subagent_name: description,
553
+ tool_use_id: toolUseId
554
+ };
555
+ if (taskPrompt !== void 0) {
556
+ metadata.task_description = chunkVXDBDPDR_cjs.summarizeToolInput(taskPrompt, inputOpts);
557
+ }
558
+ let handle2 = null;
559
+ try {
560
+ if (fanOutSnapshot !== null) {
561
+ handle2 = emitWithPinnedParent({
562
+ name: `${ADAPTER}.subagent.spawn`,
563
+ type: "agent",
564
+ metadata,
565
+ snapshot: fanOutSnapshot
566
+ });
567
+ }
568
+ } catch {
569
+ handle2 = null;
570
+ }
571
+ if (handle2 === null) return;
572
+ open.set(toolUseId, { handle: handle2, isSubagent: true });
573
+ openSubagentCount++;
574
+ return;
575
+ }
576
+ let handle = null;
577
+ try {
578
+ handle = chunkKZBCOZIQ_cjs.emitToolSpan({
579
+ adapter: ADAPTER,
580
+ toolName: name,
581
+ inputSummary: chunkVXDBDPDR_cjs.summarizeToolInput(event.input, inputOpts),
582
+ attributes: { tool_use_id: toolUseId }
583
+ });
584
+ } catch {
585
+ handle = null;
586
+ }
587
+ if (handle === null) return;
588
+ open.set(toolUseId, { handle, isSubagent: false });
589
+ };
590
+ const handleToolResult = (event) => {
591
+ const toolUseId = typeof event.tool_use_id === "string" ? event.tool_use_id : null;
592
+ if (toolUseId === null) return;
593
+ const entry = open.get(toolUseId);
594
+ if (!entry) return;
595
+ open.delete(toolUseId);
596
+ const isError = event.is_error === true;
597
+ try {
598
+ const outputSummary = chunkVXDBDPDR_cjs.summarizeToolOutput(event.content, outputOpts);
599
+ entry.handle.span.metadata = {
600
+ ...entry.handle.span.metadata ?? {},
601
+ tool_output_summary: outputSummary
602
+ };
603
+ if (entry.isSubagent) {
604
+ entry.handle.span.metadata.success = !isError;
605
+ } else {
606
+ entry.handle.span.metadata.success = !isError;
607
+ }
608
+ } catch {
609
+ }
610
+ if (isError) {
611
+ safeCloseFailed(entry.handle, "tool error");
612
+ } else {
613
+ safeCloseOk(entry.handle);
614
+ }
615
+ if (entry.isSubagent) {
616
+ openSubagentCount = Math.max(0, openSubagentCount - 1);
617
+ if (openSubagentCount === 0) {
618
+ fanOutSnapshot = null;
619
+ }
620
+ }
621
+ };
622
+ try {
623
+ for await (const event of events) {
624
+ try {
625
+ const type = typeof event?.type === "string" ? event.type : null;
626
+ if (type === "tool_use") {
627
+ handleToolUse(event);
628
+ } else if (type === "tool_result") {
629
+ handleToolResult(event);
630
+ } else if (type === "assistant" || type === "user") {
631
+ const blocks = extractContentBlocks(event);
632
+ for (const block of blocks) {
633
+ if (!block || typeof block !== "object") continue;
634
+ const bt = typeof block.type === "string" ? block.type : null;
635
+ if (bt === "tool_use" && type === "assistant") {
636
+ handleToolUse({
637
+ type: "tool_use",
638
+ tool_use_id: block.id,
639
+ name: block.name,
640
+ input: block.input
641
+ });
642
+ } else if (bt === "tool_result" && type === "user") {
643
+ handleToolResult({
644
+ type: "tool_result",
645
+ tool_use_id: block.tool_use_id,
646
+ content: block.content,
647
+ is_error: block.is_error
648
+ });
649
+ }
650
+ }
651
+ }
652
+ } catch {
653
+ }
654
+ yield event;
655
+ }
656
+ } finally {
657
+ for (const [, entry] of open) {
658
+ safeCloseFailed(entry.handle, "tool_use without matching tool_result");
659
+ if (entry.isSubagent) {
660
+ openSubagentCount = Math.max(0, openSubagentCount - 1);
661
+ }
662
+ }
663
+ open.clear();
664
+ fanOutSnapshot = null;
665
+ }
666
+ }
667
+
668
+ // src/anthropic-agent-sdk/index.ts
669
+ var FULL_WRAP_SENTINEL = /* @__PURE__ */ Symbol.for("morse.anthropic-agent-sdk.full-wrapped");
670
+ function wrapClaudeAgentSDKWithFullInstrumentation(client, options = {}) {
671
+ const existing = client[FULL_WRAP_SENTINEL];
672
+ if (existing) {
673
+ return existing;
674
+ }
675
+ const wrapOpts = {
676
+ defaultAgentName: options.defaultAgentName,
677
+ defaultModel: options.defaultModel
678
+ };
679
+ const llmOpts = {
680
+ fallbackModel: options.defaultModel
681
+ };
682
+ const toolOpts = {
683
+ toolInputMaxBytes: options.toolInputMaxBytes,
684
+ toolOutputMaxBytes: options.toolOutputMaxBytes
685
+ };
686
+ const hookOpts = {
687
+ toolSpanLookup: options.toolSpanLookup
688
+ };
689
+ const outerWrapped = wrapClaudeAgentSDK(client, wrapOpts);
690
+ const composed = new Proxy(outerWrapped, {
691
+ get(target, prop, receiver) {
692
+ if (prop === "query") {
693
+ const outerQuery = target.query.bind(target);
694
+ return function composedQuery(prompt, callOptions) {
695
+ async function* compose() {
696
+ const ret = outerQuery(prompt, callOptions);
697
+ const iter = ret instanceof Promise ? await ret : ret;
698
+ const llmTapped = instrumentLlmCalls(iter, llmOpts);
699
+ const toolTapped = instrumentTools(llmTapped, toolOpts);
700
+ for await (const event of toolTapped) {
701
+ yield event;
702
+ }
703
+ }
704
+ return compose();
705
+ };
706
+ }
707
+ const value = Reflect.get(target, prop, receiver);
708
+ if (typeof value === "function") {
709
+ return value.bind(target);
710
+ }
711
+ return value;
712
+ }
713
+ });
714
+ const unsubscribeHooks = installHookInstrumentation(client, hookOpts);
715
+ let disposed = false;
716
+ const dispose = () => {
717
+ if (disposed) return;
718
+ disposed = true;
719
+ try {
720
+ unsubscribeHooks();
721
+ } catch {
722
+ }
723
+ };
724
+ const result = {
725
+ client: composed,
726
+ dispose
727
+ };
728
+ try {
729
+ client[FULL_WRAP_SENTINEL] = result;
730
+ } catch {
731
+ }
732
+ return result;
733
+ }
734
+
735
+ exports.installHookInstrumentation = installHookInstrumentation;
736
+ exports.instrumentClaudeAgentSDK = instrumentClaudeAgentSDK;
737
+ exports.instrumentLlmCalls = instrumentLlmCalls;
738
+ exports.instrumentTools = instrumentTools;
739
+ exports.isClaudeAgentSDKWrapped = isClaudeAgentSDKWrapped;
740
+ exports.uninstallClaudeAgentSDK = uninstallClaudeAgentSDK;
741
+ exports.wrapClaudeAgentSDK = wrapClaudeAgentSDK;
742
+ exports.wrapClaudeAgentSDKWithFullInstrumentation = wrapClaudeAgentSDKWithFullInstrumentation;
743
+ //# sourceMappingURL=index.cjs.map
744
+ //# sourceMappingURL=index.cjs.map