@mastra/claude 0.3.0 → 0.3.1-alpha.0
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/LICENSE.md +6 -4
- package/dist/docs/SKILL.md +3 -2
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/docs-connections-overview.md +96 -0
- package/dist/docs/references/{docs-agents-sdk-agents.md → docs-connections-sdk-agents.md} +7 -1
- package/dist/index.cjs +866 -1077
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +864 -1074
- package/dist/index.js.map +1 -1
- package/package.json +17 -17
- package/CHANGELOG.md +0 -176
package/dist/index.cjs
CHANGED
|
@@ -1,1161 +1,950 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
// src/index.ts
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let crypto = require("crypto");
|
|
3
|
+
let stream_web = require("stream/web");
|
|
4
|
+
let _anthropic_ai_claude_agent_sdk = require("@anthropic-ai/claude-agent-sdk");
|
|
5
|
+
let _mastra_core_agent = require("@mastra/core/agent");
|
|
6
|
+
let _mastra_core_request_context = require("@mastra/core/request-context");
|
|
7
|
+
let _mastra_core_stream = require("@mastra/core/stream");
|
|
8
|
+
let _mastra_core_agent_message_list = require("@mastra/core/agent/message-list");
|
|
9
|
+
let _mastra_core_observability = require("@mastra/core/observability");
|
|
10
|
+
let _mastra_core_schema = require("@mastra/core/schema");
|
|
11
|
+
//#region src/utils.ts
|
|
14
12
|
function createNoopModel({ modelId, provider }) {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
13
|
+
return {
|
|
14
|
+
modelId,
|
|
15
|
+
provider,
|
|
16
|
+
specificationVersion: "v3",
|
|
17
|
+
supportedUrls: {},
|
|
18
|
+
doGenerate: async () => createNoopStreamResult(),
|
|
19
|
+
doStream: async () => createNoopStreamResult()
|
|
20
|
+
};
|
|
23
21
|
}
|
|
24
22
|
function createNoopStreamResult() {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
}
|
|
99
|
-
function
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
usage,
|
|
290
|
-
providerMetadata
|
|
291
|
-
});
|
|
292
|
-
return;
|
|
293
|
-
}
|
|
294
|
-
modelSpan?.end({
|
|
295
|
-
output: {
|
|
296
|
-
text
|
|
297
|
-
},
|
|
298
|
-
attributes: {
|
|
299
|
-
finishReason,
|
|
300
|
-
responseId,
|
|
301
|
-
responseModel,
|
|
302
|
-
usage: usage ? toUsageStats(usage) : void 0,
|
|
303
|
-
costContext
|
|
304
|
-
}
|
|
305
|
-
});
|
|
306
|
-
};
|
|
307
|
-
const end = (result) => {
|
|
308
|
-
if (ended) {
|
|
309
|
-
return;
|
|
310
|
-
}
|
|
311
|
-
ended = true;
|
|
312
|
-
closeOpenToolSpans(true);
|
|
313
|
-
endModel(result);
|
|
314
|
-
agentSpan?.end({
|
|
315
|
-
output: {
|
|
316
|
-
text: result.text
|
|
317
|
-
}
|
|
318
|
-
});
|
|
319
|
-
};
|
|
320
|
-
const fail = (error) => {
|
|
321
|
-
if (ended) {
|
|
322
|
-
return;
|
|
323
|
-
}
|
|
324
|
-
ended = true;
|
|
325
|
-
const normalized = error instanceof Error ? error : new Error(String(error));
|
|
326
|
-
closeOpenToolSpans(false, normalized);
|
|
327
|
-
if (modelSpanTracker) {
|
|
328
|
-
modelSpanTracker.reportGenerationError({ error: normalized });
|
|
329
|
-
} else {
|
|
330
|
-
modelSpan?.error({ error: normalized });
|
|
331
|
-
}
|
|
332
|
-
agentSpan?.error({ error: normalized });
|
|
333
|
-
};
|
|
334
|
-
return {
|
|
335
|
-
execute: (fn) => observability.executeWithContext({ span: modelSpan ?? agentSpan, fn }),
|
|
336
|
-
endGenerate(result) {
|
|
337
|
-
end({
|
|
338
|
-
text: result.content.map((part) => part.text).join(""),
|
|
339
|
-
usage: toLanguageModelUsage(result.usage),
|
|
340
|
-
providerMetadata: result.providerMetadata,
|
|
341
|
-
finishReason: result.finishReason.unified,
|
|
342
|
-
responseId: result.response.id,
|
|
343
|
-
responseModel: result.response.modelId,
|
|
344
|
-
costContext: result.costContext
|
|
345
|
-
});
|
|
346
|
-
},
|
|
347
|
-
fail,
|
|
348
|
-
startToolCall,
|
|
349
|
-
endToolCall,
|
|
350
|
-
wrapStream(stream) {
|
|
351
|
-
const trackedStream = modelSpanTracker?.wrapStream(stream) ?? stream;
|
|
352
|
-
return wrapStreamForAgentSpan(trackedStream, {
|
|
353
|
-
end,
|
|
354
|
-
fail
|
|
355
|
-
});
|
|
356
|
-
},
|
|
357
|
-
outputOptions() {
|
|
358
|
-
return {
|
|
359
|
-
onFinish,
|
|
360
|
-
onStepFinish,
|
|
361
|
-
requestContext,
|
|
362
|
-
tracingContext: agentSpan ? { currentSpan: agentSpan } : tracingContext
|
|
363
|
-
};
|
|
364
|
-
}
|
|
365
|
-
};
|
|
23
|
+
return { stream: new stream_web.ReadableStream({ start: (controller) => controller.close() }) };
|
|
24
|
+
}
|
|
25
|
+
function createCompletedMastraStream({ runId, prompt, text, responseId, modelId, usage, providerMetadata, costContext, object }) {
|
|
26
|
+
return new stream_web.ReadableStream({ start(controller) {
|
|
27
|
+
const textId = (0, crypto.randomUUID)();
|
|
28
|
+
enqueueStartChunks(controller, {
|
|
29
|
+
runId,
|
|
30
|
+
prompt,
|
|
31
|
+
textId,
|
|
32
|
+
responseId,
|
|
33
|
+
modelId,
|
|
34
|
+
providerMetadata
|
|
35
|
+
});
|
|
36
|
+
if (text) enqueueTextDelta(controller, runId, textId, text);
|
|
37
|
+
enqueueFinishChunks(controller, {
|
|
38
|
+
runId,
|
|
39
|
+
prompt,
|
|
40
|
+
textId,
|
|
41
|
+
text,
|
|
42
|
+
responseId,
|
|
43
|
+
modelId,
|
|
44
|
+
usage,
|
|
45
|
+
providerMetadata,
|
|
46
|
+
costContext,
|
|
47
|
+
object
|
|
48
|
+
});
|
|
49
|
+
controller.close();
|
|
50
|
+
} });
|
|
51
|
+
}
|
|
52
|
+
function createMastraOutput({ messages, runId, modelId, provider, stream, responseText = "", options }) {
|
|
53
|
+
const messageList = new _mastra_core_agent_message_list.MessageList();
|
|
54
|
+
messageList.add(messages, "input");
|
|
55
|
+
messageList.add([{
|
|
56
|
+
role: "assistant",
|
|
57
|
+
content: responseText
|
|
58
|
+
}], "response");
|
|
59
|
+
return new _mastra_core_stream.MastraModelOutput({
|
|
60
|
+
model: {
|
|
61
|
+
modelId,
|
|
62
|
+
provider,
|
|
63
|
+
version: "v3"
|
|
64
|
+
},
|
|
65
|
+
stream,
|
|
66
|
+
messageList,
|
|
67
|
+
messageId: (0, crypto.randomUUID)(),
|
|
68
|
+
options: {
|
|
69
|
+
...options,
|
|
70
|
+
runId
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
function toFullOutput({ messages, runId, provider, result, options }) {
|
|
75
|
+
const text = result.content.map((part) => part.text).join("");
|
|
76
|
+
const stream = createCompletedMastraStream({
|
|
77
|
+
runId,
|
|
78
|
+
prompt: promptToText(messages),
|
|
79
|
+
text,
|
|
80
|
+
responseId: result.response.id,
|
|
81
|
+
modelId: result.response.modelId,
|
|
82
|
+
usage: toLanguageModelUsage(result.usage),
|
|
83
|
+
providerMetadata: result.providerMetadata,
|
|
84
|
+
costContext: result.costContext,
|
|
85
|
+
object: result.object
|
|
86
|
+
});
|
|
87
|
+
return createMastraOutput({
|
|
88
|
+
messages,
|
|
89
|
+
runId,
|
|
90
|
+
modelId: result.response.modelId,
|
|
91
|
+
provider,
|
|
92
|
+
stream,
|
|
93
|
+
responseText: text,
|
|
94
|
+
options
|
|
95
|
+
}).getFullOutput();
|
|
96
|
+
}
|
|
97
|
+
function createSDKAgentTelemetry({ agentId, agentName, provider, modelId, messages, prompt, runId, streaming, method, requestContext, instructions, maxSteps, tracingOptions, tracingContext, onFinish, onStepFinish, mastra }) {
|
|
98
|
+
const agentSpan = (0, _mastra_core_observability.getOrCreateSpan)({
|
|
99
|
+
type: _mastra_core_observability.SpanType.AGENT_RUN,
|
|
100
|
+
name: `agent run: '${agentId}'`,
|
|
101
|
+
entityType: _mastra_core_observability.EntityType.AGENT,
|
|
102
|
+
entityId: agentId,
|
|
103
|
+
entityName: agentName,
|
|
104
|
+
input: messages,
|
|
105
|
+
attributes: {
|
|
106
|
+
prompt,
|
|
107
|
+
instructions,
|
|
108
|
+
maxSteps
|
|
109
|
+
},
|
|
110
|
+
metadata: {
|
|
111
|
+
runId,
|
|
112
|
+
sdkAgent: true,
|
|
113
|
+
sdkProvider: provider,
|
|
114
|
+
sdkMethod: method
|
|
115
|
+
},
|
|
116
|
+
tracingOptions,
|
|
117
|
+
tracingContext,
|
|
118
|
+
requestContext,
|
|
119
|
+
mastra
|
|
120
|
+
});
|
|
121
|
+
const modelSpan = agentSpan?.createChildSpan({
|
|
122
|
+
type: _mastra_core_observability.SpanType.MODEL_GENERATION,
|
|
123
|
+
name: `llm: '${modelId}'`,
|
|
124
|
+
input: { messages },
|
|
125
|
+
attributes: {
|
|
126
|
+
model: modelId,
|
|
127
|
+
provider,
|
|
128
|
+
streaming
|
|
129
|
+
},
|
|
130
|
+
metadata: {
|
|
131
|
+
runId,
|
|
132
|
+
sdkAgent: true,
|
|
133
|
+
sdkProvider: provider,
|
|
134
|
+
sdkMethod: method
|
|
135
|
+
},
|
|
136
|
+
requestContext
|
|
137
|
+
});
|
|
138
|
+
const modelSpanTracker = getModelSpanTracker(modelSpan);
|
|
139
|
+
const toolSpans = /* @__PURE__ */ new Map();
|
|
140
|
+
let ended = false;
|
|
141
|
+
const startToolCall = ({ toolCallId, toolName, input }) => {
|
|
142
|
+
if (toolSpans.has(toolCallId)) return;
|
|
143
|
+
const parentSpan = agentSpan ?? modelSpan;
|
|
144
|
+
if (!parentSpan) return;
|
|
145
|
+
const mcp = parseMcpToolName(toolName);
|
|
146
|
+
const span = mcp ? parentSpan.createChildSpan({
|
|
147
|
+
type: _mastra_core_observability.SpanType.MCP_TOOL_CALL,
|
|
148
|
+
name: `mcp_tool: '${toolName}' on '${mcp.serverName}'`,
|
|
149
|
+
input,
|
|
150
|
+
entityType: _mastra_core_observability.EntityType.TOOL,
|
|
151
|
+
entityId: toolName,
|
|
152
|
+
entityName: toolName,
|
|
153
|
+
attributes: { mcpServer: mcp.serverName },
|
|
154
|
+
metadata: {
|
|
155
|
+
runId,
|
|
156
|
+
sdkAgent: true,
|
|
157
|
+
sdkProvider: provider,
|
|
158
|
+
sdkMethod: method,
|
|
159
|
+
toolCallId
|
|
160
|
+
},
|
|
161
|
+
requestContext
|
|
162
|
+
}) : parentSpan.createChildSpan({
|
|
163
|
+
type: _mastra_core_observability.SpanType.TOOL_CALL,
|
|
164
|
+
name: `tool: '${toolName}'`,
|
|
165
|
+
input,
|
|
166
|
+
entityType: _mastra_core_observability.EntityType.TOOL,
|
|
167
|
+
entityId: toolName,
|
|
168
|
+
entityName: toolName,
|
|
169
|
+
attributes: { toolType: "tool" },
|
|
170
|
+
metadata: {
|
|
171
|
+
runId,
|
|
172
|
+
sdkAgent: true,
|
|
173
|
+
sdkProvider: provider,
|
|
174
|
+
sdkMethod: method,
|
|
175
|
+
toolCallId
|
|
176
|
+
},
|
|
177
|
+
requestContext
|
|
178
|
+
});
|
|
179
|
+
toolSpans.set(toolCallId, span);
|
|
180
|
+
};
|
|
181
|
+
const endToolCall = ({ toolCallId, output, isError }) => {
|
|
182
|
+
const span = toolSpans.get(toolCallId);
|
|
183
|
+
if (!span) return;
|
|
184
|
+
toolSpans.delete(toolCallId);
|
|
185
|
+
if (isError) {
|
|
186
|
+
span.error({
|
|
187
|
+
error: output instanceof Error ? output : new Error(typeof output === "string" ? output : "SDK tool call failed"),
|
|
188
|
+
attributes: { success: false }
|
|
189
|
+
});
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
span.end({
|
|
193
|
+
output,
|
|
194
|
+
attributes: { success: true }
|
|
195
|
+
});
|
|
196
|
+
};
|
|
197
|
+
const closeOpenToolSpans = (success, error) => {
|
|
198
|
+
for (const [toolCallId, span] of toolSpans) {
|
|
199
|
+
toolSpans.delete(toolCallId);
|
|
200
|
+
if (success) {
|
|
201
|
+
span.end({ attributes: { success: true } });
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
const normalized = error instanceof Error ? error : new Error(String(error ?? "SDK agent run failed"));
|
|
205
|
+
span.error({
|
|
206
|
+
error: normalized,
|
|
207
|
+
attributes: { success: false }
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
const endModel = ({ text, usage, providerMetadata, finishReason = "stop", responseId, responseModel, costContext }) => {
|
|
212
|
+
if (modelSpanTracker) {
|
|
213
|
+
modelSpanTracker.endGeneration({
|
|
214
|
+
output: { text },
|
|
215
|
+
attributes: {
|
|
216
|
+
finishReason,
|
|
217
|
+
responseId,
|
|
218
|
+
responseModel,
|
|
219
|
+
costContext
|
|
220
|
+
},
|
|
221
|
+
usage,
|
|
222
|
+
providerMetadata
|
|
223
|
+
});
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
modelSpan?.end({
|
|
227
|
+
output: { text },
|
|
228
|
+
attributes: {
|
|
229
|
+
finishReason,
|
|
230
|
+
responseId,
|
|
231
|
+
responseModel,
|
|
232
|
+
usage: usage ? toUsageStats(usage) : void 0,
|
|
233
|
+
costContext
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
};
|
|
237
|
+
const end = (result) => {
|
|
238
|
+
if (ended) return;
|
|
239
|
+
ended = true;
|
|
240
|
+
closeOpenToolSpans(true);
|
|
241
|
+
endModel(result);
|
|
242
|
+
agentSpan?.end({ output: { text: result.text } });
|
|
243
|
+
};
|
|
244
|
+
const fail = (error) => {
|
|
245
|
+
if (ended) return;
|
|
246
|
+
ended = true;
|
|
247
|
+
const normalized = error instanceof Error ? error : new Error(String(error));
|
|
248
|
+
closeOpenToolSpans(false, normalized);
|
|
249
|
+
if (modelSpanTracker) modelSpanTracker.reportGenerationError({ error: normalized });
|
|
250
|
+
else modelSpan?.error({ error: normalized });
|
|
251
|
+
agentSpan?.error({ error: normalized });
|
|
252
|
+
};
|
|
253
|
+
return {
|
|
254
|
+
execute: (fn) => (0, _mastra_core_observability.executeWithContext)({
|
|
255
|
+
span: modelSpan ?? agentSpan,
|
|
256
|
+
fn
|
|
257
|
+
}),
|
|
258
|
+
endGenerate(result) {
|
|
259
|
+
end({
|
|
260
|
+
text: result.content.map((part) => part.text).join(""),
|
|
261
|
+
usage: toLanguageModelUsage(result.usage),
|
|
262
|
+
providerMetadata: result.providerMetadata,
|
|
263
|
+
finishReason: result.finishReason.unified,
|
|
264
|
+
responseId: result.response.id,
|
|
265
|
+
responseModel: result.response.modelId,
|
|
266
|
+
costContext: result.costContext
|
|
267
|
+
});
|
|
268
|
+
},
|
|
269
|
+
fail,
|
|
270
|
+
startToolCall,
|
|
271
|
+
endToolCall,
|
|
272
|
+
wrapStream(stream) {
|
|
273
|
+
return wrapStreamForAgentSpan(modelSpanTracker?.wrapStream(stream) ?? stream, {
|
|
274
|
+
end,
|
|
275
|
+
fail
|
|
276
|
+
});
|
|
277
|
+
},
|
|
278
|
+
outputOptions() {
|
|
279
|
+
return {
|
|
280
|
+
onFinish,
|
|
281
|
+
onStepFinish,
|
|
282
|
+
requestContext,
|
|
283
|
+
tracingContext: agentSpan ? { currentSpan: agentSpan } : tracingContext
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
};
|
|
366
287
|
}
|
|
367
288
|
function parseMcpToolName(toolName) {
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
toolName: match[2]
|
|
375
|
-
};
|
|
289
|
+
const match = /^mcp__([^_].*?)__(.+)$/.exec(toolName);
|
|
290
|
+
if (!match?.[1] || !match[2]) return;
|
|
291
|
+
return {
|
|
292
|
+
serverName: match[1],
|
|
293
|
+
toolName: match[2]
|
|
294
|
+
};
|
|
376
295
|
}
|
|
377
296
|
function getModelSpanTracker(modelSpan) {
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
}
|
|
381
|
-
return modelSpan.createTracker();
|
|
297
|
+
if (!modelSpan || !("createTracker" in modelSpan)) return;
|
|
298
|
+
return modelSpan.createTracker();
|
|
382
299
|
}
|
|
383
300
|
function wrapStreamForAgentSpan(stream, telemetry) {
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
}
|
|
405
|
-
controller.enqueue(chunk);
|
|
406
|
-
},
|
|
407
|
-
flush() {
|
|
408
|
-
telemetry.end({ text });
|
|
409
|
-
}
|
|
410
|
-
})
|
|
411
|
-
);
|
|
301
|
+
let text = "";
|
|
302
|
+
return stream.pipeThrough(new stream_web.TransformStream({
|
|
303
|
+
transform(chunk, controller) {
|
|
304
|
+
if (chunk.type === "text-delta") text += chunk.payload.text;
|
|
305
|
+
if (chunk.type === "finish") telemetry.end({
|
|
306
|
+
text,
|
|
307
|
+
usage: chunk.payload.output.usage,
|
|
308
|
+
providerMetadata: chunk.payload.providerMetadata,
|
|
309
|
+
finishReason: chunk.payload.stepResult.reason,
|
|
310
|
+
responseId: chunk.payload.response?.id,
|
|
311
|
+
responseModel: chunk.payload.response?.modelId,
|
|
312
|
+
costContext: getCostContext(chunk.payload.metadata?.costContext)
|
|
313
|
+
});
|
|
314
|
+
if (chunk.type === "error") telemetry.fail(chunk.payload.error);
|
|
315
|
+
controller.enqueue(chunk);
|
|
316
|
+
},
|
|
317
|
+
flush() {
|
|
318
|
+
telemetry.end({ text });
|
|
319
|
+
}
|
|
320
|
+
}));
|
|
412
321
|
}
|
|
413
322
|
function toUsageStats(usage) {
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
323
|
+
return {
|
|
324
|
+
inputTokens: usage.inputTokens,
|
|
325
|
+
outputTokens: usage.outputTokens,
|
|
326
|
+
inputDetails: {
|
|
327
|
+
cacheRead: usage.cachedInputTokens,
|
|
328
|
+
cacheWrite: usage.cacheCreationInputTokens
|
|
329
|
+
},
|
|
330
|
+
outputDetails: {
|
|
331
|
+
text: usage.outputTokens,
|
|
332
|
+
reasoning: usage.reasoningTokens
|
|
333
|
+
}
|
|
334
|
+
};
|
|
426
335
|
}
|
|
427
336
|
function getCostContext(value) {
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
}
|
|
464
|
-
});
|
|
465
|
-
controller.enqueue({
|
|
466
|
-
type: "text-start",
|
|
467
|
-
runId,
|
|
468
|
-
from: stream.ChunkFrom.AGENT,
|
|
469
|
-
payload: {
|
|
470
|
-
id: textId,
|
|
471
|
-
providerMetadata
|
|
472
|
-
}
|
|
473
|
-
});
|
|
337
|
+
if (!value || typeof value !== "object") return;
|
|
338
|
+
return value;
|
|
339
|
+
}
|
|
340
|
+
function enqueueStartChunks(controller, { runId, prompt, textId, responseId, modelId, providerMetadata }) {
|
|
341
|
+
controller.enqueue({
|
|
342
|
+
type: "start",
|
|
343
|
+
runId,
|
|
344
|
+
from: _mastra_core_stream.ChunkFrom.AGENT,
|
|
345
|
+
payload: {}
|
|
346
|
+
});
|
|
347
|
+
controller.enqueue({
|
|
348
|
+
type: "step-start",
|
|
349
|
+
runId,
|
|
350
|
+
from: _mastra_core_stream.ChunkFrom.AGENT,
|
|
351
|
+
payload: { request: { body: prompt } }
|
|
352
|
+
});
|
|
353
|
+
controller.enqueue({
|
|
354
|
+
type: "response-metadata",
|
|
355
|
+
runId,
|
|
356
|
+
from: _mastra_core_stream.ChunkFrom.AGENT,
|
|
357
|
+
payload: {
|
|
358
|
+
id: responseId,
|
|
359
|
+
modelId,
|
|
360
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
361
|
+
}
|
|
362
|
+
});
|
|
363
|
+
controller.enqueue({
|
|
364
|
+
type: "text-start",
|
|
365
|
+
runId,
|
|
366
|
+
from: _mastra_core_stream.ChunkFrom.AGENT,
|
|
367
|
+
payload: {
|
|
368
|
+
id: textId,
|
|
369
|
+
providerMetadata
|
|
370
|
+
}
|
|
371
|
+
});
|
|
474
372
|
}
|
|
475
373
|
function enqueueTextDelta(controller, runId, textId, text) {
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
}
|
|
486
|
-
function enqueueFinishChunks(controller, {
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
usage,
|
|
560
|
-
steps: []
|
|
561
|
-
},
|
|
562
|
-
metadata,
|
|
563
|
-
providerMetadata,
|
|
564
|
-
messages: {
|
|
565
|
-
all: [],
|
|
566
|
-
user: [],
|
|
567
|
-
nonUser: []
|
|
568
|
-
},
|
|
569
|
-
response
|
|
570
|
-
}
|
|
571
|
-
});
|
|
374
|
+
controller.enqueue({
|
|
375
|
+
type: "text-delta",
|
|
376
|
+
runId,
|
|
377
|
+
from: _mastra_core_stream.ChunkFrom.AGENT,
|
|
378
|
+
payload: {
|
|
379
|
+
id: textId,
|
|
380
|
+
text
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
function enqueueFinishChunks(controller, { runId, prompt, textId, text, responseId, modelId, usage, providerMetadata, costContext, object }) {
|
|
385
|
+
const timestamp = /* @__PURE__ */ new Date();
|
|
386
|
+
const response = {
|
|
387
|
+
id: responseId,
|
|
388
|
+
modelId,
|
|
389
|
+
timestamp
|
|
390
|
+
};
|
|
391
|
+
const metadata = {
|
|
392
|
+
providerMetadata,
|
|
393
|
+
costContext,
|
|
394
|
+
request: { body: prompt },
|
|
395
|
+
modelId,
|
|
396
|
+
timestamp
|
|
397
|
+
};
|
|
398
|
+
controller.enqueue({
|
|
399
|
+
type: "text-end",
|
|
400
|
+
runId,
|
|
401
|
+
from: _mastra_core_stream.ChunkFrom.AGENT,
|
|
402
|
+
payload: {
|
|
403
|
+
id: textId,
|
|
404
|
+
providerMetadata
|
|
405
|
+
}
|
|
406
|
+
});
|
|
407
|
+
if (object !== void 0) controller.enqueue({
|
|
408
|
+
type: "object-result",
|
|
409
|
+
runId,
|
|
410
|
+
from: _mastra_core_stream.ChunkFrom.AGENT,
|
|
411
|
+
object
|
|
412
|
+
});
|
|
413
|
+
controller.enqueue({
|
|
414
|
+
type: "step-finish",
|
|
415
|
+
runId,
|
|
416
|
+
from: _mastra_core_stream.ChunkFrom.AGENT,
|
|
417
|
+
payload: {
|
|
418
|
+
id: responseId,
|
|
419
|
+
providerMetadata,
|
|
420
|
+
totalUsage: usage,
|
|
421
|
+
response,
|
|
422
|
+
stepResult: {
|
|
423
|
+
reason: "stop",
|
|
424
|
+
warnings: []
|
|
425
|
+
},
|
|
426
|
+
output: {
|
|
427
|
+
text,
|
|
428
|
+
usage,
|
|
429
|
+
steps: []
|
|
430
|
+
},
|
|
431
|
+
metadata
|
|
432
|
+
}
|
|
433
|
+
});
|
|
434
|
+
controller.enqueue({
|
|
435
|
+
type: "finish",
|
|
436
|
+
runId,
|
|
437
|
+
from: _mastra_core_stream.ChunkFrom.AGENT,
|
|
438
|
+
payload: {
|
|
439
|
+
stepResult: {
|
|
440
|
+
reason: "stop",
|
|
441
|
+
warnings: []
|
|
442
|
+
},
|
|
443
|
+
output: {
|
|
444
|
+
usage,
|
|
445
|
+
steps: []
|
|
446
|
+
},
|
|
447
|
+
metadata,
|
|
448
|
+
providerMetadata,
|
|
449
|
+
messages: {
|
|
450
|
+
all: [],
|
|
451
|
+
user: [],
|
|
452
|
+
nonUser: []
|
|
453
|
+
},
|
|
454
|
+
response
|
|
455
|
+
}
|
|
456
|
+
});
|
|
572
457
|
}
|
|
573
458
|
function toLanguageModelUsage(usage) {
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
459
|
+
const inputTokens = usage.inputTokens.total ?? 0;
|
|
460
|
+
const outputTokens = usage.outputTokens.total ?? 0;
|
|
461
|
+
return {
|
|
462
|
+
inputTokens,
|
|
463
|
+
outputTokens,
|
|
464
|
+
totalTokens: inputTokens + outputTokens,
|
|
465
|
+
cachedInputTokens: usage.inputTokens.cacheRead,
|
|
466
|
+
cacheCreationInputTokens: usage.inputTokens.cacheWrite,
|
|
467
|
+
raw: usage
|
|
468
|
+
};
|
|
584
469
|
}
|
|
585
470
|
function createProviderMetadata(provider, metadata) {
|
|
586
|
-
|
|
587
|
-
[provider]: toJsonRecord(metadata)
|
|
588
|
-
};
|
|
471
|
+
return { [provider]: toJsonRecord(metadata) };
|
|
589
472
|
}
|
|
590
473
|
function toJsonRecord(record) {
|
|
591
|
-
|
|
592
|
-
Object.entries(record).filter((entry) => entry[1] !== void 0).map(([key, value]) => [key, toJsonValue(value)])
|
|
593
|
-
);
|
|
474
|
+
return Object.fromEntries(Object.entries(record).filter((entry) => entry[1] !== void 0).map(([key, value]) => [key, toJsonValue(value)]));
|
|
594
475
|
}
|
|
595
476
|
function toJsonValue(value) {
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
}
|
|
602
|
-
if (value instanceof Date) {
|
|
603
|
-
return value.toISOString();
|
|
604
|
-
}
|
|
605
|
-
if (typeof value === "object") {
|
|
606
|
-
return toJsonRecord(value);
|
|
607
|
-
}
|
|
608
|
-
return String(value);
|
|
477
|
+
if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
|
|
478
|
+
if (Array.isArray(value)) return value.filter((item) => item !== void 0).map(toJsonValue);
|
|
479
|
+
if (value instanceof Date) return value.toISOString();
|
|
480
|
+
if (typeof value === "object") return toJsonRecord(value);
|
|
481
|
+
return String(value);
|
|
609
482
|
}
|
|
610
483
|
function promptToText(prompt) {
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
}
|
|
620
|
-
const record = prompt;
|
|
621
|
-
if (typeof record.text === "string") {
|
|
622
|
-
return record.text;
|
|
623
|
-
}
|
|
624
|
-
if (typeof record.content === "string") {
|
|
625
|
-
return record.content;
|
|
626
|
-
}
|
|
627
|
-
if (record.content) {
|
|
628
|
-
return promptToText(record.content);
|
|
629
|
-
}
|
|
630
|
-
return "";
|
|
484
|
+
if (typeof prompt === "string") return prompt;
|
|
485
|
+
if (Array.isArray(prompt)) return prompt.map(promptToText).filter(Boolean).join("\n");
|
|
486
|
+
if (!prompt || typeof prompt !== "object") return "";
|
|
487
|
+
const record = prompt;
|
|
488
|
+
if (typeof record.text === "string") return record.text;
|
|
489
|
+
if (typeof record.content === "string") return record.content;
|
|
490
|
+
if (record.content) return promptToText(record.content);
|
|
491
|
+
return "";
|
|
631
492
|
}
|
|
632
493
|
function getStructuredOutputSchema(structuredOutput) {
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
}
|
|
636
|
-
return schema.standardSchemaToJSONSchema(schema.toStandardSchema(structuredOutput.schema));
|
|
494
|
+
if (!structuredOutput?.schema) return;
|
|
495
|
+
return (0, _mastra_core_schema.standardSchemaToJSONSchema)((0, _mastra_core_schema.toStandardSchema)(structuredOutput.schema));
|
|
637
496
|
}
|
|
638
497
|
async function getStructuredOutputFromValue(value, structuredOutput) {
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
}
|
|
652
|
-
} else {
|
|
653
|
-
parsed = value;
|
|
654
|
-
}
|
|
655
|
-
const schema$1 = schema.toStandardSchema(structuredOutput.schema);
|
|
656
|
-
const result = await schema$1["~standard"].validate(parsed);
|
|
657
|
-
if (!result.issues) {
|
|
658
|
-
return result.value;
|
|
659
|
-
}
|
|
660
|
-
const message = result.issues.map((issue) => `- ${issue.path?.join(".") || "root"}: ${issue.message}`).join("\n");
|
|
661
|
-
return handleStructuredOutputError(new Error(`Structured output validation failed:
|
|
662
|
-
${message}`), structuredOutput);
|
|
498
|
+
if (!structuredOutput?.schema) return;
|
|
499
|
+
let parsed;
|
|
500
|
+
if (typeof value === "string") try {
|
|
501
|
+
parsed = JSON.parse(value);
|
|
502
|
+
} catch (error) {
|
|
503
|
+
return handleStructuredOutputError(new Error("Structured output must be valid JSON.", { cause: error }), structuredOutput);
|
|
504
|
+
}
|
|
505
|
+
else parsed = value;
|
|
506
|
+
const result = await (0, _mastra_core_schema.toStandardSchema)(structuredOutput.schema)["~standard"].validate(parsed);
|
|
507
|
+
if (!result.issues) return result.value;
|
|
508
|
+
const message = result.issues.map((issue) => `- ${issue.path?.join(".") || "root"}: ${issue.message}`).join("\n");
|
|
509
|
+
return handleStructuredOutputError(/* @__PURE__ */ new Error(`Structured output validation failed:\n${message}`), structuredOutput);
|
|
663
510
|
}
|
|
664
511
|
function handleStructuredOutputError(error, structuredOutput) {
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
}
|
|
672
|
-
throw error;
|
|
512
|
+
if (structuredOutput.errorStrategy === "fallback") return structuredOutput.fallbackValue;
|
|
513
|
+
if (structuredOutput.errorStrategy === "warn") {
|
|
514
|
+
structuredOutput.logger?.warn(error.message);
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
throw error;
|
|
673
518
|
}
|
|
674
519
|
function sumDefined(...values) {
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
var
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
520
|
+
const defined = values.filter((value) => typeof value === "number");
|
|
521
|
+
if (defined.length === 0) return;
|
|
522
|
+
return defined.reduce((sum, value) => sum + value, 0);
|
|
523
|
+
}
|
|
524
|
+
//#endregion
|
|
525
|
+
//#region src/index.ts
|
|
526
|
+
const PROVIDER = "@anthropic-ai/claude-agent-sdk";
|
|
527
|
+
const MODEL_ID = "claude-agent-sdk";
|
|
528
|
+
var ClaudeSDKAgent = class extends _mastra_core_agent.Agent {
|
|
529
|
+
options;
|
|
530
|
+
#mastra;
|
|
531
|
+
constructor(options) {
|
|
532
|
+
super({
|
|
533
|
+
id: options.id,
|
|
534
|
+
name: options.name ?? options.id,
|
|
535
|
+
description: options.description,
|
|
536
|
+
instructions: "",
|
|
537
|
+
model: createNoopModel({
|
|
538
|
+
modelId: getModelId(options),
|
|
539
|
+
provider: PROVIDER
|
|
540
|
+
})
|
|
541
|
+
});
|
|
542
|
+
this.options = options;
|
|
543
|
+
}
|
|
544
|
+
__registerMastra(mastra) {
|
|
545
|
+
super.__registerMastra(mastra);
|
|
546
|
+
this.#mastra = mastra;
|
|
547
|
+
}
|
|
548
|
+
supportsMemory() {
|
|
549
|
+
return false;
|
|
550
|
+
}
|
|
551
|
+
async generate(messages, options) {
|
|
552
|
+
const prompt = promptToText(messages);
|
|
553
|
+
const runId = options?.runId ?? (0, crypto.randomUUID)();
|
|
554
|
+
const requestContext = options?.requestContext ?? new _mastra_core_request_context.RequestContext();
|
|
555
|
+
const instructions = options?.instructions ? promptToText(options.instructions) : void 0;
|
|
556
|
+
const telemetry = createSDKAgentTelemetry({
|
|
557
|
+
agentId: this.id,
|
|
558
|
+
agentName: this.name,
|
|
559
|
+
provider: PROVIDER,
|
|
560
|
+
modelId: getModelId(this.options),
|
|
561
|
+
messages,
|
|
562
|
+
prompt,
|
|
563
|
+
runId,
|
|
564
|
+
streaming: false,
|
|
565
|
+
method: "generate",
|
|
566
|
+
requestContext,
|
|
567
|
+
instructions,
|
|
568
|
+
maxSteps: options?.maxSteps,
|
|
569
|
+
tracingOptions: options?.tracingOptions,
|
|
570
|
+
tracingContext: options?.tracingContext,
|
|
571
|
+
onFinish: options?.onFinish,
|
|
572
|
+
onStepFinish: options?.onStepFinish,
|
|
573
|
+
mastra: this.#mastra
|
|
574
|
+
});
|
|
575
|
+
let result;
|
|
576
|
+
try {
|
|
577
|
+
result = await telemetry.execute(() => runClaudeGenerate(prompt, this.options, telemetry, options));
|
|
578
|
+
telemetry.endGenerate(result);
|
|
579
|
+
} catch (error) {
|
|
580
|
+
telemetry.fail(error);
|
|
581
|
+
throw error;
|
|
582
|
+
}
|
|
583
|
+
return toFullOutput({
|
|
584
|
+
messages,
|
|
585
|
+
runId,
|
|
586
|
+
provider: PROVIDER,
|
|
587
|
+
result,
|
|
588
|
+
options: {
|
|
589
|
+
...telemetry.outputOptions(),
|
|
590
|
+
structuredOutput: options?.structuredOutput
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
async stream(messages, options) {
|
|
595
|
+
const runId = options?.runId ?? (0, crypto.randomUUID)();
|
|
596
|
+
const prompt = promptToText(messages);
|
|
597
|
+
const modelId = getModelId(this.options);
|
|
598
|
+
const requestContext = options?.requestContext ?? new _mastra_core_request_context.RequestContext();
|
|
599
|
+
const instructions = options?.instructions ? promptToText(options.instructions) : void 0;
|
|
600
|
+
const telemetry = createSDKAgentTelemetry({
|
|
601
|
+
agentId: this.id,
|
|
602
|
+
agentName: this.name,
|
|
603
|
+
provider: PROVIDER,
|
|
604
|
+
modelId,
|
|
605
|
+
messages,
|
|
606
|
+
prompt,
|
|
607
|
+
runId,
|
|
608
|
+
streaming: true,
|
|
609
|
+
method: "stream",
|
|
610
|
+
requestContext,
|
|
611
|
+
instructions,
|
|
612
|
+
maxSteps: options?.maxSteps,
|
|
613
|
+
tracingOptions: options?.tracingOptions,
|
|
614
|
+
tracingContext: options?.tracingContext,
|
|
615
|
+
onFinish: options?.onFinish,
|
|
616
|
+
onStepFinish: options?.onStepFinish,
|
|
617
|
+
mastra: this.#mastra
|
|
618
|
+
});
|
|
619
|
+
return createMastraOutput({
|
|
620
|
+
messages,
|
|
621
|
+
runId,
|
|
622
|
+
modelId,
|
|
623
|
+
provider: PROVIDER,
|
|
624
|
+
stream: telemetry.wrapStream(runClaudeAsMastraStream(prompt, this.options, runId, telemetry, options)),
|
|
625
|
+
options: {
|
|
626
|
+
...telemetry.outputOptions(),
|
|
627
|
+
structuredOutput: options?.structuredOutput
|
|
628
|
+
}
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
async resumeGenerate(resumeData, options) {
|
|
632
|
+
const data = validateClaudeResumeData(resumeData);
|
|
633
|
+
return this.generate(data.message, createClaudeResumeRunOptions(data, options));
|
|
634
|
+
}
|
|
635
|
+
async resumeStream(resumeData, options) {
|
|
636
|
+
const data = validateClaudeResumeData(resumeData);
|
|
637
|
+
return this.stream(data.message, createClaudeResumeRunOptions(data, options));
|
|
638
|
+
}
|
|
790
639
|
};
|
|
791
640
|
function validateClaudeResumeData(resumeData) {
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
}
|
|
806
|
-
if (hasContinue) {
|
|
807
|
-
if (resumeData.continue !== true) {
|
|
808
|
-
throw new Error("ClaudeSDKAgent resumeData.continue must be true when provided.");
|
|
809
|
-
}
|
|
810
|
-
return resumeData;
|
|
811
|
-
}
|
|
812
|
-
throw new Error("ClaudeSDKAgent resumeData must include sessionId or continue: true.");
|
|
641
|
+
if (!isRecord(resumeData) || !("message" in resumeData)) throw new Error("ClaudeSDKAgent resumeData must include a message.");
|
|
642
|
+
const hasSessionId = "sessionId" in resumeData;
|
|
643
|
+
const hasContinue = "continue" in resumeData;
|
|
644
|
+
if (hasSessionId && hasContinue) throw new Error("ClaudeSDKAgent resumeData must include either sessionId or continue: true, not both.");
|
|
645
|
+
if (hasSessionId) {
|
|
646
|
+
if (typeof resumeData.sessionId !== "string") throw new Error("ClaudeSDKAgent resumeData.sessionId must be a string.");
|
|
647
|
+
return resumeData;
|
|
648
|
+
}
|
|
649
|
+
if (hasContinue) {
|
|
650
|
+
if (resumeData.continue !== true) throw new Error("ClaudeSDKAgent resumeData.continue must be true when provided.");
|
|
651
|
+
return resumeData;
|
|
652
|
+
}
|
|
653
|
+
throw new Error("ClaudeSDKAgent resumeData must include sessionId or continue: true.");
|
|
813
654
|
}
|
|
814
655
|
function createClaudeResumeRunOptions(resumeData, options) {
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
sdkOptions.continue = true;
|
|
826
|
-
}
|
|
827
|
-
return {
|
|
828
|
-
...options,
|
|
829
|
-
sdkOptions
|
|
830
|
-
};
|
|
656
|
+
const sdkOptions = { ...options?.sdkOptions };
|
|
657
|
+
if ("sessionId" in resumeData && typeof resumeData.sessionId === "string") {
|
|
658
|
+
sdkOptions.resume = resumeData.sessionId;
|
|
659
|
+
if (resumeData.forkSession !== void 0) sdkOptions.forkSession = resumeData.forkSession;
|
|
660
|
+
if (resumeData.resumeSessionAt !== void 0) sdkOptions.resumeSessionAt = resumeData.resumeSessionAt;
|
|
661
|
+
} else sdkOptions.continue = true;
|
|
662
|
+
return {
|
|
663
|
+
...options,
|
|
664
|
+
sdkOptions
|
|
665
|
+
};
|
|
831
666
|
}
|
|
832
667
|
async function runClaudeGenerate(prompt, options, telemetry, runOptions) {
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
object
|
|
866
|
-
};
|
|
668
|
+
let text = "";
|
|
669
|
+
let structuredOutputValue;
|
|
670
|
+
const usage = createClaudeUsageCollector();
|
|
671
|
+
for await (const message of observeClaudeMessages(runClaude(prompt, options, runOptions?.abortSignal ?? runOptions?.signal, runOptions), telemetry)) {
|
|
672
|
+
usage.record(message);
|
|
673
|
+
if (message.type === "result") {
|
|
674
|
+
if (message.subtype !== "success") throw new Error(message.errors.join("\n") || `Claude Agent SDK failed with ${message.subtype}`);
|
|
675
|
+
text = message.result;
|
|
676
|
+
structuredOutputValue = getClaudeStructuredOutput(message);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
const totals = usage.totals();
|
|
680
|
+
const object = await getStructuredOutputFromValue(structuredOutputValue === void 0 ? text : structuredOutputValue, runOptions?.structuredOutput);
|
|
681
|
+
return {
|
|
682
|
+
content: [{
|
|
683
|
+
type: "text",
|
|
684
|
+
text
|
|
685
|
+
}],
|
|
686
|
+
finishReason: {
|
|
687
|
+
unified: "stop",
|
|
688
|
+
raw: "stop"
|
|
689
|
+
},
|
|
690
|
+
usage: usage.toV3Usage(),
|
|
691
|
+
response: {
|
|
692
|
+
id: (0, crypto.randomUUID)(),
|
|
693
|
+
modelId: getModelId(options),
|
|
694
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
695
|
+
},
|
|
696
|
+
providerMetadata: getClaudeProviderMetadata(options, totals),
|
|
697
|
+
costContext: getClaudeCostContext(options, totals),
|
|
698
|
+
object
|
|
699
|
+
};
|
|
867
700
|
}
|
|
868
701
|
function runClaudeAsMastraStream(prompt, options, runId, telemetry, runOptions) {
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
controller.enqueue({
|
|
929
|
-
type: "error",
|
|
930
|
-
runId,
|
|
931
|
-
from: stream.ChunkFrom.AGENT,
|
|
932
|
-
payload: { error }
|
|
933
|
-
});
|
|
934
|
-
controller.close();
|
|
935
|
-
}
|
|
936
|
-
}
|
|
937
|
-
});
|
|
702
|
+
return new stream_web.ReadableStream({ start: async (controller) => {
|
|
703
|
+
const textId = (0, crypto.randomUUID)();
|
|
704
|
+
const responseId = (0, crypto.randomUUID)();
|
|
705
|
+
const modelId = getModelId(options);
|
|
706
|
+
const usage = createClaudeUsageCollector();
|
|
707
|
+
let text = "";
|
|
708
|
+
let structuredOutputValue;
|
|
709
|
+
let sawDelta = false;
|
|
710
|
+
try {
|
|
711
|
+
enqueueStartChunks(controller, {
|
|
712
|
+
runId,
|
|
713
|
+
prompt,
|
|
714
|
+
textId,
|
|
715
|
+
responseId,
|
|
716
|
+
modelId,
|
|
717
|
+
providerMetadata: getClaudeProviderMetadata(options, usage.totals())
|
|
718
|
+
});
|
|
719
|
+
for await (const message of observeClaudeMessages(runClaude(prompt, options, runOptions?.abortSignal ?? runOptions?.signal, runOptions), telemetry)) {
|
|
720
|
+
usage.record(message);
|
|
721
|
+
const delta = getTextDelta(message);
|
|
722
|
+
if (delta) {
|
|
723
|
+
sawDelta = true;
|
|
724
|
+
text += delta;
|
|
725
|
+
enqueueTextDelta(controller, runId, textId, delta);
|
|
726
|
+
}
|
|
727
|
+
if (message.type === "result") {
|
|
728
|
+
if (message.subtype !== "success") throw new Error(message.errors.join("\n") || `Claude Agent SDK failed with ${message.subtype}`);
|
|
729
|
+
if (!sawDelta && message.result) {
|
|
730
|
+
text += message.result;
|
|
731
|
+
enqueueTextDelta(controller, runId, textId, message.result);
|
|
732
|
+
}
|
|
733
|
+
structuredOutputValue = getClaudeStructuredOutput(message);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
const totals = usage.totals();
|
|
737
|
+
const providerMetadata = getClaudeProviderMetadata(options, totals);
|
|
738
|
+
enqueueFinishChunks(controller, {
|
|
739
|
+
runId,
|
|
740
|
+
prompt,
|
|
741
|
+
textId,
|
|
742
|
+
text,
|
|
743
|
+
responseId,
|
|
744
|
+
modelId,
|
|
745
|
+
usage: usage.toLanguageModelUsage(),
|
|
746
|
+
providerMetadata,
|
|
747
|
+
costContext: getClaudeCostContext(options, totals),
|
|
748
|
+
object: await getStructuredOutputFromValue(structuredOutputValue === void 0 ? text : structuredOutputValue, runOptions?.structuredOutput)
|
|
749
|
+
});
|
|
750
|
+
controller.close();
|
|
751
|
+
} catch (error) {
|
|
752
|
+
controller.enqueue({
|
|
753
|
+
type: "error",
|
|
754
|
+
runId,
|
|
755
|
+
from: _mastra_core_stream.ChunkFrom.AGENT,
|
|
756
|
+
payload: { error }
|
|
757
|
+
});
|
|
758
|
+
controller.close();
|
|
759
|
+
}
|
|
760
|
+
} });
|
|
938
761
|
}
|
|
939
762
|
function runClaude(prompt, options, signal, runOptions) {
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
return claudeAgentSdk.query({
|
|
956
|
-
prompt,
|
|
957
|
-
options: queryOptions
|
|
958
|
-
});
|
|
763
|
+
const abortController = createAbortController(signal);
|
|
764
|
+
const queryOptions = {
|
|
765
|
+
...options.sdkOptions,
|
|
766
|
+
...runOptions?.sdkOptions
|
|
767
|
+
};
|
|
768
|
+
const outputSchema = getStructuredOutputSchema(runOptions?.structuredOutput);
|
|
769
|
+
if (outputSchema) queryOptions.outputFormat = {
|
|
770
|
+
type: "json_schema",
|
|
771
|
+
schema: outputSchema
|
|
772
|
+
};
|
|
773
|
+
if (abortController) queryOptions.abortController = abortController;
|
|
774
|
+
return (0, _anthropic_ai_claude_agent_sdk.query)({
|
|
775
|
+
prompt,
|
|
776
|
+
options: queryOptions
|
|
777
|
+
});
|
|
959
778
|
}
|
|
960
779
|
function getClaudeStructuredOutput(message) {
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
}
|
|
964
|
-
return message.structured_output;
|
|
780
|
+
if (message.type !== "result") return;
|
|
781
|
+
return message.structured_output;
|
|
965
782
|
}
|
|
966
783
|
async function* observeClaudeMessages(messages, telemetry) {
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
784
|
+
for await (const message of messages) {
|
|
785
|
+
recordClaudeToolTelemetry(message, telemetry);
|
|
786
|
+
yield message;
|
|
787
|
+
}
|
|
971
788
|
}
|
|
972
789
|
function recordClaudeToolTelemetry(message, telemetry) {
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
}
|
|
976
|
-
for (const toolResult of getClaudeToolResults(message)) {
|
|
977
|
-
telemetry.endToolCall(toolResult);
|
|
978
|
-
}
|
|
790
|
+
for (const toolCall of getClaudeToolCalls(message)) telemetry.startToolCall(toolCall);
|
|
791
|
+
for (const toolResult of getClaudeToolResults(message)) telemetry.endToolCall(toolResult);
|
|
979
792
|
}
|
|
980
793
|
function getClaudeToolCalls(message) {
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
input: block.input
|
|
988
|
-
}));
|
|
794
|
+
if (message.type !== "assistant") return [];
|
|
795
|
+
return getContentBlocks(message.message).filter(isRecord).filter((block) => block.type === "tool_use" && typeof block.id === "string" && typeof block.name === "string").map((block) => ({
|
|
796
|
+
toolCallId: block.id,
|
|
797
|
+
toolName: block.name,
|
|
798
|
+
input: block.input
|
|
799
|
+
}));
|
|
989
800
|
}
|
|
990
801
|
function getClaudeToolResults(message) {
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
isError: block.is_error === true
|
|
998
|
-
}));
|
|
802
|
+
if (message.type !== "user") return [];
|
|
803
|
+
return getContentBlocks(message.message).filter(isRecord).filter((block) => block.type === "tool_result" && typeof block.tool_use_id === "string").map((block) => ({
|
|
804
|
+
toolCallId: block.tool_use_id,
|
|
805
|
+
output: block.content,
|
|
806
|
+
isError: block.is_error === true
|
|
807
|
+
}));
|
|
999
808
|
}
|
|
1000
809
|
function getContentBlocks(message) {
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
}
|
|
1004
|
-
return Array.isArray(message.content) ? message.content : [];
|
|
810
|
+
if (!isRecord(message)) return [];
|
|
811
|
+
return Array.isArray(message.content) ? message.content : [];
|
|
1005
812
|
}
|
|
1006
813
|
function isRecord(value) {
|
|
1007
|
-
|
|
814
|
+
return value !== null && typeof value === "object";
|
|
1008
815
|
}
|
|
1009
816
|
function createAbortController(signal) {
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
signal.addEventListener("abort", () => controller.abort(signal.reason), { once: true });
|
|
1019
|
-
return controller;
|
|
817
|
+
if (!signal) return;
|
|
818
|
+
const controller = new AbortController();
|
|
819
|
+
if (signal.aborted) {
|
|
820
|
+
controller.abort(signal.reason);
|
|
821
|
+
return controller;
|
|
822
|
+
}
|
|
823
|
+
signal.addEventListener("abort", () => controller.abort(signal.reason), { once: true });
|
|
824
|
+
return controller;
|
|
1020
825
|
}
|
|
1021
826
|
function getModelId(options) {
|
|
1022
|
-
|
|
827
|
+
return options.sdkOptions?.model ?? MODEL_ID;
|
|
1023
828
|
}
|
|
1024
829
|
function createClaudeUsageCollector() {
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
toLanguageModelUsage() {
|
|
1058
|
-
return toLanguageModelUsage(toV3Usage(this.totals()));
|
|
1059
|
-
}
|
|
1060
|
-
};
|
|
830
|
+
const assistantUsageById = /* @__PURE__ */ new Map();
|
|
831
|
+
let resultUsage = {};
|
|
832
|
+
return {
|
|
833
|
+
record(message) {
|
|
834
|
+
if (message.type === "assistant") {
|
|
835
|
+
assistantUsageById.set(message.message.id, usageFromClaudeMessage(message.message.usage));
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
if (message.type === "result") resultUsage = {
|
|
839
|
+
...usageFromClaudeMessage(message.usage),
|
|
840
|
+
totalCostUsd: message.total_cost_usd,
|
|
841
|
+
modelUsage: message.modelUsage
|
|
842
|
+
};
|
|
843
|
+
},
|
|
844
|
+
totals() {
|
|
845
|
+
const assistantUsage = getAssistantUsageTotals(assistantUsageById);
|
|
846
|
+
if (hasAnyUsage(resultUsage)) return {
|
|
847
|
+
...resultUsage,
|
|
848
|
+
inputTokens: resultUsage.inputTokens ?? assistantUsage.inputTokens,
|
|
849
|
+
outputTokens: resultUsage.outputTokens ?? assistantUsage.outputTokens,
|
|
850
|
+
cacheReadInputTokens: resultUsage.cacheReadInputTokens ?? assistantUsage.cacheReadInputTokens,
|
|
851
|
+
cacheCreationInputTokens: resultUsage.cacheCreationInputTokens ?? assistantUsage.cacheCreationInputTokens
|
|
852
|
+
};
|
|
853
|
+
return assistantUsage;
|
|
854
|
+
},
|
|
855
|
+
toV3Usage() {
|
|
856
|
+
return toV3Usage(this.totals());
|
|
857
|
+
},
|
|
858
|
+
toLanguageModelUsage() {
|
|
859
|
+
return toLanguageModelUsage(toV3Usage(this.totals()));
|
|
860
|
+
}
|
|
861
|
+
};
|
|
1061
862
|
}
|
|
1062
863
|
function getAssistantUsageTotals(assistantUsageById) {
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
864
|
+
return [...assistantUsageById.values()].reduce((totals, item) => {
|
|
865
|
+
totals.inputTokens = addOptional(totals.inputTokens, item.inputTokens);
|
|
866
|
+
totals.outputTokens = addOptional(totals.outputTokens, item.outputTokens);
|
|
867
|
+
totals.cacheReadInputTokens = addOptional(totals.cacheReadInputTokens, item.cacheReadInputTokens);
|
|
868
|
+
totals.cacheCreationInputTokens = addOptional(totals.cacheCreationInputTokens, item.cacheCreationInputTokens);
|
|
869
|
+
return totals;
|
|
870
|
+
}, {});
|
|
1070
871
|
}
|
|
1071
872
|
function usageFromClaudeMessage(usage) {
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
cacheCreationInputTokens: getTokenTotal(record.cache_creation_input_tokens)
|
|
1081
|
-
};
|
|
873
|
+
if (!usage || typeof usage !== "object") return {};
|
|
874
|
+
const record = usage;
|
|
875
|
+
return {
|
|
876
|
+
inputTokens: getTokenTotal(record.input_tokens),
|
|
877
|
+
outputTokens: getTokenTotal(record.output_tokens),
|
|
878
|
+
cacheReadInputTokens: getTokenTotal(record.cache_read_input_tokens),
|
|
879
|
+
cacheCreationInputTokens: getTokenTotal(record.cache_creation_input_tokens)
|
|
880
|
+
};
|
|
1082
881
|
}
|
|
1083
882
|
function hasAnyUsage(usage) {
|
|
1084
|
-
|
|
883
|
+
return usage.inputTokens !== void 0 || usage.outputTokens !== void 0 || usage.cacheReadInputTokens !== void 0 || usage.cacheCreationInputTokens !== void 0 || usage.totalCostUsd !== void 0;
|
|
1085
884
|
}
|
|
1086
885
|
function addOptional(left, right) {
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
if (right === void 0) {
|
|
1091
|
-
return left;
|
|
1092
|
-
}
|
|
1093
|
-
return left + right;
|
|
886
|
+
if (left === void 0) return right;
|
|
887
|
+
if (right === void 0) return left;
|
|
888
|
+
return left + right;
|
|
1094
889
|
}
|
|
1095
890
|
function toV3Usage(usage) {
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
891
|
+
const noCache = usage.inputTokens;
|
|
892
|
+
const cacheRead = usage.cacheReadInputTokens;
|
|
893
|
+
const cacheWrite = usage.cacheCreationInputTokens;
|
|
894
|
+
const totalInputTokens = sumDefined(noCache, cacheRead, cacheWrite);
|
|
895
|
+
const outputTokens = usage.outputTokens;
|
|
896
|
+
return {
|
|
897
|
+
inputTokens: {
|
|
898
|
+
total: totalInputTokens,
|
|
899
|
+
noCache,
|
|
900
|
+
cacheRead,
|
|
901
|
+
cacheWrite
|
|
902
|
+
},
|
|
903
|
+
outputTokens: {
|
|
904
|
+
total: outputTokens,
|
|
905
|
+
text: outputTokens
|
|
906
|
+
}
|
|
907
|
+
};
|
|
1113
908
|
}
|
|
1114
909
|
function getClaudeProviderMetadata(options, usage) {
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
910
|
+
const queryOptions = options.sdkOptions;
|
|
911
|
+
return createProviderMetadata("claude", {
|
|
912
|
+
totalCostUsd: usage?.totalCostUsd,
|
|
913
|
+
model: getModelId(options),
|
|
914
|
+
cwd: queryOptions?.cwd,
|
|
915
|
+
permissionMode: queryOptions?.permissionMode,
|
|
916
|
+
maxTurns: queryOptions?.maxTurns,
|
|
917
|
+
allowedTools: queryOptions?.allowedTools,
|
|
918
|
+
disallowedTools: queryOptions?.disallowedTools,
|
|
919
|
+
usage
|
|
920
|
+
});
|
|
1126
921
|
}
|
|
1127
922
|
function getClaudeCostContext(options, usage) {
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
}
|
|
1143
|
-
};
|
|
923
|
+
if (typeof usage?.totalCostUsd !== "number") return;
|
|
924
|
+
return {
|
|
925
|
+
provider: "anthropic",
|
|
926
|
+
model: getModelId(options),
|
|
927
|
+
estimatedCost: usage.totalCostUsd,
|
|
928
|
+
costUnit: "USD",
|
|
929
|
+
costMetadata: {
|
|
930
|
+
source: "sdk_estimate",
|
|
931
|
+
sdkProvider: PROVIDER,
|
|
932
|
+
sdkCostField: "total_cost_usd",
|
|
933
|
+
scope: "query_total",
|
|
934
|
+
modelUsage: usage.modelUsage
|
|
935
|
+
}
|
|
936
|
+
};
|
|
1144
937
|
}
|
|
1145
938
|
function getTextDelta(message) {
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
if (event.type === "content_block_delta" && event.delta?.type === "text_delta") {
|
|
1151
|
-
return event.delta.text ?? "";
|
|
1152
|
-
}
|
|
1153
|
-
return "";
|
|
939
|
+
if (message.type !== "stream_event") return "";
|
|
940
|
+
const event = message.event;
|
|
941
|
+
if (event.type === "content_block_delta" && event.delta?.type === "text_delta") return event.delta.text ?? "";
|
|
942
|
+
return "";
|
|
1154
943
|
}
|
|
1155
944
|
function getTokenTotal(value) {
|
|
1156
|
-
|
|
945
|
+
return typeof value === "number" ? value : void 0;
|
|
1157
946
|
}
|
|
1158
|
-
|
|
947
|
+
//#endregion
|
|
1159
948
|
exports.ClaudeSDKAgent = ClaudeSDKAgent;
|
|
1160
|
-
|
|
949
|
+
|
|
1161
950
|
//# sourceMappingURL=index.cjs.map
|