agents 0.20.1 → 0.21.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.
Files changed (76) hide show
  1. package/README.md +50 -12
  2. package/dist/{agent-tool-types-BC-WFlsz.d.ts → agent-tool-types-CzGGB-20.d.ts} +375 -72
  3. package/dist/agent-tool-types.d.ts +1 -1
  4. package/dist/{agent-tools-DeHe9Xov.d.ts → agent-tools-zR2d5uij.d.ts} +2 -2
  5. package/dist/agent-tools.d.ts +24 -8
  6. package/dist/agent-tools.js +14 -6
  7. package/dist/agent-tools.js.map +1 -1
  8. package/dist/browser/ai.d.ts +5 -3
  9. package/dist/browser/ai.js +86 -7
  10. package/dist/browser/ai.js.map +1 -1
  11. package/dist/browser/index.d.ts +1 -1
  12. package/dist/browser/index.js +1 -1
  13. package/dist/browser/tanstack-ai.js +13 -1
  14. package/dist/browser/tanstack-ai.js.map +1 -1
  15. package/dist/chat/index.d.ts +31 -2
  16. package/dist/chat/index.js +57 -2
  17. package/dist/chat/index.js.map +1 -1
  18. package/dist/chat/react.d.ts +5 -179
  19. package/dist/chat/react.js +18 -555
  20. package/dist/chat/react.js.map +1 -1
  21. package/dist/chat/transport.d.ts +10 -0
  22. package/dist/chat/transport.js +2 -0
  23. package/dist/chat-sdk/index.d.ts +1 -1
  24. package/dist/client.d.ts +1 -1
  25. package/dist/{connector-v2M1zlZp.d.ts → connector-CkQD4MK3.d.ts} +20 -3
  26. package/dist/{connector-KEJnl6e5.js → connector-CptFKzRh.js} +158 -40
  27. package/dist/connector-CptFKzRh.js.map +1 -0
  28. package/dist/index.d.ts +20 -12
  29. package/dist/index.js +5 -4
  30. package/dist/index.js.map +1 -1
  31. package/dist/mcp/client.d.ts +20 -20
  32. package/dist/mcp/index.d.ts +35 -35
  33. package/dist/observability/ai/index.d.ts +1 -130
  34. package/dist/observability/ai/index.js +39 -399
  35. package/dist/observability/ai/index.js.map +1 -1
  36. package/dist/{wire-types-CU9rLoeS.js → protocol-Dqc2MQxo.js} +2 -46
  37. package/dist/protocol-Dqc2MQxo.js.map +1 -0
  38. package/dist/react.d.ts +1 -1
  39. package/dist/react.js +5 -8
  40. package/dist/react.js.map +1 -1
  41. package/dist/serializable.d.ts +1 -1
  42. package/dist/sub-routing.d.ts +18 -6
  43. package/dist/sub-routing.js +92 -2
  44. package/dist/sub-routing.js.map +1 -1
  45. package/dist/wire-types-CnMt6_HR.js +47 -0
  46. package/dist/wire-types-CnMt6_HR.js.map +1 -0
  47. package/dist/workflow-types.d.ts +25 -25
  48. package/dist/workflow-types.js.map +1 -1
  49. package/dist/workflows.d.ts +22 -22
  50. package/dist/ws-chat-transport-CIoOBbO7.js +561 -0
  51. package/dist/ws-chat-transport-CIoOBbO7.js.map +1 -0
  52. package/dist/ws-chat-transport-UNRIS2xl.d.ts +184 -0
  53. package/docs/adding-to-existing-project.md +4 -2
  54. package/docs/agent-class.md +1 -1
  55. package/docs/agent-tools.md +29 -0
  56. package/docs/browse-the-web.md +16 -1
  57. package/docs/chat-agents.md +3 -1
  58. package/docs/client-sdk.md +12 -8
  59. package/docs/configuration.md +7 -1
  60. package/docs/cross-domain-authentication.md +7 -35
  61. package/docs/email.md +2 -13
  62. package/docs/human-in-the-loop.md +15 -12
  63. package/docs/long-running-agents.md +11 -11
  64. package/docs/mcp-servers.md +6 -0
  65. package/docs/mcp-transports.md +18 -12
  66. package/docs/migration-to-ai-sdk-v5.md +2 -2
  67. package/docs/migration-to-ai-sdk-v6.md +5 -1
  68. package/docs/observability.md +22 -66
  69. package/docs/routing.md +27 -0
  70. package/docs/sub-agents.md +47 -2
  71. package/docs/webhooks.md +109 -136
  72. package/docs/workflows.md +9 -1
  73. package/package.json +13 -4
  74. package/dist/connector-KEJnl6e5.js.map +0 -1
  75. package/dist/wire-types-CU9rLoeS.js.map +0 -1
  76. package/dist/workflow-types-Baz_PO5v.d.ts +0 -280
@@ -38,7 +38,6 @@ function readNestedTokenField(value, key) {
38
38
  const TraceAttribute = {
39
39
  Cloudflare: {
40
40
  AIGatewayLogID: "cloudflare.ai_gateway.log.id",
41
- CallID: "cloudflare.agents.call.id",
42
41
  IntegrationName: "cloudflare.agents.integration.name",
43
42
  MetadataPrefix: "cloudflare.agents.metadata.",
44
43
  OperationName: "cloudflare.agents.operation.name",
@@ -195,7 +194,7 @@ function operationSpan(input) {
195
194
  return {
196
195
  attributes: {
197
196
  ...input.attributes,
198
- [TraceAttribute.Cloudflare.IntegrationName]: input.integration,
197
+ [TraceAttribute.Cloudflare.IntegrationName]: "ai-sdk",
199
198
  [TraceAttribute.Cloudflare.OperationName]: input.operation,
200
199
  [TraceAttribute.GenAI.AgentID]: input.context?.agentId,
201
200
  [TraceAttribute.GenAI.AgentName]: input.context?.agentName,
@@ -213,7 +212,7 @@ function modelCallSpan(input) {
213
212
  return {
214
213
  attributes: {
215
214
  ...input.attributes,
216
- [TraceAttribute.Cloudflare.IntegrationName]: input.integration,
215
+ [TraceAttribute.Cloudflare.IntegrationName]: "ai-sdk",
217
216
  [TraceAttribute.Cloudflare.OperationName]: input.operation,
218
217
  [TraceAttribute.GenAI.OperationName]: TraceAttribute.GenAI.OperationNameValueChat,
219
218
  [TraceAttribute.GenAI.ProviderName]: normalizeProviderName(input.provider),
@@ -240,7 +239,7 @@ function requestAttributes(request, model) {
240
239
  function toolCallSpan(input) {
241
240
  return {
242
241
  attributes: {
243
- [TraceAttribute.Cloudflare.IntegrationName]: input.integration,
242
+ [TraceAttribute.Cloudflare.IntegrationName]: "ai-sdk",
244
243
  [TraceAttribute.Cloudflare.OperationName]: input.operation,
245
244
  [TraceAttribute.GenAI.OperationName]: TraceAttribute.GenAI.OperationNameValueExecuteTool,
246
245
  [TraceAttribute.GenAI.ToolCallID]: input.toolCallId,
@@ -291,14 +290,14 @@ function totalTokens(usage) {
291
290
  return usage?.inputTokens !== void 0 && usage.outputTokens !== void 0 ? usage.inputTokens + usage.outputTokens : void 0;
292
291
  }
293
292
  //#endregion
294
- //#region src/observability/ai/v6/extract.ts
293
+ //#region src/observability/ai/wrapper/extract.ts
295
294
  function finishAttributesFromResult(result, options = {}) {
296
295
  return finishAttributes({
297
296
  aiGatewayLogId: options.aiGatewayLogId,
298
- finishReason: extractFinishReason$1(result),
297
+ finishReason: extractFinishReason(result),
299
298
  response: options.includeResponse ? extractResponseInfo(result) : void 0,
300
299
  toolCallCount: extractToolCallCount(result),
301
- usage: extractAISDKv6TokenUsage(result)
300
+ usage: extractAISDKTokenUsage(result)
302
301
  });
303
302
  }
304
303
  function extractRequestSummary(params, operation) {
@@ -314,7 +313,7 @@ function extractRequestSummary(params, operation) {
314
313
  topP: readNumber(params.topP)
315
314
  };
316
315
  }
317
- /** Extracts model identity from an AI SDK v6 model object. */
316
+ /** Extracts model identity from an AI SDK model object. */
318
317
  function extractModelInfo(value) {
319
318
  if (typeof value === "string") return value.length > 0 ? {
320
319
  modelId: value,
@@ -331,13 +330,11 @@ function extractModelInfo(value) {
331
330
  };
332
331
  }
333
332
  /**
334
- * Extracts token usage from an AI SDK v6 result or stream chunk.
335
- *
336
- * AI SDK v6 exposes usage as `{ inputTokens, outputTokens, totalTokens }`
337
- * where `inputTokens`/`outputTokens` may be plain numbers or nested objects
338
- * like `{ total, cacheRead, cacheWrite }` / `{ total, reasoning }`.
333
+ * Extracts token usage from an AI SDK result or stream chunk across supported
334
+ * majors. Token counts may be plain numbers or nested objects such as
335
+ * `{ total, cacheRead, cacheWrite }` / `{ total, reasoning }`.
339
336
  */
340
- function extractAISDKv6TokenUsage(value) {
337
+ function extractAISDKTokenUsage(value) {
341
338
  if (typeof value !== "object" || value === null) return;
342
339
  const record = value;
343
340
  const raw = record.totalUsage ?? record.usage;
@@ -365,9 +362,9 @@ function extractToolCallCount(value) {
365
362
  return Array.isArray(toolCalls) && toolCalls.length > 0 ? toolCalls.length : void 0;
366
363
  }
367
364
  /**
368
- * Reads a finish reason from an AI SDK v6 result or `finish`-type stream chunk.
365
+ * Reads a finish reason from an AI SDK result or `finish`-type stream chunk.
369
366
  */
370
- function extractFinishReason$1(value) {
367
+ function extractFinishReason(value) {
371
368
  if (typeof value !== "object" || value === null) return;
372
369
  const finishReason = value.finishReason;
373
370
  if (typeof finishReason === "string") return finishReason;
@@ -805,7 +802,7 @@ function byteLength(value) {
805
802
  return new TextEncoder().encode(value).length;
806
803
  }
807
804
  //#endregion
808
- //#region src/observability/ai/v6/streams.ts
805
+ //#region src/observability/ai/wrapper/streams.ts
809
806
  function finishWhenStreamCompletes(result, span, options = {}) {
810
807
  return patchStreamFields(result, {
811
808
  onComplete: (summary) => {
@@ -1043,8 +1040,8 @@ function createStreamState(hooks, startedAtMs, initialAIGatewayLogId, storeMessa
1043
1040
  if (isErrorChunk(chunk)) observedError = { cause: chunk.error };
1044
1041
  if (isAbortChunk(chunk)) observedAbort = true;
1045
1042
  if (isToolCallChunk(chunk)) toolCallCount += 1;
1046
- finishReason = extractFinishReason$1(chunk) ?? finishReason;
1047
- usage = extractAISDKv6TokenUsage(chunk) ?? usage;
1043
+ finishReason = extractFinishReason(chunk) ?? finishReason;
1044
+ usage = extractAISDKTokenUsage(chunk) ?? usage;
1048
1045
  response = extractResponseInfo(chunk) ?? response;
1049
1046
  }
1050
1047
  };
@@ -1087,7 +1084,7 @@ function isAsyncIterable$1(value) {
1087
1084
  return typeof value === "object" && value !== null && Symbol.asyncIterator in value && typeof value[Symbol.asyncIterator] === "function";
1088
1085
  }
1089
1086
  //#endregion
1090
- //#region src/observability/ai/v6/model.ts
1087
+ //#region src/observability/ai/wrapper/model.ts
1091
1088
  function wrapModel(tracer, wrapLanguageModel, model, parentOperation, storeMessages, boundToInvocation = false) {
1092
1089
  if (!wrapLanguageModel) return model;
1093
1090
  if (typeof model !== "object" || model === null) return model;
@@ -1146,7 +1143,6 @@ function recordAIGatewayLogOnError(span, cause, capturedLogId) {
1146
1143
  function modelCallSpanForModel(operation, model, params, parentOperation, storeMessages) {
1147
1144
  const record = typeof params === "object" && params !== null ? params : {};
1148
1145
  const span = modelCallSpan({
1149
- integration: "ai-sdk",
1150
1146
  model: model?.modelId,
1151
1147
  operation,
1152
1148
  provider: model?.provider,
@@ -1161,7 +1157,7 @@ function modelCallSpanForModel(operation, model, params, parentOperation, storeM
1161
1157
  };
1162
1158
  }
1163
1159
  //#endregion
1164
- //#region src/observability/ai/v6/tools.ts
1160
+ //#region src/observability/ai/wrapper/tools.ts
1165
1161
  function wrapTools(tracer, tools, storeTools, boundToInvocation = false, approvedToolCalls) {
1166
1162
  if (typeof tools !== "object" || tools === null) return tools;
1167
1163
  const toolRecord = tools;
@@ -1183,7 +1179,6 @@ function wrapTool(tracer, toolName, tool, storeTools, boundToInvocation, approve
1183
1179
  const originalExecute = execute.bind(tool);
1184
1180
  wrappedTool.execute = (...args) => {
1185
1181
  const span = toolCallSpan({
1186
- integration: "ai-sdk",
1187
1182
  operation: "tool.execute",
1188
1183
  toolCallId: extractToolCallId(args[1]),
1189
1184
  toolName
@@ -1225,7 +1220,7 @@ function wrapApprovalCheck(tracer, wrappedTool, toolRecord, tool, toolName, boun
1225
1220
  /** Instruments AI SDK v7's top-level tool approval policy. */
1226
1221
  function wrapToolApprovalPolicy(tracer, policy, approvedToolCalls, boundToInvocation = false) {
1227
1222
  if (typeof policy === "function") return (...args) => {
1228
- const toolCall = recordValue$1(recordValue$1(args[0])?.toolCall);
1223
+ const toolCall = recordValue(recordValue(args[0])?.toolCall);
1229
1224
  return observePolicyResult(policy(...args), readString(toolCall?.toolName) ?? "tool", readString(toolCall?.toolCallId), tracer, approvedToolCalls, boundToInvocation);
1230
1225
  };
1231
1226
  if (typeof policy !== "object" || policy === null) return policy;
@@ -1234,7 +1229,7 @@ function wrapToolApprovalPolicy(tracer, policy, approvedToolCalls, boundToInvoca
1234
1229
  function observePolicyResult(result, toolName, toolCallId, tracer, approvedToolCalls, boundToInvocation = false) {
1235
1230
  const observe = (status) => {
1236
1231
  if (toolCallId === void 0) return status;
1237
- const type = typeof status === "string" ? status : readString(recordValue$1(status)?.type);
1232
+ const type = typeof status === "string" ? status : readString(recordValue(status)?.type);
1238
1233
  if (type === "approved") approvedToolCalls.set(toolCallId, toolName);
1239
1234
  else if (type === "user-approval" || type === "denied") recordApprovalSegment(tracer, toolName, toolCallId, type === "denied" ? "denied" : "requested", boundToInvocation);
1240
1235
  return status;
@@ -1247,7 +1242,6 @@ function recordDeniedApprovalResponses(tracer, messages) {
1247
1242
  }
1248
1243
  function recordApprovalSegment(tracer, toolName, toolCallId, state, boundToInvocation = false) {
1249
1244
  const tool = toolCallSpan({
1250
- integration: "ai-sdk",
1251
1245
  operation: "tool.approval",
1252
1246
  toolCallId,
1253
1247
  toolName
@@ -1361,19 +1355,19 @@ function extractToolCallId(options) {
1361
1355
  function isAsyncIterable(value) {
1362
1356
  return typeof value === "object" && value !== null && Symbol.asyncIterator in value && typeof value[Symbol.asyncIterator] === "function";
1363
1357
  }
1364
- function recordValue$1(value) {
1358
+ function recordValue(value) {
1365
1359
  return typeof value === "object" && value !== null ? value : void 0;
1366
1360
  }
1367
1361
  function isPromiseLike(value) {
1368
1362
  return value !== null && value !== void 0 && (typeof value === "object" || typeof value === "function") && "then" in value && typeof value.then === "function";
1369
1363
  }
1370
1364
  //#endregion
1371
- //#region src/observability/ai/v6/wrap.ts
1365
+ //#region src/observability/ai/wrapper/wrap.ts
1372
1366
  /**
1373
- * Wraps an AI SDK namespace object with v6 tracing while preserving its public
1374
- * shape and overloaded call signatures.
1367
+ * Wraps an AI SDK namespace object with tracing while preserving its public
1368
+ * shape and overloaded call signatures across supported majors.
1375
1369
  */
1376
- function createAISDKV6Wrapper(ai, instrumentation) {
1370
+ function createAISDKWrapper(ai, instrumentation) {
1377
1371
  const target = isModuleNamespace(ai) ? Object.setPrototypeOf({}, ai) : ai;
1378
1372
  const wrapperCache = /* @__PURE__ */ new Map();
1379
1373
  return new Proxy(target, { get(proxyTarget, property, receiver) {
@@ -1381,7 +1375,7 @@ function createAISDKV6Wrapper(ai, instrumentation) {
1381
1375
  if (isWrappedOperationName(property) && typeof original === "function") {
1382
1376
  let wrapper = wrapperCache.get(property);
1383
1377
  if (!wrapper) {
1384
- wrapper = createOperationWrapper(property, toAISDKV6Operation(original), readWrapLanguageModel(ai), instrumentation);
1378
+ wrapper = createOperationWrapper(property, toAISDKOperation(original), readWrapLanguageModel(ai), instrumentation);
1385
1379
  wrapperCache.set(property, wrapper);
1386
1380
  }
1387
1381
  return wrapper;
@@ -1394,7 +1388,7 @@ function readWrapLanguageModel(ai) {
1394
1388
  if (typeof value !== "function") return;
1395
1389
  return value;
1396
1390
  }
1397
- function toAISDKV6Operation(value) {
1391
+ function toAISDKOperation(value) {
1398
1392
  return value;
1399
1393
  }
1400
1394
  function isModuleNamespace(value) {
@@ -1414,7 +1408,7 @@ function createOperationWrapper(operationName, operation, wrapLanguageModel, ins
1414
1408
  storeMessages: instrumentation.options?.storeMessages === true,
1415
1409
  storeTools: instrumentation.options?.storeTools === true
1416
1410
  };
1417
- if (isStreamOperation$1(operationName)) return (params, ...args) => {
1411
+ if (isStreamOperation(operationName)) return (params, ...args) => {
1418
1412
  const boundToInvocation = isAISDKInvocationBounded(params);
1419
1413
  return instrumentation.tracer.openSpan(operationSpanName(agentNameForCall(params)), {}, (operationSpan) => {
1420
1414
  if (!operationSpan.isTraced) {
@@ -1454,21 +1448,21 @@ function agentNameForCall(params) {
1454
1448
  const telemetry = telemetryOptions(params);
1455
1449
  const metadata = telemetryMetadata(params);
1456
1450
  const runtimeContext = runtimeContextRecord(params);
1457
- return metadataValue$1(metadata, "agentName", "gen_ai.agent.name") ?? metadataValue$1(runtimeContext, "agentName", "gen_ai.agent.name") ?? readString(telemetry?.functionId);
1451
+ return metadataValue(metadata, "agentName", "gen_ai.agent.name") ?? metadataValue(runtimeContext, "agentName", "gen_ai.agent.name") ?? readString(telemetry?.functionId);
1458
1452
  }
1459
1453
  function operationParamsForCall(params, operationName, wrapLanguageModel, tracer, storage, boundToInvocation = false) {
1460
1454
  const approvedToolCalls = /* @__PURE__ */ new Map();
1461
1455
  return {
1462
1456
  ...params,
1463
1457
  ...shouldWrapTools(operationName) && params.tools !== void 0 ? { tools: wrapTools(tracer, params.tools, storage.storeTools, boundToInvocation, approvedToolCalls) } : {},
1464
- ...params.toolApproval !== void 0 ? { toolApproval: wrapToolApprovalPolicy(tracer, params.toolApproval, approvedToolCalls) } : {},
1458
+ ...params.toolApproval !== void 0 ? { toolApproval: wrapToolApprovalPolicy(tracer, params.toolApproval, approvedToolCalls, boundToInvocation) } : {},
1465
1459
  ...params.model !== void 0 ? { model: wrapModel(tracer, wrapLanguageModel, params.model, operationName, storage.storeMessages, boundToInvocation) } : {}
1466
1460
  };
1467
1461
  }
1468
1462
  function canWrapModel(wrapLanguageModel, model) {
1469
1463
  return wrapLanguageModel !== void 0 && typeof model === "object" && model !== null;
1470
1464
  }
1471
- function isStreamOperation$1(operationName) {
1465
+ function isStreamOperation(operationName) {
1472
1466
  return operationName === "streamObject" || operationName === "streamText";
1473
1467
  }
1474
1468
  function shouldWrapTools(operationName) {
@@ -1485,7 +1479,6 @@ function operationSpanForCall(operation, model, params, options) {
1485
1479
  ...contextAttributes(params, options)
1486
1480
  },
1487
1481
  context: semanticContext(params),
1488
- integration: "ai-sdk",
1489
1482
  model: model?.modelId,
1490
1483
  operation,
1491
1484
  provider: model?.provider,
@@ -1573,15 +1566,15 @@ function semanticContext(params) {
1573
1566
  const telemetry = telemetryOptions(params);
1574
1567
  const metadata = telemetryMetadata(params);
1575
1568
  const runtimeContext = runtimeContextRecord(params);
1576
- const fromContext = (key, semanticKey) => isExcludedFromContext(params, key) ? void 0 : metadataValue$1(runtimeContext, key, semanticKey);
1569
+ const fromContext = (key, semanticKey) => isExcludedFromContext(params, key) ? void 0 : metadataValue(runtimeContext, key, semanticKey);
1577
1570
  return {
1578
- agentId: metadataValue$1(metadata, "agentId", "gen_ai.agent.id") ?? fromContext("agentId", "gen_ai.agent.id"),
1579
- agentName: metadataValue$1(metadata, "agentName", "gen_ai.agent.name") ?? fromContext("agentName", "gen_ai.agent.name") ?? readString(telemetry?.functionId),
1580
- agentVersion: metadataValue$1(metadata, "agentVersion", "gen_ai.agent.version") ?? fromContext("agentVersion", "gen_ai.agent.version"),
1581
- conversationId: metadataValue$1(metadata, "conversationId", "gen_ai.conversation.id") ?? fromContext("conversationId", "gen_ai.conversation.id")
1571
+ agentId: metadataValue(metadata, "agentId", "gen_ai.agent.id") ?? fromContext("agentId", "gen_ai.agent.id"),
1572
+ agentName: metadataValue(metadata, "agentName", "gen_ai.agent.name") ?? fromContext("agentName", "gen_ai.agent.name") ?? readString(telemetry?.functionId),
1573
+ agentVersion: metadataValue(metadata, "agentVersion", "gen_ai.agent.version") ?? fromContext("agentVersion", "gen_ai.agent.version"),
1574
+ conversationId: metadataValue(metadata, "conversationId", "gen_ai.conversation.id") ?? fromContext("conversationId", "gen_ai.conversation.id")
1582
1575
  };
1583
1576
  }
1584
- function metadataValue$1(metadata, key, semanticKey) {
1577
+ function metadataValue(metadata, key, semanticKey) {
1585
1578
  return readString(metadata?.[key] ?? metadata?.[semanticKey]);
1586
1579
  }
1587
1580
  /**
@@ -1604,370 +1597,17 @@ function isAISDKInvocationBounded(params) {
1604
1597
  return params[invocationBounded] === true || __DO_NOT_USE_WILL_BREAK__agentContext.getStore()?.connection !== void 0;
1605
1598
  }
1606
1599
  //#endregion
1607
- //#region src/observability/ai/v7/extract.ts
1608
- /** Extracts the safe operation name from an AI SDK v7 operation id. */
1609
- function operationNameFromId(operationId) {
1610
- const value = readString(operationId);
1611
- if (value === void 0) return "ai-sdk";
1612
- return value.startsWith("ai.") ? value.slice(3) : value;
1613
- }
1614
- /**
1615
- * Extracts safe GenAI semantic context from an AI SDK v7 event. The AI SDK's
1616
- * canonical OpenTelemetry projection maps `functionId` to agent name. v7 has
1617
- * no telemetry metadata bag, so other identity fields come from the SDK-
1618
- * filtered runtime context only when the caller explicitly includes them.
1619
- */
1620
- function semanticContextFromEvent(event) {
1621
- const record = eventRecord(event);
1622
- const runtimeContext = typeof record.runtimeContext === "object" && record.runtimeContext !== null ? record.runtimeContext : void 0;
1623
- return {
1624
- agentId: metadataValue(runtimeContext, "agentId", "gen_ai.agent.id"),
1625
- agentName: metadataValue(runtimeContext, "agentName", "gen_ai.agent.name") ?? readString(record.functionId),
1626
- agentVersion: metadataValue(runtimeContext, "agentVersion", "gen_ai.agent.version"),
1627
- conversationId: metadataValue(runtimeContext, "conversationId", "gen_ai.conversation.id")
1628
- };
1629
- }
1630
- /** Extracts safe request settings from an AI SDK v7 event. */
1631
- function requestSummaryFromEvent(event, operationName) {
1632
- const record = eventRecord(event);
1633
- return {
1634
- frequencyPenalty: readNumber(record.frequencyPenalty),
1635
- maxTokens: readNumber(record.maxOutputTokens ?? record.maxTokens),
1636
- outputType: operationName === "generateObject" || operationName === "streamObject" ? "json" : "text",
1637
- presencePenalty: readNumber(record.presencePenalty),
1638
- seed: readNumber(record.seed),
1639
- stream: operationName === "streamText" || operationName === "streamObject",
1640
- temperature: readNumber(record.temperature),
1641
- topK: readNumber(record.topK),
1642
- topP: readNumber(record.topP)
1643
- };
1644
- }
1645
- /** Extracts safe finish attributes from an AI SDK v7 result-like event. */
1646
- function finishAttributesFromEvent(event, options = {}) {
1647
- const record = eventRecord(event);
1648
- return finishAttributes({
1649
- aiGatewayLogId: options.includeAIGatewayLog ? extractAIGatewayLogId(record) : void 0,
1650
- finishReason: extractFinishReason(record),
1651
- response: options.includeResponse ? responseSummaryFromEvent(record) : void 0,
1652
- timeToFirstChunkSeconds: options.includePerformance ? timeToFirstChunkSeconds(record) : void 0,
1653
- usage: tokenUsageFromEvent(record)
1654
- });
1655
- }
1656
- /** Builds correlation attributes for AI SDK v7 callback ids. */
1657
- function correlationAttributes(input) {
1658
- return {
1659
- [TraceAttribute.Cloudflare.CallID]: input.callId,
1660
- [TraceAttribute.GenAI.ToolCallID]: input.toolCallId
1661
- };
1662
- }
1663
- function metadataValue(metadata, key, semanticKey) {
1664
- return readString(metadata?.[key] ?? metadata?.[semanticKey]);
1665
- }
1666
- function eventRecord(event) {
1667
- return event;
1668
- }
1669
- function extractFinishReason(event) {
1670
- const finishReason = event.finishReason;
1671
- if (typeof finishReason === "string") return finishReason;
1672
- if (typeof finishReason === "object" && finishReason !== null) return readString(finishReason.unified);
1673
- }
1674
- function responseSummaryFromEvent(event) {
1675
- const response = typeof event.response === "object" && event.response !== null ? event.response : void 0;
1676
- const id = readString(event.responseId ?? response?.id);
1677
- const model = readString(event.responseModel ?? response?.modelId ?? response?.model);
1678
- if (id === void 0 && model === void 0) return;
1679
- return {
1680
- ...id !== void 0 ? { id } : {},
1681
- ...model !== void 0 ? { model } : {}
1682
- };
1683
- }
1684
- function tokenUsageFromEvent(event) {
1685
- const raw = event.totalUsage ?? event.usage;
1686
- if (typeof raw !== "object" || raw === null) return;
1687
- const usage = raw;
1688
- const inputTokens = readTokenCount(usage.inputTokens);
1689
- const outputTokens = readTokenCount(usage.outputTokens);
1690
- const cacheReadInputTokens = readNestedTokenField(usage.inputTokenDetails, "cacheReadTokens") ?? readNestedTokenField(usage.inputTokens, "cacheRead") ?? readNumber(usage.cachedInputTokens);
1691
- const cacheCreationInputTokens = readNestedTokenField(usage.inputTokenDetails, "cacheWriteTokens") ?? readNestedTokenField(usage.inputTokens, "cacheWrite");
1692
- const reasoningTokens = readNestedTokenField(usage.outputTokenDetails, "reasoningTokens") ?? readNestedTokenField(usage.outputTokens, "reasoning") ?? readNumber(usage.reasoningTokens);
1693
- if (inputTokens === void 0 && outputTokens === void 0 && cacheReadInputTokens === void 0 && cacheCreationInputTokens === void 0 && reasoningTokens === void 0) return;
1694
- return {
1695
- ...cacheCreationInputTokens !== void 0 ? { cacheCreationInputTokens } : {},
1696
- ...cacheReadInputTokens !== void 0 ? { cacheReadInputTokens } : {},
1697
- ...inputTokens !== void 0 ? { inputTokens } : {},
1698
- ...outputTokens !== void 0 ? { outputTokens } : {},
1699
- ...reasoningTokens !== void 0 ? { reasoningTokens } : {}
1700
- };
1701
- }
1702
- function timeToFirstChunkSeconds(event) {
1703
- const milliseconds = readNumber((typeof event.performance === "object" && event.performance !== null ? event.performance : void 0)?.timeToFirstOutputMs);
1704
- return milliseconds === void 0 ? void 0 : milliseconds / 1e3;
1705
- }
1706
- //#endregion
1707
- //#region src/observability/ai/v7/telemetry.ts
1708
- /**
1709
- * Creates an AI SDK v7 `Telemetry` object that projects callback events into
1710
- * Cloudflare-compatible GenAI spans without recording raw prompts or outputs.
1711
- */
1712
- function createAISDKV7Telemetry(instrumentation) {
1713
- const storeMessages = instrumentation.options?.storeMessages === true;
1714
- const storeTools = instrumentation.options?.storeTools === true;
1715
- const operations = /* @__PURE__ */ new Map();
1716
- const modelSpans = /* @__PURE__ */ new Map();
1717
- const toolSpans = /* @__PURE__ */ new Map();
1718
- const toolSpanKey = (callId, toolCallId) => `${callId}:${toolCallId}`;
1719
- const finishOperation = (event) => {
1720
- const state = operations.get(event.callId);
1721
- if (!state) return;
1722
- finishOpenModelSpans(event.callId, void 0, modelSpans, instrumentation.tracer);
1723
- finishOpenToolSpans(event.callId, void 0, toolSpans, instrumentation.tracer);
1724
- state.span.finish(finishAttributesFromEvent(event));
1725
- operations.delete(event.callId);
1726
- };
1727
- return {
1728
- onStart(event) {
1729
- const operationName = supportedOperationName(operationNameFromId(event.operationId));
1730
- if (!operationName) return;
1731
- const span = operationSpan({
1732
- attributes: {
1733
- ...correlationAttributes({ callId: event.callId }),
1734
- ...runtimeContextAttributes(event.runtimeContext)
1735
- },
1736
- context: semanticContextFromEvent(event),
1737
- integration: "ai-sdk",
1738
- model: readString(event.modelId),
1739
- operation: operationName,
1740
- provider: readString(event.provider),
1741
- request: requestSummaryFromEvent(event, operationName)
1742
- });
1743
- const operation = instrumentation.tracer.openSpan(span.name, span.attributes, (activeSpan) => activeSpan);
1744
- operations.set(event.callId, {
1745
- callId: event.callId,
1746
- operationName,
1747
- span: operation
1748
- });
1749
- },
1750
- onLanguageModelCallStart(event) {
1751
- const state = operations.get(event.callId);
1752
- if (!state) return;
1753
- const span = modelCallSpan({
1754
- attributes: {
1755
- ...correlationAttributes({ callId: event.callId }),
1756
- ...inputMessageAttributes(event, storeMessages)
1757
- },
1758
- integration: "ai-sdk",
1759
- model: readString(event.modelId),
1760
- operation: isStreamOperation(state.operationName) ? "doStream" : "doGenerate",
1761
- provider: readString(event.provider),
1762
- request: requestSummaryFromEvent(event, state.operationName)
1763
- });
1764
- const spans = modelSpans.get(event.callId) ?? [];
1765
- spans.push({ spanSpec: span });
1766
- modelSpans.set(event.callId, spans);
1767
- },
1768
- onLanguageModelCallEnd(event) {
1769
- const state = shiftModelSpan(modelSpans, event.callId);
1770
- if (!state) return;
1771
- (state.span ?? instrumentation.tracer.openSpan(state.spanSpec.name, state.spanSpec.attributes, (activeSpan) => activeSpan)).finish({
1772
- ...finishAttributesFromEvent(event, {
1773
- includeAIGatewayLog: true,
1774
- includePerformance: true,
1775
- includeResponse: true
1776
- }),
1777
- ...outputMessageAttributes(event, storeMessages)
1778
- });
1779
- },
1780
- onToolExecutionStart(event) {
1781
- const toolCallId = readString(event.toolCall.toolCallId);
1782
- if (toolCallId === void 0 || !operations.has(event.callId)) return;
1783
- const toolName = readString(event.toolCall.toolName) ?? "tool";
1784
- const span = toolCallSpan({
1785
- integration: "ai-sdk",
1786
- operation: "tool.execute",
1787
- toolName
1788
- });
1789
- toolSpans.set(toolSpanKey(event.callId, toolCallId), {
1790
- callId: event.callId,
1791
- spanSpec: {
1792
- name: span.name,
1793
- attributes: {
1794
- ...span.attributes,
1795
- ...correlationAttributes({
1796
- callId: event.callId,
1797
- toolCallId
1798
- }),
1799
- ...toolInputAttributes(event.toolCall.input, storeTools),
1800
- ...toolContextAttributes(toolName, event.toolContext)
1801
- }
1802
- }
1803
- });
1804
- },
1805
- onToolExecutionEnd(event) {
1806
- const toolCallId = readString(event.toolCall.toolCallId);
1807
- if (toolCallId === void 0) return;
1808
- const state = toolSpans.get(toolSpanKey(event.callId, toolCallId));
1809
- if (!state) return;
1810
- const span = state.span ?? instrumentation.tracer.openSpan(state.spanSpec.name, state.spanSpec.attributes, (activeSpan) => activeSpan);
1811
- if (event.toolOutput?.type === "tool-error") span.fail(event.toolOutput.error);
1812
- else span.finish(toolOutputAttributes(event.toolOutput?.output, storeTools));
1813
- toolSpans.delete(toolSpanKey(event.callId, toolCallId));
1814
- },
1815
- onAbort(event) {
1816
- const cause = { name: "AbortError" };
1817
- finishOpenModelSpans(event.callId, cause, modelSpans, instrumentation.tracer);
1818
- finishOpenToolSpans(event.callId, cause, toolSpans, instrumentation.tracer);
1819
- const state = operations.get(event.callId);
1820
- if (!state) return;
1821
- state.span.fail(cause);
1822
- operations.delete(event.callId);
1823
- },
1824
- onEnd: finishOperation,
1825
- onError(event) {
1826
- const errorEvent = eventObject(event);
1827
- const callId = readString(errorEvent.callId);
1828
- if (callId === void 0) return;
1829
- const cause = errorEvent.error ?? event;
1830
- finishOpenModelSpans(callId, cause, modelSpans, instrumentation.tracer);
1831
- finishOpenToolSpans(callId, cause, toolSpans, instrumentation.tracer);
1832
- const state = operations.get(callId);
1833
- if (!state) return;
1834
- state.span.fail(cause);
1835
- operations.delete(callId);
1836
- },
1837
- executeLanguageModelCall(options) {
1838
- const state = modelSpans.get(options.callId)?.find((candidate) => candidate.span === void 0);
1839
- if (!state) return options.execute();
1840
- return instrumentation.tracer.openSpan(state.spanSpec.name, state.spanSpec.attributes, (span) => {
1841
- state.span = span;
1842
- try {
1843
- return Promise.resolve(options.execute()).catch((cause) => {
1844
- writeSpanAttributes(span, aiGatewayLogAttributes(extractAIGatewayLogId(cause)));
1845
- span.fail(cause);
1846
- removeModelState(modelSpans, options.callId, state);
1847
- throw cause;
1848
- });
1849
- } catch (cause) {
1850
- writeSpanAttributes(span, aiGatewayLogAttributes(extractAIGatewayLogId(cause)));
1851
- span.fail(cause);
1852
- removeModelState(modelSpans, options.callId, state);
1853
- throw cause;
1854
- }
1855
- });
1856
- },
1857
- executeTool(options) {
1858
- const state = toolSpans.get(toolSpanKey(options.callId, options.toolCallId));
1859
- if (!state) return options.execute();
1860
- return instrumentation.tracer.openSpan(state.spanSpec.name, state.spanSpec.attributes, (span) => {
1861
- state.span = span;
1862
- try {
1863
- return Promise.resolve(options.execute()).catch((cause) => {
1864
- span.fail(cause);
1865
- toolSpans.delete(toolSpanKey(options.callId, options.toolCallId));
1866
- throw cause;
1867
- });
1868
- } catch (cause) {
1869
- span.fail(cause);
1870
- toolSpans.delete(toolSpanKey(options.callId, options.toolCallId));
1871
- throw cause;
1872
- }
1873
- });
1874
- }
1875
- };
1876
- }
1877
- function supportedOperationName(operationName) {
1878
- if (operationName === "generateObject" || operationName === "generateText" || operationName === "streamObject" || operationName === "streamText") return operationName;
1879
- }
1880
- function isStreamOperation(operationName) {
1881
- return operationName === "streamObject" || operationName === "streamText";
1882
- }
1883
- function shiftModelSpan(spansByCallId, callId) {
1884
- const spans = spansByCallId.get(callId);
1885
- const span = spans?.shift();
1886
- if (spans && spans.length === 0) spansByCallId.delete(callId);
1887
- return span;
1888
- }
1889
- function removeModelState(statesByCallId, callId, state) {
1890
- const states = statesByCallId.get(callId);
1891
- if (!states) return;
1892
- const index = states.indexOf(state);
1893
- if (index !== -1) states.splice(index, 1);
1894
- if (states.length === 0) statesByCallId.delete(callId);
1895
- }
1896
- function finishOpenModelSpans(callId, cause, spansByCallId, tracer) {
1897
- const states = spansByCallId.get(callId);
1898
- if (!states) return;
1899
- for (const state of states) {
1900
- const span = state.span ?? tracer.openSpan(state.spanSpec.name, state.spanSpec.attributes, (activeSpan) => activeSpan);
1901
- if (cause === void 0) span.finish();
1902
- else span.fail(cause);
1903
- }
1904
- spansByCallId.delete(callId);
1905
- }
1906
- function finishOpenToolSpans(callId, cause, spansByToolCallId, tracer) {
1907
- for (const [toolCallId, state] of spansByToolCallId) {
1908
- if (state.callId !== callId) continue;
1909
- const span = state.span ?? tracer.openSpan(state.spanSpec.name, state.spanSpec.attributes, (activeSpan) => activeSpan);
1910
- if (cause === void 0) span.finish();
1911
- else span.fail(cause);
1912
- spansByToolCallId.delete(toolCallId);
1913
- }
1914
- }
1915
- function eventObject(event) {
1916
- return typeof event === "object" && event !== null ? event : {};
1917
- }
1918
- const SEMANTIC_CONTEXT_KEYS = /* @__PURE__ */ new Set([
1919
- "agentId",
1920
- "agentName",
1921
- "agentVersion",
1922
- "conversationId",
1923
- "gen_ai.agent.id",
1924
- "gen_ai.agent.name",
1925
- "gen_ai.agent.version",
1926
- "gen_ai.conversation.id"
1927
- ]);
1928
- function runtimeContextAttributes(runtimeContextValue) {
1929
- const attributes = {};
1930
- const runtimeContext = recordValue(runtimeContextValue);
1931
- for (const [key, value] of Object.entries(runtimeContext ?? {})) if (!SEMANTIC_CONTEXT_KEYS.has(key) && isScalarAttributeValue(value)) attributes[key.startsWith("cloudflare.agents.") ? key : `cloudflare.agents.runtime_context.${key}`] = value;
1932
- return attributes;
1933
- }
1934
- function toolContextAttributes(toolName, toolContextValue) {
1935
- const attributes = {};
1936
- const toolContext = recordValue(toolContextValue);
1937
- for (const [key, value] of Object.entries(toolContext ?? {})) if (isScalarAttributeValue(value)) attributes[`cloudflare.agents.tool_context.${toolName}.${key}`] = value;
1938
- return attributes;
1939
- }
1940
- function recordValue(value) {
1941
- return typeof value === "object" && value !== null ? value : void 0;
1942
- }
1943
- function isScalarAttributeValue(value) {
1944
- return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
1945
- }
1946
- //#endregion
1947
1600
  //#region src/observability/ai/index.ts
1948
- const agentsAISDKTelemetryBrand = Symbol.for("cloudflare.agents.ai-sdk-telemetry");
1949
1601
  /**
1950
1602
  * Wraps an AI SDK namespace with tracing.
1951
1603
  */
1952
1604
  function wrapAISDK(ai, options = {}) {
1953
- return createAISDKV6Wrapper(ai, {
1954
- options,
1955
- tracer
1956
- });
1957
- }
1958
- /**
1959
- * Creates an AI SDK v7 telemetry adapter for use with `registerTelemetry` or
1960
- * per-call telemetry configuration.
1961
- */
1962
- function createAISDKTelemetry(options = {}) {
1963
- const telemetry = createAISDKV7Telemetry({
1605
+ return createAISDKWrapper(ai, {
1964
1606
  options,
1965
1607
  tracer
1966
1608
  });
1967
- Object.defineProperty(telemetry, agentsAISDKTelemetryBrand, { value: true });
1968
- return telemetry;
1969
1609
  }
1970
1610
  //#endregion
1971
- export { createAISDKTelemetry, wrapAISDK };
1611
+ export { wrapAISDK };
1972
1612
 
1973
1613
  //# sourceMappingURL=index.js.map