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