@raindrop-ai/ai-sdk 0.0.30 → 0.0.32

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.
@@ -1024,7 +1024,7 @@ globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = async_hooks.AsyncLocalStorage;
1024
1024
  // package.json
1025
1025
  var package_default = {
1026
1026
  name: "@raindrop-ai/ai-sdk",
1027
- version: "0.0.30"};
1027
+ version: "0.0.32"};
1028
1028
 
1029
1029
  // src/internal/version.ts
1030
1030
  var libraryName = package_default.name;
@@ -2091,6 +2091,7 @@ var RaindropTelemetryIntegration = class {
2091
2091
  attrInt("gen_ai.usage.output_tokens", usage.outputTokens)
2092
2092
  );
2093
2093
  }
2094
+ this.emitProviderExecutedToolSpans(event, state);
2094
2095
  this.traceShipper.endSpan(state.stepSpan, { attributes: outputAttrs });
2095
2096
  state.stepSpan = void 0;
2096
2097
  state.stepParent = void 0;
@@ -2145,6 +2146,10 @@ var RaindropTelemetryIntegration = class {
2145
2146
  this.traceShipper.endSpan(embedSpan, { attributes: outputAttrs });
2146
2147
  state.embedSpans.delete(event.embedCallId);
2147
2148
  };
2149
+ // v7 canary.159 renamed `onEmbedFinish` -> `onEmbedEnd`. Both names forward
2150
+ // to the same implementation; the installed SDK only wires up whichever it
2151
+ // knows about, so there is no double dispatch.
2152
+ this.onEmbedEnd = (event) => this.onEmbedFinish(event);
2148
2153
  // ── onFinish ────────────────────────────────────────────────────────────
2149
2154
  this.onFinish = (event) => {
2150
2155
  const state = this.getState(event.callId);
@@ -2160,6 +2165,12 @@ var RaindropTelemetryIntegration = class {
2160
2165
  }
2161
2166
  this.cleanup(event.callId);
2162
2167
  };
2168
+ // v7 < canary.159 dispatched `onFinish` as the operation finalizer; canary.159
2169
+ // renamed it to `onEnd` (the same change renamed onEmbedFinish -> onEmbedEnd
2170
+ // and onRerankFinish -> onRerankEnd). The event shape is unchanged, so this
2171
+ // is a thin alias to one implementation. The installed SDK wires up whichever
2172
+ // name it knows about, so old and new names never double dispatch.
2173
+ this.onEnd = (event) => this.onFinish(event);
2163
2174
  // ── onError ─────────────────────────────────────────────────────────────
2164
2175
  this.onError = (error) => {
2165
2176
  var _a;
@@ -2357,6 +2368,74 @@ var RaindropTelemetryIntegration = class {
2357
2368
  this.emitLive(state, "tool_result", event.toolCall.toolName);
2358
2369
  state.toolSpans.delete(event.toolCall.toolCallId);
2359
2370
  }
2371
+ // ── provider-executed tool calls ─────────────────────────────────────────
2372
+ //
2373
+ // Provider-executed (server-side) tools — e.g. Anthropic's hosted
2374
+ // `web_search` (`anthropic.web_search_20250305`) — are run by the provider,
2375
+ // not by the AI SDK. They therefore never flow through the client
2376
+ // `onToolExecutionStart`/`onToolExecutionEnd` callbacks that emit our
2377
+ // `ai.toolCall` spans; the SDK only surfaces them as `tool-call` /
2378
+ // `tool-result` content parts on the step (carrying `providerExecuted: true`).
2379
+ // Without this, such calls are invisible in every trace backend.
2380
+ //
2381
+ // At step finish we synthesize the same `ai.toolCall` span shape we emit for
2382
+ // client tools (name `ai.toolCall`, `operationId: "ai.toolCall"`, attrs
2383
+ // `ai.toolCall.name`/`id`/`args`/`result`), parented under the step span, so
2384
+ // downstream ingestion maps them to a tool span with no special-casing.
2385
+ //
2386
+ // Client-executed tools are excluded (`providerExecuted` falsy) — they were
2387
+ // already spanned during execution, so this never double-emits.
2388
+ emitProviderExecutedToolSpans(event, state) {
2389
+ if (!state.stepParent) return;
2390
+ const content = Array.isArray(event.content) ? event.content : [];
2391
+ const providerToolCalls = content.filter(
2392
+ (part) => (part == null ? void 0 : part.type) === "tool-call" && part.providerExecuted === true
2393
+ );
2394
+ if (providerToolCalls.length === 0) return;
2395
+ const resultsByCallId = /* @__PURE__ */ new Map();
2396
+ for (const part of content) {
2397
+ if (((part == null ? void 0 : part.type) === "tool-result" || (part == null ? void 0 : part.type) === "tool-error") && typeof part.toolCallId === "string") {
2398
+ resultsByCallId.set(part.toolCallId, part);
2399
+ }
2400
+ }
2401
+ for (const call of providerToolCalls) {
2402
+ const { operationName, resourceName } = opName(
2403
+ "ai.toolCall",
2404
+ state.functionId
2405
+ );
2406
+ const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(call.input))] : [];
2407
+ const toolSpan = this.traceShipper.startSpan({
2408
+ name: "ai.toolCall",
2409
+ parent: state.stepParent,
2410
+ eventId: state.eventId,
2411
+ operationId: "ai.toolCall",
2412
+ attributes: [
2413
+ attrString("operation.name", operationName),
2414
+ attrString("resource.name", resourceName),
2415
+ attrString("ai.telemetry.functionId", state.functionId),
2416
+ attrString("ai.toolCall.name", call.toolName),
2417
+ attrString("ai.toolCall.id", call.toolCallId),
2418
+ attrString("ai.toolCall.providerExecuted", "true"),
2419
+ ...inputAttrs
2420
+ ]
2421
+ });
2422
+ state.toolCallCount += 1;
2423
+ this.emitLive(state, "tool_start", call.toolName, { args: call.input });
2424
+ const resultPart = resultsByCallId.get(call.toolCallId);
2425
+ if ((resultPart == null ? void 0 : resultPart.type) === "tool-error") {
2426
+ this.traceShipper.endSpan(toolSpan, { error: resultPart.error });
2427
+ } else {
2428
+ const outputAttrs = state.recordOutputs && resultPart && "output" in resultPart ? [
2429
+ attrString(
2430
+ "ai.toolCall.result",
2431
+ safeJsonWithUint8(resultPart.output)
2432
+ )
2433
+ ] : [];
2434
+ this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
2435
+ }
2436
+ this.emitLive(state, "tool_result", call.toolName);
2437
+ }
2438
+ }
2360
2439
  finishGenerate(event, state) {
2361
2440
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
2362
2441
  if (state.rootSpan) {
@@ -2462,22 +2541,9 @@ var RaindropTelemetryIntegration = class {
2462
2541
  }
2463
2542
  };
2464
2543
 
2465
- // src/internal/traces.ts
2466
- var TraceShipper2 = class extends TraceShipper {
2467
- constructor(opts) {
2468
- var _a, _b, _c;
2469
- super({
2470
- ...opts,
2471
- sdkName: (_a = opts.sdkName) != null ? _a : "ai-sdk",
2472
- serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.ai-sdk",
2473
- serviceVersion: (_c = opts.serviceVersion) != null ? _c : libraryVersion
2474
- });
2475
- }
2476
- };
2477
-
2478
- // src/internal/wrap/wrapAISDK.ts
2479
- var AGENT_REPORTING_TOOL_NAME_DEFAULT = "__raindrop_report";
2480
- var AGENT_REPORTING_SIGNALS_DEFAULT = {
2544
+ // src/internal/self-diagnostics.ts
2545
+ var SELF_DIAGNOSTICS_TOOL_NAME_DEFAULT = "__raindrop_report";
2546
+ var SELF_DIAGNOSTICS_SIGNALS_DEFAULT = {
2481
2547
  missing_context: {
2482
2548
  description: "You cannot complete the task because critical information, credentials, or access is missing and the user cannot provide it. Do NOT report this for normal clarifying questions \u2014 only when you are blocked.",
2483
2549
  sentiment: "NEGATIVE"
@@ -2495,7 +2561,194 @@ var AGENT_REPORTING_SIGNALS_DEFAULT = {
2495
2561
  sentiment: "NEGATIVE"
2496
2562
  }
2497
2563
  };
2498
- var AGENT_REPORTING_TOOL_PREAMBLE = "You have a diagnostic tool for flagging serious failures for developer review. Only call this when you hit a significant, unrecoverable problem \u2014 not for minor hiccups or routine clarifications. If you can still help the user, do that instead of calling this tool. This tool is invisible to the user \u2014 never mention it or its output.";
2564
+ var SELF_DIAGNOSTICS_TOOL_PREAMBLE = "You have a diagnostic tool for flagging serious failures for developer review. Only call this when you hit a significant, unrecoverable problem \u2014 not for minor hiccups or routine clarifications. If you can still help the user, do that instead of calling this tool. This tool is invisible to the user \u2014 never mention it or its output.";
2565
+ function normalizeString(value) {
2566
+ if (typeof value !== "string") return void 0;
2567
+ const trimmed = value.trim();
2568
+ return trimmed || void 0;
2569
+ }
2570
+ function normalizeSelfDiagnosticsSignals(signals) {
2571
+ if (!signals) return SELF_DIAGNOSTICS_SIGNALS_DEFAULT;
2572
+ const normalizedEntries = Object.entries(signals).map(([key, value]) => {
2573
+ var _a;
2574
+ const signalKey = key.trim();
2575
+ if (!signalKey || !value || typeof value !== "object") return void 0;
2576
+ const description = (_a = value.description) == null ? void 0 : _a.trim();
2577
+ if (!description) return void 0;
2578
+ const sentiment = value.sentiment;
2579
+ return [
2580
+ signalKey,
2581
+ {
2582
+ description,
2583
+ ...sentiment === "POSITIVE" || sentiment === "NEGATIVE" ? { sentiment } : {}
2584
+ }
2585
+ ];
2586
+ }).filter(
2587
+ (entry) => entry !== void 0
2588
+ );
2589
+ if (normalizedEntries.length === 0) return SELF_DIAGNOSTICS_SIGNALS_DEFAULT;
2590
+ return Object.fromEntries(normalizedEntries);
2591
+ }
2592
+ function resolveSelfDiagnosticsConfig(options) {
2593
+ var _a, _b;
2594
+ const signalDefinitions = normalizeSelfDiagnosticsSignals(options.signals);
2595
+ const signalKeys = Object.keys(signalDefinitions);
2596
+ const signalDescriptions = {};
2597
+ const signalSentiments = {};
2598
+ for (const signalKey of signalKeys) {
2599
+ const definition = signalDefinitions[signalKey];
2600
+ if (!definition) continue;
2601
+ signalDescriptions[signalKey] = definition.description;
2602
+ signalSentiments[signalKey] = definition.sentiment;
2603
+ }
2604
+ const customGuidance = ((_a = options.guidance) == null ? void 0 : _a.trim()) || "";
2605
+ const toolName = ((_b = options.toolName) == null ? void 0 : _b.trim()) || SELF_DIAGNOSTICS_TOOL_NAME_DEFAULT;
2606
+ const signalList = signalKeys.map((signalKey) => {
2607
+ const sentiment = signalSentiments[signalKey];
2608
+ const sentimentTag = sentiment ? ` [${sentiment.toLowerCase()}]` : "";
2609
+ return `- ${signalKey}: ${signalDescriptions[signalKey]}${sentimentTag}`;
2610
+ }).join("\n");
2611
+ const guidanceBlock = customGuidance ? `
2612
+ Additional guidance: ${customGuidance}
2613
+ ` : "";
2614
+ const toolDescription = `${SELF_DIAGNOSTICS_TOOL_PREAMBLE}
2615
+
2616
+ When to call:
2617
+ - You are blocked from completing the task due to missing information or access that the user cannot provide.
2618
+ - A tool is persistently failing across multiple attempts, not just a single transient error.
2619
+ - The task requires a tool, permission, or capability you do not have.
2620
+ - You genuinely cannot deliver what the user asked for despite trying.
2621
+
2622
+ When NOT to call:
2623
+ - Normal clarifying questions or back-and-forth with the user.
2624
+ - A single tool error that you can recover from or retry.
2625
+ - You successfully completed the task, even if it was difficult.
2626
+ - Policy refusals or content filtering \u2014 those are working as intended.
2627
+
2628
+ Rules:
2629
+ 1. Pick the single best category.
2630
+ 2. Do not fabricate issues. Only report what is evident from the conversation.
2631
+ 3. Err on the side of NOT calling this tool. When in doubt, help the user instead.
2632
+ ${guidanceBlock}
2633
+ Categories:
2634
+ ` + signalList;
2635
+ return {
2636
+ toolName,
2637
+ toolDescription,
2638
+ signalKeys,
2639
+ signalKeySet: new Set(signalKeys),
2640
+ signalDescriptions,
2641
+ signalSentiments
2642
+ };
2643
+ }
2644
+ function normalizeSelfDiagnosticsConfig(options) {
2645
+ if (!(options == null ? void 0 : options.enabled)) return void 0;
2646
+ return resolveSelfDiagnosticsConfig(options);
2647
+ }
2648
+ function asVercelSchema(inputSchema) {
2649
+ const validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
2650
+ const schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
2651
+ return {
2652
+ [schemaSymbol]: true,
2653
+ [validatorSymbol]: true,
2654
+ _type: void 0,
2655
+ jsonSchema: inputSchema,
2656
+ validate: (value) => ({ success: true, value })
2657
+ };
2658
+ }
2659
+ function resolveStandaloneEventId(options) {
2660
+ var _a, _b, _c, _d, _e, _f;
2661
+ return (_f = (_d = (_b = normalizeString((_a = options.getEventId) == null ? void 0 : _a.call(options))) != null ? _b : normalizeString(options.eventId)) != null ? _d : normalizeString((_c = getContextManager().getParentSpanIds()) == null ? void 0 : _c.eventId)) != null ? _f : normalizeString((_e = getCurrentRaindropCallMetadata()) == null ? void 0 : _e.eventId);
2662
+ }
2663
+ function createSelfDiagnosticsToolDefinition(args) {
2664
+ const { config, eventShipper, getEventId, aiSDKVersion, debug } = args;
2665
+ const inputJsonSchema = {
2666
+ type: "object",
2667
+ additionalProperties: false,
2668
+ properties: {
2669
+ category: {
2670
+ type: "string",
2671
+ enum: config.signalKeys,
2672
+ description: "The single best-matching category from the list above."
2673
+ },
2674
+ detail: {
2675
+ type: "string",
2676
+ description: "One sentence of factual context: what happened and why it matters. Do not include PII or secrets."
2677
+ }
2678
+ },
2679
+ required: ["category", "detail"]
2680
+ };
2681
+ const inputSchema = asVercelSchema(inputJsonSchema);
2682
+ const execute = async (rawInput) => {
2683
+ var _a, _b;
2684
+ const fallbackCategory = (_a = config.signalKeys[0]) != null ? _a : "unknown";
2685
+ const categoryCandidate = normalizeString(rawInput == null ? void 0 : rawInput.category);
2686
+ const category = categoryCandidate && config.signalKeySet.has(categoryCandidate) ? categoryCandidate : fallbackCategory;
2687
+ const detail = normalizeString(rawInput == null ? void 0 : rawInput.detail);
2688
+ const eventId = getEventId();
2689
+ if (!eventId) {
2690
+ const message = "self diagnostics signal skipped: missing eventId. Pass eventId or getEventId when creating the tool.";
2691
+ if (args.onMissingEventId === "throw") {
2692
+ throw new Error(`[raindrop-ai/ai-sdk] ${message}`);
2693
+ }
2694
+ if (((_b = args.onMissingEventId) != null ? _b : "warn") === "warn") {
2695
+ console.warn(`[raindrop-ai/ai-sdk] ${message}`);
2696
+ }
2697
+ return { acknowledged: false, category, reason: "missing_event_id" };
2698
+ }
2699
+ void eventShipper.trackSignal({
2700
+ eventId,
2701
+ name: `self diagnostics - ${category}`,
2702
+ type: "agent",
2703
+ sentiment: config.signalSentiments[category],
2704
+ properties: {
2705
+ source: "agent_reporting_tool",
2706
+ category,
2707
+ signal_description: config.signalDescriptions[category],
2708
+ ...aiSDKVersion ? { ai_sdk_version: aiSDKVersion } : {},
2709
+ ...detail ? { detail } : {}
2710
+ }
2711
+ }).catch((error) => {
2712
+ if (debug) {
2713
+ const message = error instanceof Error ? error.message : String(error);
2714
+ console.warn(`[raindrop-ai/ai-sdk] selfDiagnostics signal dispatch failed: ${message}`);
2715
+ }
2716
+ });
2717
+ return { acknowledged: true, category };
2718
+ };
2719
+ return {
2720
+ name: config.toolName,
2721
+ description: config.toolDescription,
2722
+ parameters: inputSchema,
2723
+ inputSchema,
2724
+ execute
2725
+ };
2726
+ }
2727
+ function createStandaloneSelfDiagnosticsTool(args) {
2728
+ const config = resolveSelfDiagnosticsConfig(args.options);
2729
+ return createSelfDiagnosticsToolDefinition({
2730
+ config,
2731
+ eventShipper: args.eventShipper,
2732
+ getEventId: () => resolveStandaloneEventId(args.options),
2733
+ onMissingEventId: args.options.onMissingEventId,
2734
+ debug: args.debug
2735
+ });
2736
+ }
2737
+
2738
+ // src/internal/traces.ts
2739
+ var TraceShipper2 = class extends TraceShipper {
2740
+ constructor(opts) {
2741
+ var _a, _b, _c;
2742
+ super({
2743
+ ...opts,
2744
+ sdkName: (_a = opts.sdkName) != null ? _a : "ai-sdk",
2745
+ serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.ai-sdk",
2746
+ serviceVersion: (_c = opts.serviceVersion) != null ? _c : libraryVersion
2747
+ });
2748
+ }
2749
+ };
2750
+
2751
+ // src/internal/wrap/wrapAISDK.ts
2499
2752
  var pendingStoresByShipper = /* @__PURE__ */ new WeakMap();
2500
2753
  var PendingToolSpanStore = class _PendingToolSpanStore {
2501
2754
  constructor() {
@@ -2599,85 +2852,6 @@ function mergeContexts(wrapTime, callTime) {
2599
2852
  }
2600
2853
  return result;
2601
2854
  }
2602
- function normalizeSelfDiagnosticsSignals(signals) {
2603
- if (!signals) return AGENT_REPORTING_SIGNALS_DEFAULT;
2604
- const normalizedEntries = Object.entries(signals).map(([key, value]) => {
2605
- var _a;
2606
- const signalKey = key.trim();
2607
- if (!signalKey || !value || typeof value !== "object") return void 0;
2608
- const description = (_a = value.description) == null ? void 0 : _a.trim();
2609
- if (!description) return void 0;
2610
- const sentiment = value.sentiment;
2611
- return [
2612
- signalKey,
2613
- {
2614
- description,
2615
- ...sentiment === "POSITIVE" || sentiment === "NEGATIVE" ? { sentiment } : {}
2616
- }
2617
- ];
2618
- }).filter(
2619
- (entry) => entry !== void 0
2620
- );
2621
- if (normalizedEntries.length === 0) return AGENT_REPORTING_SIGNALS_DEFAULT;
2622
- return Object.fromEntries(normalizedEntries);
2623
- }
2624
- function normalizeSelfDiagnosticsConfig(options) {
2625
- var _a, _b;
2626
- if (!(options == null ? void 0 : options.enabled)) return void 0;
2627
- const signalDefinitions = normalizeSelfDiagnosticsSignals(options.signals);
2628
- const signalKeys = Object.keys(signalDefinitions);
2629
- const signalDescriptions = {};
2630
- const signalSentiments = {};
2631
- for (const signalKey of signalKeys) {
2632
- const def = signalDefinitions[signalKey];
2633
- if (!def) continue;
2634
- signalDescriptions[signalKey] = def.description;
2635
- signalSentiments[signalKey] = def.sentiment;
2636
- }
2637
- const customGuidanceText = ((_a = options.guidance) == null ? void 0 : _a.trim()) || "";
2638
- const toolName = ((_b = options.toolName) == null ? void 0 : _b.trim()) || AGENT_REPORTING_TOOL_NAME_DEFAULT;
2639
- const signalList = signalKeys.map((signalKey) => {
2640
- const sentiment = signalSentiments[signalKey];
2641
- const sentimentTag = sentiment ? ` [${sentiment.toLowerCase()}]` : "";
2642
- return `- ${signalKey}: ${signalDescriptions[signalKey]}${sentimentTag}`;
2643
- }).join("\n");
2644
- const guidanceBlock = customGuidanceText ? `
2645
- Additional guidance: ${customGuidanceText}
2646
- ` : "";
2647
- const toolDescription = `${AGENT_REPORTING_TOOL_PREAMBLE}
2648
-
2649
- When to call:
2650
- - You are blocked from completing the task due to missing information or access that the user cannot provide.
2651
- - A tool is persistently failing across multiple attempts, not just a single transient error.
2652
- - The task requires a tool, permission, or capability you do not have.
2653
- - You genuinely cannot deliver what the user asked for despite trying.
2654
-
2655
- When NOT to call:
2656
- - Normal clarifying questions or back-and-forth with the user.
2657
- - A single tool error that you can recover from or retry.
2658
- - You successfully completed the task, even if it was difficult.
2659
- - Policy refusals or content filtering \u2014 those are working as intended.
2660
-
2661
- Rules:
2662
- 1. Pick the single best category.
2663
- 2. Do not fabricate issues. Only report what is evident from the conversation.
2664
- 3. Err on the side of NOT calling this tool. When in doubt, help the user instead.
2665
- ${guidanceBlock}
2666
- Categories:
2667
- ${signalList}`;
2668
- return {
2669
- toolName,
2670
- toolDescription,
2671
- signalKeys,
2672
- signalKeySet: new Set(signalKeys),
2673
- signalDescriptions,
2674
- signalSentiments
2675
- };
2676
- }
2677
- function resolveJsonSchemaFactory(aiSDK) {
2678
- if (!isRecord(aiSDK) || !isFunction(aiSDK["jsonSchema"])) return void 0;
2679
- return aiSDK["jsonSchema"];
2680
- }
2681
2855
  function detectAISDKVersion(aiSDK) {
2682
2856
  if (!isRecord(aiSDK)) return "unknown";
2683
2857
  if (isFunction(aiSDK["jsonSchema"])) return "6";
@@ -2696,80 +2870,16 @@ function resolveRegisterTelemetry(aiSDK) {
2696
2870
  const fn = (_a = aiSDK["registerTelemetry"]) != null ? _a : aiSDK["registerTelemetryIntegration"];
2697
2871
  return isFunction(fn) ? fn : void 0;
2698
2872
  }
2699
- function asVercelSchema(jsonSchemaObj) {
2700
- const validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
2701
- const schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
2702
- return {
2703
- [schemaSymbol]: true,
2704
- [validatorSymbol]: true,
2705
- _type: void 0,
2706
- jsonSchema: jsonSchemaObj,
2707
- validate: (value) => ({ success: true, value })
2708
- };
2709
- }
2710
2873
  function createSelfDiagnosticsTool(ctx) {
2711
2874
  const config = ctx.selfDiagnostics;
2712
2875
  if (!config) return void 0;
2713
- const schema = {
2714
- type: "object",
2715
- additionalProperties: false,
2716
- properties: {
2717
- category: {
2718
- type: "string",
2719
- enum: config.signalKeys,
2720
- description: "The single best-matching category from the list above."
2721
- },
2722
- detail: {
2723
- type: "string",
2724
- description: "One sentence of factual context: what happened and why it matters. Do not include PII or secrets."
2725
- }
2726
- },
2727
- required: ["category", "detail"]
2728
- };
2729
- const parameters = asVercelSchema(schema);
2730
- let inputSchema = parameters;
2731
- if (ctx.jsonSchemaFactory) {
2732
- try {
2733
- inputSchema = ctx.jsonSchemaFactory(schema);
2734
- } catch (e) {
2735
- inputSchema = parameters;
2736
- }
2737
- }
2738
- const execute = async (rawInput) => {
2739
- var _a;
2740
- const input = isRecord(rawInput) ? rawInput : void 0;
2741
- const fallbackCategory = (_a = config.signalKeys[0]) != null ? _a : "unknown";
2742
- const categoryCandidate = typeof (input == null ? void 0 : input["category"]) === "string" ? input["category"].trim() : void 0;
2743
- const category = categoryCandidate && config.signalKeySet.has(categoryCandidate) ? categoryCandidate : fallbackCategory;
2744
- const detail = typeof (input == null ? void 0 : input["detail"]) === "string" ? input["detail"].trim() : "";
2745
- const signalDescription = config.signalDescriptions[category];
2746
- const signalSentiment = config.signalSentiments[category];
2747
- void ctx.eventShipper.trackSignal({
2748
- eventId: ctx.eventId,
2749
- name: `self diagnostics - ${category}`,
2750
- type: "agent",
2751
- sentiment: signalSentiment,
2752
- properties: {
2753
- source: "agent_reporting_tool",
2754
- category,
2755
- signal_description: signalDescription,
2756
- ai_sdk_version: ctx.aiSDKVersion,
2757
- ...detail ? { detail } : {}
2758
- }
2759
- }).catch((err) => {
2760
- if (ctx.debug) {
2761
- const msg = err instanceof Error ? err.message : String(err);
2762
- console.warn(`[raindrop-ai/ai-sdk] selfDiagnostics signal dispatch failed: ${msg}`);
2763
- }
2764
- });
2765
- return { acknowledged: true, category };
2766
- };
2767
- return {
2768
- description: config.toolDescription,
2769
- execute,
2770
- parameters,
2771
- inputSchema
2772
- };
2876
+ return createSelfDiagnosticsToolDefinition({
2877
+ config,
2878
+ eventShipper: ctx.eventShipper,
2879
+ getEventId: () => ctx.eventId,
2880
+ aiSDKVersion: ctx.aiSDKVersion,
2881
+ debug: ctx.debug
2882
+ });
2773
2883
  }
2774
2884
  function getCurrentParentSpanContextSync() {
2775
2885
  return getContextManager().getParentSpanIds();
@@ -2996,7 +3106,6 @@ function setupOperation(params) {
2996
3106
  eventShipper,
2997
3107
  traceShipper,
2998
3108
  rootParentForChildren,
2999
- jsonSchemaFactory: resolveJsonSchemaFactory(aiSDK),
3000
3109
  selfDiagnostics: operationSelfDiagnostics,
3001
3110
  aiSDKVersion: detectAISDKVersion(aiSDK)
3002
3111
  };
@@ -3345,7 +3454,6 @@ function wrapAISDK(aiSDK, deps) {
3345
3454
  );
3346
3455
  }
3347
3456
  const selfDiagnostics2 = normalizeSelfDiagnosticsConfig(deps.options.selfDiagnostics);
3348
- const jsonSchemaFactory = selfDiagnostics2 ? resolveJsonSchemaFactory(aiSDK) : void 0;
3349
3457
  const metadataAwareOps = /* @__PURE__ */ new Set([
3350
3458
  "generateText",
3351
3459
  "streamText",
@@ -3377,14 +3485,9 @@ function wrapAISDK(aiSDK, deps) {
3377
3485
  const perCallEventIdGenerated = !perCallEventIdExplicit;
3378
3486
  const perCallCtx = {
3379
3487
  eventId: perCallEventId,
3380
- context: wrapTimeCtx,
3381
- telemetry,
3382
- sendTraces: false,
3383
3488
  debug,
3384
3489
  eventShipper: deps.eventShipper,
3385
3490
  traceShipper: deps.traceShipper,
3386
- rootParentForChildren: void 0,
3387
- jsonSchemaFactory,
3388
3491
  selfDiagnostics: selfDiagnostics2,
3389
3492
  aiSDKVersion: "7"
3390
3493
  };
@@ -3586,7 +3689,6 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
3586
3689
  eventShipper: deps.eventShipper,
3587
3690
  traceShipper: deps.traceShipper,
3588
3691
  rootParentForChildren,
3589
- jsonSchemaFactory: resolveJsonSchemaFactory(aiSDK),
3590
3692
  selfDiagnostics,
3591
3693
  aiSDKVersion: detectAISDKVersion(aiSDK)
3592
3694
  };
@@ -3794,7 +3896,6 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
3794
3896
  eventShipper: deps.eventShipper,
3795
3897
  traceShipper: deps.traceShipper,
3796
3898
  rootParentForChildren,
3797
- jsonSchemaFactory: resolveJsonSchemaFactory(aiSDK),
3798
3899
  selfDiagnostics,
3799
3900
  aiSDKVersion: detectAISDKVersion(aiSDK)
3800
3901
  };
@@ -4610,6 +4711,14 @@ function createRaindropAISDK(opts) {
4610
4711
  traceShipper
4611
4712
  });
4612
4713
  },
4714
+ createSelfDiagnosticsTool(options = {}) {
4715
+ var _a2;
4716
+ return createStandaloneSelfDiagnosticsTool({
4717
+ options,
4718
+ eventShipper,
4719
+ debug: ((_a2 = opts.events) == null ? void 0 : _a2.debug) === true || envDebug
4720
+ });
4721
+ },
4613
4722
  createTelemetryIntegration(contextOrOptions) {
4614
4723
  const FLAT_CONTEXT_KEYS = [
4615
4724
  "userId",
@@ -1,4 +1,4 @@
1
- export { DEFAULT_REDACT_ATTRIBUTE_KEYS, DEFAULT_SECRET_KEY_NAMES, REDACTED_PLACEHOLDER, RaindropTelemetryIntegration, _resetParentToolContextStorage, _resetRaindropCallMetadataStorage, _resetWarnedMissingUserId, clearParentToolContext, createRaindropAISDK, currentSpan, defaultTransformSpan, enterParentToolContext, eventMetadata, eventMetadataFromChatRequest, getContextManager, getCurrentParentToolContext, getCurrentRaindropCallMetadata, readRaindropCallMetadataFromArgs, redactJsonAttributeValue, redactSecretsInObject, runWithParentToolContext, runWithRaindropCallMetadata, withCurrent } from './chunk-LM3XO4KR.mjs';
1
+ export { DEFAULT_REDACT_ATTRIBUTE_KEYS, DEFAULT_SECRET_KEY_NAMES, REDACTED_PLACEHOLDER, RaindropTelemetryIntegration, _resetParentToolContextStorage, _resetRaindropCallMetadataStorage, _resetWarnedMissingUserId, clearParentToolContext, createRaindropAISDK, currentSpan, defaultTransformSpan, enterParentToolContext, eventMetadata, eventMetadataFromChatRequest, getContextManager, getCurrentParentToolContext, getCurrentRaindropCallMetadata, readRaindropCallMetadataFromArgs, redactJsonAttributeValue, redactSecretsInObject, runWithParentToolContext, runWithRaindropCallMetadata, withCurrent } from './chunk-YDMJ6ABM.mjs';
2
2
  import { AsyncLocalStorage } from 'async_hooks';
3
3
 
4
4
  globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = AsyncLocalStorage;
@@ -1,4 +1,4 @@
1
- export { A as AISDKChatRequestLike, a as AISDKChatRequestMessageLike, b as AISDKMessage, c as AgentCallMetadata, d as AgentWithMetadata, e as Attachment, B as BuildEventPatch, C as ContextManager, f as ContextSpan, g as CreateSpanArgs, D as DEFAULT_REDACT_ATTRIBUTE_KEYS, h as DEFAULT_SECRET_KEY_NAMES, E as EndSpanArgs, i as EventBuilder, j as EventMetadataOptions, I as IdentifyInput, O as OtlpAnyValue, k as OtlpSpan, P as ParentToolContext, R as REDACTED_PLACEHOLDER, l as RaindropAISDKClient, m as RaindropAISDKContext, n as RaindropAISDKOptions, o as RaindropCallMetadata, p as RaindropTelemetryIntegration, q as RaindropTelemetryIntegrationOptions, S as SelfDiagnosticsOptions, r as SelfDiagnosticsSignalDefinition, s as SelfDiagnosticsSignalDefinitions, t as StartSpanArgs, T as TraceSpan, u as TransformSpanHook, W as WrapAISDKOptions, v as WrappedAI, w as WrappedAISDK, _ as _resetParentToolContextStorage, x as _resetRaindropCallMetadataStorage, y as _resetWarnedMissingUserId, z as clearParentToolContext, F as createRaindropAISDK, G as currentSpan, H as defaultTransformSpan, J as enterParentToolContext, K as eventMetadata, L as eventMetadataFromChatRequest, M as getContextManager, N as getCurrentParentToolContext, Q as getCurrentRaindropCallMetadata, U as readRaindropCallMetadataFromArgs, V as redactJsonAttributeValue, X as redactSecretsInObject, Y as runWithParentToolContext, Z as runWithRaindropCallMetadata, $ as withCurrent } from './index-Ba_ZzUH4.mjs';
1
+ export { A as AISDKChatRequestLike, a as AISDKChatRequestMessageLike, b as AISDKMessage, c as AgentCallMetadata, d as AgentWithMetadata, e as Attachment, B as BuildEventPatch, C as ContextManager, f as ContextSpan, g as CreateSpanArgs, D as DEFAULT_REDACT_ATTRIBUTE_KEYS, h as DEFAULT_SECRET_KEY_NAMES, E as EndSpanArgs, i as EventBuilder, j as EventMetadataOptions, I as IdentifyInput, O as OtlpAnyValue, k as OtlpSpan, P as ParentToolContext, R as REDACTED_PLACEHOLDER, l as RaindropAISDKClient, m as RaindropAISDKContext, n as RaindropAISDKOptions, o as RaindropCallMetadata, p as RaindropTelemetryIntegration, q as RaindropTelemetryIntegrationOptions, S as SelfDiagnosticsOptions, r as SelfDiagnosticsSignalDefinition, s as SelfDiagnosticsSignalDefinitions, t as SelfDiagnosticsTool, u as SelfDiagnosticsToolInput, v as SelfDiagnosticsToolOptions, w as SelfDiagnosticsToolResult, x as StartSpanArgs, T as TraceSpan, y as TransformSpanHook, W as WrapAISDKOptions, z as WrappedAI, F as WrappedAISDK, _ as _resetParentToolContextStorage, G as _resetRaindropCallMetadataStorage, H as _resetWarnedMissingUserId, J as clearParentToolContext, K as createRaindropAISDK, L as currentSpan, M as defaultTransformSpan, N as enterParentToolContext, Q as eventMetadata, U as eventMetadataFromChatRequest, V as getContextManager, X as getCurrentParentToolContext, Y as getCurrentRaindropCallMetadata, Z as readRaindropCallMetadataFromArgs, $ as redactJsonAttributeValue, a0 as redactSecretsInObject, a1 as runWithParentToolContext, a2 as runWithRaindropCallMetadata, a3 as withCurrent } from './index-CwK0GdEe.mjs';
2
2
 
3
3
  declare global {
4
4
  var RAINDROP_ASYNC_LOCAL_STORAGE: (new <T>() => {
@@ -1,4 +1,4 @@
1
- export { A as AISDKChatRequestLike, a as AISDKChatRequestMessageLike, b as AISDKMessage, c as AgentCallMetadata, d as AgentWithMetadata, e as Attachment, B as BuildEventPatch, C as ContextManager, f as ContextSpan, g as CreateSpanArgs, D as DEFAULT_REDACT_ATTRIBUTE_KEYS, h as DEFAULT_SECRET_KEY_NAMES, E as EndSpanArgs, i as EventBuilder, j as EventMetadataOptions, I as IdentifyInput, O as OtlpAnyValue, k as OtlpSpan, P as ParentToolContext, R as REDACTED_PLACEHOLDER, l as RaindropAISDKClient, m as RaindropAISDKContext, n as RaindropAISDKOptions, o as RaindropCallMetadata, p as RaindropTelemetryIntegration, q as RaindropTelemetryIntegrationOptions, S as SelfDiagnosticsOptions, r as SelfDiagnosticsSignalDefinition, s as SelfDiagnosticsSignalDefinitions, t as StartSpanArgs, T as TraceSpan, u as TransformSpanHook, W as WrapAISDKOptions, v as WrappedAI, w as WrappedAISDK, _ as _resetParentToolContextStorage, x as _resetRaindropCallMetadataStorage, y as _resetWarnedMissingUserId, z as clearParentToolContext, F as createRaindropAISDK, G as currentSpan, H as defaultTransformSpan, J as enterParentToolContext, K as eventMetadata, L as eventMetadataFromChatRequest, M as getContextManager, N as getCurrentParentToolContext, Q as getCurrentRaindropCallMetadata, U as readRaindropCallMetadataFromArgs, V as redactJsonAttributeValue, X as redactSecretsInObject, Y as runWithParentToolContext, Z as runWithRaindropCallMetadata, $ as withCurrent } from './index-Ba_ZzUH4.js';
1
+ export { A as AISDKChatRequestLike, a as AISDKChatRequestMessageLike, b as AISDKMessage, c as AgentCallMetadata, d as AgentWithMetadata, e as Attachment, B as BuildEventPatch, C as ContextManager, f as ContextSpan, g as CreateSpanArgs, D as DEFAULT_REDACT_ATTRIBUTE_KEYS, h as DEFAULT_SECRET_KEY_NAMES, E as EndSpanArgs, i as EventBuilder, j as EventMetadataOptions, I as IdentifyInput, O as OtlpAnyValue, k as OtlpSpan, P as ParentToolContext, R as REDACTED_PLACEHOLDER, l as RaindropAISDKClient, m as RaindropAISDKContext, n as RaindropAISDKOptions, o as RaindropCallMetadata, p as RaindropTelemetryIntegration, q as RaindropTelemetryIntegrationOptions, S as SelfDiagnosticsOptions, r as SelfDiagnosticsSignalDefinition, s as SelfDiagnosticsSignalDefinitions, t as SelfDiagnosticsTool, u as SelfDiagnosticsToolInput, v as SelfDiagnosticsToolOptions, w as SelfDiagnosticsToolResult, x as StartSpanArgs, T as TraceSpan, y as TransformSpanHook, W as WrapAISDKOptions, z as WrappedAI, F as WrappedAISDK, _ as _resetParentToolContextStorage, G as _resetRaindropCallMetadataStorage, H as _resetWarnedMissingUserId, J as clearParentToolContext, K as createRaindropAISDK, L as currentSpan, M as defaultTransformSpan, N as enterParentToolContext, Q as eventMetadata, U as eventMetadataFromChatRequest, V as getContextManager, X as getCurrentParentToolContext, Y as getCurrentRaindropCallMetadata, Z as readRaindropCallMetadataFromArgs, $ as redactJsonAttributeValue, a0 as redactSecretsInObject, a1 as runWithParentToolContext, a2 as runWithRaindropCallMetadata, a3 as withCurrent } from './index-CwK0GdEe.js';
2
2
 
3
3
  declare global {
4
4
  var RAINDROP_ASYNC_LOCAL_STORAGE: (new <T>() => {