@raindrop-ai/ai-sdk 0.0.31 → 0.0.33

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.
@@ -1017,7 +1017,7 @@ async function* asyncGeneratorWithCurrent(span, gen) {
1017
1017
  // package.json
1018
1018
  var package_default = {
1019
1019
  name: "@raindrop-ai/ai-sdk",
1020
- version: "0.0.31"};
1020
+ version: "0.0.33"};
1021
1021
 
1022
1022
  // src/internal/version.ts
1023
1023
  var libraryName = package_default.name;
@@ -1800,6 +1800,25 @@ var RaindropTelemetryIntegration = class {
1800
1800
  * (the `event.callId` can be the same for parallel sibling tools).
1801
1801
  */
1802
1802
  this.priorParentContexts = /* @__PURE__ */ new Map();
1803
+ // ── lifecycle ─────────────────────────────────────────────────────────────
1804
+ //
1805
+ // The shippers buffer spans/events and flush on a timer, so a short-lived
1806
+ // script (e.g. a single `generateText` then `process.exit`) can exit before
1807
+ // anything ships. Expose `flush`/`shutdown` on the integration itself so the
1808
+ // value returned by `raindrop()` is self-sufficient — callers can keep the
1809
+ // reference they pass to `registerTelemetry` and `await rd.flush()` before
1810
+ // exiting, without also constructing a separate client.
1811
+ /** Flush any buffered events and trace spans to their destinations. */
1812
+ this.flush = async () => {
1813
+ await Promise.all([this.eventShipper.flush(), this.traceShipper.flush()]);
1814
+ };
1815
+ /** Flush and stop the background flush timers. */
1816
+ this.shutdown = async () => {
1817
+ await Promise.all([
1818
+ this.eventShipper.shutdown(),
1819
+ this.traceShipper.shutdown()
1820
+ ]);
1821
+ };
1803
1822
  // ── onStart ─────────────────────────────────────────────────────────────
1804
1823
  this.onStart = (event) => {
1805
1824
  var _a, _b, _c, _d, _e;
@@ -2084,6 +2103,7 @@ var RaindropTelemetryIntegration = class {
2084
2103
  attrInt("gen_ai.usage.output_tokens", usage.outputTokens)
2085
2104
  );
2086
2105
  }
2106
+ this.emitProviderExecutedToolSpans(event, state);
2087
2107
  this.traceShipper.endSpan(state.stepSpan, { attributes: outputAttrs });
2088
2108
  state.stepSpan = void 0;
2089
2109
  state.stepParent = void 0;
@@ -2192,8 +2212,56 @@ var RaindropTelemetryIntegration = class {
2192
2212
  if (state.subagentToolCallSpan) {
2193
2213
  this.traceShipper.endSpan(state.subagentToolCallSpan, { error: actualError });
2194
2214
  }
2215
+ const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
2216
+ if (!isEmbed) {
2217
+ this.finalizeGenerateEvent(state, state.accumulatedText || void 0, void 0);
2218
+ }
2195
2219
  this.cleanup(event.callId);
2196
2220
  };
2221
+ // ── onAbort ─────────────────────────────────────────────────────────────
2222
+ //
2223
+ // Dispatched by the v7 canary line (post-beta.116) when a `streamText` call
2224
+ // is cancelled via its `AbortSignal`. On abort the SDK fires neither `onEnd`
2225
+ // nor `onError`, so without this every open span would leak and the event
2226
+ // would hang forever in its `isPending` state. We close every open span with
2227
+ // an `ai.response.aborted` marker (no error status — an abort is not a model
2228
+ // failure) and flush the partial event.
2229
+ this.onAbort = (event) => {
2230
+ const callId = event == null ? void 0 : event.callId;
2231
+ if (!callId) return;
2232
+ const state = this.getState(callId);
2233
+ if (!state) return;
2234
+ const abortedAttr = attrString("ai.response.aborted", "true");
2235
+ if (state.stepSpan) {
2236
+ this.traceShipper.endSpan(state.stepSpan, { attributes: [abortedAttr] });
2237
+ state.stepSpan = void 0;
2238
+ state.stepParent = void 0;
2239
+ }
2240
+ for (const embedSpan of state.embedSpans.values()) {
2241
+ this.traceShipper.endSpan(embedSpan, { attributes: [abortedAttr] });
2242
+ }
2243
+ state.embedSpans.clear();
2244
+ for (const toolCallId of state.parentContextToolCallIds) {
2245
+ this.priorParentContexts.delete(toolCallId);
2246
+ }
2247
+ state.parentContextToolCallIds.clear();
2248
+ for (const toolSpan of state.toolSpans.values()) {
2249
+ this.traceShipper.endSpan(toolSpan, { attributes: [abortedAttr] });
2250
+ }
2251
+ state.toolSpans.clear();
2252
+ if (state.rootSpan) {
2253
+ this.traceShipper.endSpan(state.rootSpan, {
2254
+ attributes: [abortedAttr, attrInt("ai.toolCall.count", state.toolCallCount)]
2255
+ });
2256
+ }
2257
+ if (state.subagentToolCallSpan) {
2258
+ this.traceShipper.endSpan(state.subagentToolCallSpan, {
2259
+ attributes: [abortedAttr]
2260
+ });
2261
+ }
2262
+ this.finalizeGenerateEvent(state, state.accumulatedText || void 0, void 0);
2263
+ this.cleanup(callId);
2264
+ };
2197
2265
  // ── executeTool ─────────────────────────────────────────────────────────
2198
2266
  this.executeTool = async ({
2199
2267
  callId,
@@ -2351,17 +2419,86 @@ var RaindropTelemetryIntegration = class {
2351
2419
  const toolSpan = state.toolSpans.get(event.toolCall.toolCallId);
2352
2420
  if (!toolSpan) return;
2353
2421
  state.toolCallCount += 1;
2354
- if (event.success) {
2355
- const outputAttrs = state.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(event.output))] : [];
2422
+ const outcome = "toolOutput" in event ? event.toolOutput.type === "tool-result" ? { success: true, output: event.toolOutput.output } : { success: false, error: event.toolOutput.error } : event.success ? { success: true, output: event.output } : { success: false, error: event.error };
2423
+ if (outcome.success) {
2424
+ const outputAttrs = state.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(outcome.output))] : [];
2356
2425
  this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
2357
2426
  } else {
2358
- this.traceShipper.endSpan(toolSpan, { error: event.error });
2427
+ this.traceShipper.endSpan(toolSpan, { error: outcome.error });
2359
2428
  }
2360
2429
  this.emitLive(state, "tool_result", event.toolCall.toolName);
2361
2430
  state.toolSpans.delete(event.toolCall.toolCallId);
2362
2431
  }
2432
+ // ── provider-executed tool calls ─────────────────────────────────────────
2433
+ //
2434
+ // Provider-executed (server-side) tools — e.g. Anthropic's hosted
2435
+ // `web_search` (`anthropic.web_search_20250305`) — are run by the provider,
2436
+ // not by the AI SDK. They therefore never flow through the client
2437
+ // `onToolExecutionStart`/`onToolExecutionEnd` callbacks that emit our
2438
+ // `ai.toolCall` spans; the SDK only surfaces them as `tool-call` /
2439
+ // `tool-result` content parts on the step (carrying `providerExecuted: true`).
2440
+ // Without this, such calls are invisible in every trace backend.
2441
+ //
2442
+ // At step finish we synthesize the same `ai.toolCall` span shape we emit for
2443
+ // client tools (name `ai.toolCall`, `operationId: "ai.toolCall"`, attrs
2444
+ // `ai.toolCall.name`/`id`/`args`/`result`), parented under the step span, so
2445
+ // downstream ingestion maps them to a tool span with no special-casing.
2446
+ //
2447
+ // Client-executed tools are excluded (`providerExecuted` falsy) — they were
2448
+ // already spanned during execution, so this never double-emits.
2449
+ emitProviderExecutedToolSpans(event, state) {
2450
+ if (!state.stepParent) return;
2451
+ const content = Array.isArray(event.content) ? event.content : [];
2452
+ const providerToolCalls = content.filter(
2453
+ (part) => (part == null ? void 0 : part.type) === "tool-call" && part.providerExecuted === true
2454
+ );
2455
+ if (providerToolCalls.length === 0) return;
2456
+ const resultsByCallId = /* @__PURE__ */ new Map();
2457
+ for (const part of content) {
2458
+ if (((part == null ? void 0 : part.type) === "tool-result" || (part == null ? void 0 : part.type) === "tool-error") && typeof part.toolCallId === "string") {
2459
+ resultsByCallId.set(part.toolCallId, part);
2460
+ }
2461
+ }
2462
+ for (const call of providerToolCalls) {
2463
+ const { operationName, resourceName } = opName(
2464
+ "ai.toolCall",
2465
+ state.functionId
2466
+ );
2467
+ const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(call.input))] : [];
2468
+ const toolSpan = this.traceShipper.startSpan({
2469
+ name: "ai.toolCall",
2470
+ parent: state.stepParent,
2471
+ eventId: state.eventId,
2472
+ operationId: "ai.toolCall",
2473
+ attributes: [
2474
+ attrString("operation.name", operationName),
2475
+ attrString("resource.name", resourceName),
2476
+ attrString("ai.telemetry.functionId", state.functionId),
2477
+ attrString("ai.toolCall.name", call.toolName),
2478
+ attrString("ai.toolCall.id", call.toolCallId),
2479
+ attrString("ai.toolCall.providerExecuted", "true"),
2480
+ ...inputAttrs
2481
+ ]
2482
+ });
2483
+ state.toolCallCount += 1;
2484
+ this.emitLive(state, "tool_start", call.toolName, { args: call.input });
2485
+ const resultPart = resultsByCallId.get(call.toolCallId);
2486
+ if ((resultPart == null ? void 0 : resultPart.type) === "tool-error") {
2487
+ this.traceShipper.endSpan(toolSpan, { error: resultPart.error });
2488
+ } else {
2489
+ const outputAttrs = state.recordOutputs && resultPart && "output" in resultPart ? [
2490
+ attrString(
2491
+ "ai.toolCall.result",
2492
+ safeJsonWithUint8(resultPart.output)
2493
+ )
2494
+ ] : [];
2495
+ this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
2496
+ }
2497
+ this.emitLive(state, "tool_result", call.toolName);
2498
+ }
2499
+ }
2363
2500
  finishGenerate(event, state) {
2364
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
2501
+ var _a, _b, _c, _d, _e, _f;
2365
2502
  if (state.rootSpan) {
2366
2503
  const outputAttrs = [];
2367
2504
  if (state.recordOutputs) {
@@ -2409,38 +2546,47 @@ var RaindropTelemetryIntegration = class {
2409
2546
  );
2410
2547
  this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
2411
2548
  }
2549
+ this.finalizeGenerateEvent(
2550
+ state,
2551
+ (_e = event.text) != null ? _e : state.accumulatedText || void 0,
2552
+ (_f = event.response) == null ? void 0 : _f.modelId
2553
+ );
2554
+ }
2555
+ /**
2556
+ * Patch the Raindrop event for a completed, aborted, or errored text
2557
+ * generation so it leaves the `isPending` state. Shared by `onFinish`/`onEnd`,
2558
+ * `onAbort`, and `onError`.
2559
+ */
2560
+ finalizeGenerateEvent(state, output, model) {
2561
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2412
2562
  const suppressSubagentEvent = state.subagentName !== void 0 && state.subagentToolCallSpan !== void 0;
2413
- if (this.sendEvents && !suppressSubagentEvent) {
2414
- const callMeta = this.extractRaindropMetadata(state.metadata);
2415
- const userId = (_f = callMeta.userId) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.userId;
2416
- if (userId) {
2417
- const eventName = (_i = (_h = callMeta.eventName) != null ? _h : (_g = this.defaultContext) == null ? void 0 : _g.eventName) != null ? _i : state.operationId;
2418
- const output = (_j = event.text) != null ? _j : state.accumulatedText || void 0;
2419
- const input = state.inputText;
2420
- const model = (_k = event.response) == null ? void 0 : _k.modelId;
2421
- const properties = {
2422
- ...(_l = this.defaultContext) == null ? void 0 : _l.properties,
2423
- ...callMeta.properties
2424
- };
2425
- const convoId = (_n = callMeta.convoId) != null ? _n : (_m = this.defaultContext) == null ? void 0 : _m.convoId;
2426
- void this.eventShipper.patch(state.eventId, {
2427
- eventName,
2428
- userId,
2429
- convoId,
2430
- input,
2431
- output,
2432
- model,
2433
- properties: Object.keys(properties).length > 0 ? properties : void 0,
2434
- isPending: false
2435
- }).catch((err) => {
2436
- if (this.debug) {
2437
- console.warn(
2438
- `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
2439
- );
2440
- }
2441
- });
2563
+ if (!this.sendEvents || suppressSubagentEvent) return;
2564
+ const callMeta = this.extractRaindropMetadata(state.metadata);
2565
+ const userId = (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId;
2566
+ if (!userId) return;
2567
+ const eventName = (_e = (_d = callMeta.eventName) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.eventName) != null ? _e : state.operationId;
2568
+ const input = state.inputText;
2569
+ const properties = {
2570
+ ...(_f = this.defaultContext) == null ? void 0 : _f.properties,
2571
+ ...callMeta.properties
2572
+ };
2573
+ const convoId = (_h = callMeta.convoId) != null ? _h : (_g = this.defaultContext) == null ? void 0 : _g.convoId;
2574
+ void this.eventShipper.patch(state.eventId, {
2575
+ eventName,
2576
+ userId,
2577
+ convoId,
2578
+ input,
2579
+ output,
2580
+ model,
2581
+ properties: Object.keys(properties).length > 0 ? properties : void 0,
2582
+ isPending: false
2583
+ }).catch((err) => {
2584
+ if (this.debug) {
2585
+ console.warn(
2586
+ `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
2587
+ );
2442
2588
  }
2443
- }
2589
+ });
2444
2590
  }
2445
2591
  finishEmbed(event, state) {
2446
2592
  var _a;
@@ -2465,22 +2611,9 @@ var RaindropTelemetryIntegration = class {
2465
2611
  }
2466
2612
  };
2467
2613
 
2468
- // src/internal/traces.ts
2469
- var TraceShipper2 = class extends TraceShipper {
2470
- constructor(opts) {
2471
- var _a, _b, _c;
2472
- super({
2473
- ...opts,
2474
- sdkName: (_a = opts.sdkName) != null ? _a : "ai-sdk",
2475
- serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.ai-sdk",
2476
- serviceVersion: (_c = opts.serviceVersion) != null ? _c : libraryVersion
2477
- });
2478
- }
2479
- };
2480
-
2481
- // src/internal/wrap/wrapAISDK.ts
2482
- var AGENT_REPORTING_TOOL_NAME_DEFAULT = "__raindrop_report";
2483
- var AGENT_REPORTING_SIGNALS_DEFAULT = {
2614
+ // src/internal/self-diagnostics.ts
2615
+ var SELF_DIAGNOSTICS_TOOL_NAME_DEFAULT = "__raindrop_report";
2616
+ var SELF_DIAGNOSTICS_SIGNALS_DEFAULT = {
2484
2617
  missing_context: {
2485
2618
  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.",
2486
2619
  sentiment: "NEGATIVE"
@@ -2498,7 +2631,194 @@ var AGENT_REPORTING_SIGNALS_DEFAULT = {
2498
2631
  sentiment: "NEGATIVE"
2499
2632
  }
2500
2633
  };
2501
- 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.";
2634
+ 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.";
2635
+ function normalizeString(value) {
2636
+ if (typeof value !== "string") return void 0;
2637
+ const trimmed = value.trim();
2638
+ return trimmed || void 0;
2639
+ }
2640
+ function normalizeSelfDiagnosticsSignals(signals) {
2641
+ if (!signals) return SELF_DIAGNOSTICS_SIGNALS_DEFAULT;
2642
+ const normalizedEntries = Object.entries(signals).map(([key, value]) => {
2643
+ var _a;
2644
+ const signalKey = key.trim();
2645
+ if (!signalKey || !value || typeof value !== "object") return void 0;
2646
+ const description = (_a = value.description) == null ? void 0 : _a.trim();
2647
+ if (!description) return void 0;
2648
+ const sentiment = value.sentiment;
2649
+ return [
2650
+ signalKey,
2651
+ {
2652
+ description,
2653
+ ...sentiment === "POSITIVE" || sentiment === "NEGATIVE" ? { sentiment } : {}
2654
+ }
2655
+ ];
2656
+ }).filter(
2657
+ (entry) => entry !== void 0
2658
+ );
2659
+ if (normalizedEntries.length === 0) return SELF_DIAGNOSTICS_SIGNALS_DEFAULT;
2660
+ return Object.fromEntries(normalizedEntries);
2661
+ }
2662
+ function resolveSelfDiagnosticsConfig(options) {
2663
+ var _a, _b;
2664
+ const signalDefinitions = normalizeSelfDiagnosticsSignals(options.signals);
2665
+ const signalKeys = Object.keys(signalDefinitions);
2666
+ const signalDescriptions = {};
2667
+ const signalSentiments = {};
2668
+ for (const signalKey of signalKeys) {
2669
+ const definition = signalDefinitions[signalKey];
2670
+ if (!definition) continue;
2671
+ signalDescriptions[signalKey] = definition.description;
2672
+ signalSentiments[signalKey] = definition.sentiment;
2673
+ }
2674
+ const customGuidance = ((_a = options.guidance) == null ? void 0 : _a.trim()) || "";
2675
+ const toolName = ((_b = options.toolName) == null ? void 0 : _b.trim()) || SELF_DIAGNOSTICS_TOOL_NAME_DEFAULT;
2676
+ const signalList = signalKeys.map((signalKey) => {
2677
+ const sentiment = signalSentiments[signalKey];
2678
+ const sentimentTag = sentiment ? ` [${sentiment.toLowerCase()}]` : "";
2679
+ return `- ${signalKey}: ${signalDescriptions[signalKey]}${sentimentTag}`;
2680
+ }).join("\n");
2681
+ const guidanceBlock = customGuidance ? `
2682
+ Additional guidance: ${customGuidance}
2683
+ ` : "";
2684
+ const toolDescription = `${SELF_DIAGNOSTICS_TOOL_PREAMBLE}
2685
+
2686
+ When to call:
2687
+ - You are blocked from completing the task due to missing information or access that the user cannot provide.
2688
+ - A tool is persistently failing across multiple attempts, not just a single transient error.
2689
+ - The task requires a tool, permission, or capability you do not have.
2690
+ - You genuinely cannot deliver what the user asked for despite trying.
2691
+
2692
+ When NOT to call:
2693
+ - Normal clarifying questions or back-and-forth with the user.
2694
+ - A single tool error that you can recover from or retry.
2695
+ - You successfully completed the task, even if it was difficult.
2696
+ - Policy refusals or content filtering \u2014 those are working as intended.
2697
+
2698
+ Rules:
2699
+ 1. Pick the single best category.
2700
+ 2. Do not fabricate issues. Only report what is evident from the conversation.
2701
+ 3. Err on the side of NOT calling this tool. When in doubt, help the user instead.
2702
+ ${guidanceBlock}
2703
+ Categories:
2704
+ ` + signalList;
2705
+ return {
2706
+ toolName,
2707
+ toolDescription,
2708
+ signalKeys,
2709
+ signalKeySet: new Set(signalKeys),
2710
+ signalDescriptions,
2711
+ signalSentiments
2712
+ };
2713
+ }
2714
+ function normalizeSelfDiagnosticsConfig(options) {
2715
+ if (!(options == null ? void 0 : options.enabled)) return void 0;
2716
+ return resolveSelfDiagnosticsConfig(options);
2717
+ }
2718
+ function asVercelSchema(inputSchema) {
2719
+ const validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
2720
+ const schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
2721
+ return {
2722
+ [schemaSymbol]: true,
2723
+ [validatorSymbol]: true,
2724
+ _type: void 0,
2725
+ jsonSchema: inputSchema,
2726
+ validate: (value) => ({ success: true, value })
2727
+ };
2728
+ }
2729
+ function resolveStandaloneEventId(options) {
2730
+ var _a, _b, _c, _d, _e, _f;
2731
+ 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);
2732
+ }
2733
+ function createSelfDiagnosticsToolDefinition(args) {
2734
+ const { config, eventShipper, getEventId, aiSDKVersion, debug } = args;
2735
+ const inputJsonSchema = {
2736
+ type: "object",
2737
+ additionalProperties: false,
2738
+ properties: {
2739
+ category: {
2740
+ type: "string",
2741
+ enum: config.signalKeys,
2742
+ description: "The single best-matching category from the list above."
2743
+ },
2744
+ detail: {
2745
+ type: "string",
2746
+ description: "One sentence of factual context: what happened and why it matters. Do not include PII or secrets."
2747
+ }
2748
+ },
2749
+ required: ["category", "detail"]
2750
+ };
2751
+ const inputSchema = asVercelSchema(inputJsonSchema);
2752
+ const execute = async (rawInput) => {
2753
+ var _a, _b;
2754
+ const fallbackCategory = (_a = config.signalKeys[0]) != null ? _a : "unknown";
2755
+ const categoryCandidate = normalizeString(rawInput == null ? void 0 : rawInput.category);
2756
+ const category = categoryCandidate && config.signalKeySet.has(categoryCandidate) ? categoryCandidate : fallbackCategory;
2757
+ const detail = normalizeString(rawInput == null ? void 0 : rawInput.detail);
2758
+ const eventId = getEventId();
2759
+ if (!eventId) {
2760
+ const message = "self diagnostics signal skipped: missing eventId. Pass eventId or getEventId when creating the tool.";
2761
+ if (args.onMissingEventId === "throw") {
2762
+ throw new Error(`[raindrop-ai/ai-sdk] ${message}`);
2763
+ }
2764
+ if (((_b = args.onMissingEventId) != null ? _b : "warn") === "warn") {
2765
+ console.warn(`[raindrop-ai/ai-sdk] ${message}`);
2766
+ }
2767
+ return { acknowledged: false, category, reason: "missing_event_id" };
2768
+ }
2769
+ void eventShipper.trackSignal({
2770
+ eventId,
2771
+ name: `self diagnostics - ${category}`,
2772
+ type: "agent",
2773
+ sentiment: config.signalSentiments[category],
2774
+ properties: {
2775
+ source: "agent_reporting_tool",
2776
+ category,
2777
+ signal_description: config.signalDescriptions[category],
2778
+ ...aiSDKVersion ? { ai_sdk_version: aiSDKVersion } : {},
2779
+ ...detail ? { detail } : {}
2780
+ }
2781
+ }).catch((error) => {
2782
+ if (debug) {
2783
+ const message = error instanceof Error ? error.message : String(error);
2784
+ console.warn(`[raindrop-ai/ai-sdk] selfDiagnostics signal dispatch failed: ${message}`);
2785
+ }
2786
+ });
2787
+ return { acknowledged: true, category };
2788
+ };
2789
+ return {
2790
+ name: config.toolName,
2791
+ description: config.toolDescription,
2792
+ parameters: inputSchema,
2793
+ inputSchema,
2794
+ execute
2795
+ };
2796
+ }
2797
+ function createStandaloneSelfDiagnosticsTool(args) {
2798
+ const config = resolveSelfDiagnosticsConfig(args.options);
2799
+ return createSelfDiagnosticsToolDefinition({
2800
+ config,
2801
+ eventShipper: args.eventShipper,
2802
+ getEventId: () => resolveStandaloneEventId(args.options),
2803
+ onMissingEventId: args.options.onMissingEventId,
2804
+ debug: args.debug
2805
+ });
2806
+ }
2807
+
2808
+ // src/internal/traces.ts
2809
+ var TraceShipper2 = class extends TraceShipper {
2810
+ constructor(opts) {
2811
+ var _a, _b, _c;
2812
+ super({
2813
+ ...opts,
2814
+ sdkName: (_a = opts.sdkName) != null ? _a : "ai-sdk",
2815
+ serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.ai-sdk",
2816
+ serviceVersion: (_c = opts.serviceVersion) != null ? _c : libraryVersion
2817
+ });
2818
+ }
2819
+ };
2820
+
2821
+ // src/internal/wrap/wrapAISDK.ts
2502
2822
  var pendingStoresByShipper = /* @__PURE__ */ new WeakMap();
2503
2823
  var PendingToolSpanStore = class _PendingToolSpanStore {
2504
2824
  constructor() {
@@ -2602,85 +2922,6 @@ function mergeContexts(wrapTime, callTime) {
2602
2922
  }
2603
2923
  return result;
2604
2924
  }
2605
- function normalizeSelfDiagnosticsSignals(signals) {
2606
- if (!signals) return AGENT_REPORTING_SIGNALS_DEFAULT;
2607
- const normalizedEntries = Object.entries(signals).map(([key, value]) => {
2608
- var _a;
2609
- const signalKey = key.trim();
2610
- if (!signalKey || !value || typeof value !== "object") return void 0;
2611
- const description = (_a = value.description) == null ? void 0 : _a.trim();
2612
- if (!description) return void 0;
2613
- const sentiment = value.sentiment;
2614
- return [
2615
- signalKey,
2616
- {
2617
- description,
2618
- ...sentiment === "POSITIVE" || sentiment === "NEGATIVE" ? { sentiment } : {}
2619
- }
2620
- ];
2621
- }).filter(
2622
- (entry) => entry !== void 0
2623
- );
2624
- if (normalizedEntries.length === 0) return AGENT_REPORTING_SIGNALS_DEFAULT;
2625
- return Object.fromEntries(normalizedEntries);
2626
- }
2627
- function normalizeSelfDiagnosticsConfig(options) {
2628
- var _a, _b;
2629
- if (!(options == null ? void 0 : options.enabled)) return void 0;
2630
- const signalDefinitions = normalizeSelfDiagnosticsSignals(options.signals);
2631
- const signalKeys = Object.keys(signalDefinitions);
2632
- const signalDescriptions = {};
2633
- const signalSentiments = {};
2634
- for (const signalKey of signalKeys) {
2635
- const def = signalDefinitions[signalKey];
2636
- if (!def) continue;
2637
- signalDescriptions[signalKey] = def.description;
2638
- signalSentiments[signalKey] = def.sentiment;
2639
- }
2640
- const customGuidanceText = ((_a = options.guidance) == null ? void 0 : _a.trim()) || "";
2641
- const toolName = ((_b = options.toolName) == null ? void 0 : _b.trim()) || AGENT_REPORTING_TOOL_NAME_DEFAULT;
2642
- const signalList = signalKeys.map((signalKey) => {
2643
- const sentiment = signalSentiments[signalKey];
2644
- const sentimentTag = sentiment ? ` [${sentiment.toLowerCase()}]` : "";
2645
- return `- ${signalKey}: ${signalDescriptions[signalKey]}${sentimentTag}`;
2646
- }).join("\n");
2647
- const guidanceBlock = customGuidanceText ? `
2648
- Additional guidance: ${customGuidanceText}
2649
- ` : "";
2650
- const toolDescription = `${AGENT_REPORTING_TOOL_PREAMBLE}
2651
-
2652
- When to call:
2653
- - You are blocked from completing the task due to missing information or access that the user cannot provide.
2654
- - A tool is persistently failing across multiple attempts, not just a single transient error.
2655
- - The task requires a tool, permission, or capability you do not have.
2656
- - You genuinely cannot deliver what the user asked for despite trying.
2657
-
2658
- When NOT to call:
2659
- - Normal clarifying questions or back-and-forth with the user.
2660
- - A single tool error that you can recover from or retry.
2661
- - You successfully completed the task, even if it was difficult.
2662
- - Policy refusals or content filtering \u2014 those are working as intended.
2663
-
2664
- Rules:
2665
- 1. Pick the single best category.
2666
- 2. Do not fabricate issues. Only report what is evident from the conversation.
2667
- 3. Err on the side of NOT calling this tool. When in doubt, help the user instead.
2668
- ${guidanceBlock}
2669
- Categories:
2670
- ${signalList}`;
2671
- return {
2672
- toolName,
2673
- toolDescription,
2674
- signalKeys,
2675
- signalKeySet: new Set(signalKeys),
2676
- signalDescriptions,
2677
- signalSentiments
2678
- };
2679
- }
2680
- function resolveJsonSchemaFactory(aiSDK) {
2681
- if (!isRecord(aiSDK) || !isFunction(aiSDK["jsonSchema"])) return void 0;
2682
- return aiSDK["jsonSchema"];
2683
- }
2684
2925
  function detectAISDKVersion(aiSDK) {
2685
2926
  if (!isRecord(aiSDK)) return "unknown";
2686
2927
  if (isFunction(aiSDK["jsonSchema"])) return "6";
@@ -2699,80 +2940,16 @@ function resolveRegisterTelemetry(aiSDK) {
2699
2940
  const fn = (_a = aiSDK["registerTelemetry"]) != null ? _a : aiSDK["registerTelemetryIntegration"];
2700
2941
  return isFunction(fn) ? fn : void 0;
2701
2942
  }
2702
- function asVercelSchema(jsonSchemaObj) {
2703
- const validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
2704
- const schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
2705
- return {
2706
- [schemaSymbol]: true,
2707
- [validatorSymbol]: true,
2708
- _type: void 0,
2709
- jsonSchema: jsonSchemaObj,
2710
- validate: (value) => ({ success: true, value })
2711
- };
2712
- }
2713
2943
  function createSelfDiagnosticsTool(ctx) {
2714
2944
  const config = ctx.selfDiagnostics;
2715
2945
  if (!config) return void 0;
2716
- const schema = {
2717
- type: "object",
2718
- additionalProperties: false,
2719
- properties: {
2720
- category: {
2721
- type: "string",
2722
- enum: config.signalKeys,
2723
- description: "The single best-matching category from the list above."
2724
- },
2725
- detail: {
2726
- type: "string",
2727
- description: "One sentence of factual context: what happened and why it matters. Do not include PII or secrets."
2728
- }
2729
- },
2730
- required: ["category", "detail"]
2731
- };
2732
- const parameters = asVercelSchema(schema);
2733
- let inputSchema = parameters;
2734
- if (ctx.jsonSchemaFactory) {
2735
- try {
2736
- inputSchema = ctx.jsonSchemaFactory(schema);
2737
- } catch (e) {
2738
- inputSchema = parameters;
2739
- }
2740
- }
2741
- const execute = async (rawInput) => {
2742
- var _a;
2743
- const input = isRecord(rawInput) ? rawInput : void 0;
2744
- const fallbackCategory = (_a = config.signalKeys[0]) != null ? _a : "unknown";
2745
- const categoryCandidate = typeof (input == null ? void 0 : input["category"]) === "string" ? input["category"].trim() : void 0;
2746
- const category = categoryCandidate && config.signalKeySet.has(categoryCandidate) ? categoryCandidate : fallbackCategory;
2747
- const detail = typeof (input == null ? void 0 : input["detail"]) === "string" ? input["detail"].trim() : "";
2748
- const signalDescription = config.signalDescriptions[category];
2749
- const signalSentiment = config.signalSentiments[category];
2750
- void ctx.eventShipper.trackSignal({
2751
- eventId: ctx.eventId,
2752
- name: `self diagnostics - ${category}`,
2753
- type: "agent",
2754
- sentiment: signalSentiment,
2755
- properties: {
2756
- source: "agent_reporting_tool",
2757
- category,
2758
- signal_description: signalDescription,
2759
- ai_sdk_version: ctx.aiSDKVersion,
2760
- ...detail ? { detail } : {}
2761
- }
2762
- }).catch((err) => {
2763
- if (ctx.debug) {
2764
- const msg = err instanceof Error ? err.message : String(err);
2765
- console.warn(`[raindrop-ai/ai-sdk] selfDiagnostics signal dispatch failed: ${msg}`);
2766
- }
2767
- });
2768
- return { acknowledged: true, category };
2769
- };
2770
- return {
2771
- description: config.toolDescription,
2772
- execute,
2773
- parameters,
2774
- inputSchema
2775
- };
2946
+ return createSelfDiagnosticsToolDefinition({
2947
+ config,
2948
+ eventShipper: ctx.eventShipper,
2949
+ getEventId: () => ctx.eventId,
2950
+ aiSDKVersion: ctx.aiSDKVersion,
2951
+ debug: ctx.debug
2952
+ });
2776
2953
  }
2777
2954
  function getCurrentParentSpanContextSync() {
2778
2955
  return getContextManager().getParentSpanIds();
@@ -2999,7 +3176,6 @@ function setupOperation(params) {
2999
3176
  eventShipper,
3000
3177
  traceShipper,
3001
3178
  rootParentForChildren,
3002
- jsonSchemaFactory: resolveJsonSchemaFactory(aiSDK),
3003
3179
  selfDiagnostics: operationSelfDiagnostics,
3004
3180
  aiSDKVersion: detectAISDKVersion(aiSDK)
3005
3181
  };
@@ -3348,7 +3524,6 @@ function wrapAISDK(aiSDK, deps) {
3348
3524
  );
3349
3525
  }
3350
3526
  const selfDiagnostics2 = normalizeSelfDiagnosticsConfig(deps.options.selfDiagnostics);
3351
- const jsonSchemaFactory = selfDiagnostics2 ? resolveJsonSchemaFactory(aiSDK) : void 0;
3352
3527
  const metadataAwareOps = /* @__PURE__ */ new Set([
3353
3528
  "generateText",
3354
3529
  "streamText",
@@ -3380,14 +3555,9 @@ function wrapAISDK(aiSDK, deps) {
3380
3555
  const perCallEventIdGenerated = !perCallEventIdExplicit;
3381
3556
  const perCallCtx = {
3382
3557
  eventId: perCallEventId,
3383
- context: wrapTimeCtx,
3384
- telemetry,
3385
- sendTraces: false,
3386
3558
  debug,
3387
3559
  eventShipper: deps.eventShipper,
3388
3560
  traceShipper: deps.traceShipper,
3389
- rootParentForChildren: void 0,
3390
- jsonSchemaFactory,
3391
3561
  selfDiagnostics: selfDiagnostics2,
3392
3562
  aiSDKVersion: "7"
3393
3563
  };
@@ -3589,7 +3759,6 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
3589
3759
  eventShipper: deps.eventShipper,
3590
3760
  traceShipper: deps.traceShipper,
3591
3761
  rootParentForChildren,
3592
- jsonSchemaFactory: resolveJsonSchemaFactory(aiSDK),
3593
3762
  selfDiagnostics,
3594
3763
  aiSDKVersion: detectAISDKVersion(aiSDK)
3595
3764
  };
@@ -3797,7 +3966,6 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
3797
3966
  eventShipper: deps.eventShipper,
3798
3967
  traceShipper: deps.traceShipper,
3799
3968
  rootParentForChildren,
3800
- jsonSchemaFactory: resolveJsonSchemaFactory(aiSDK),
3801
3969
  selfDiagnostics,
3802
3970
  aiSDKVersion: detectAISDKVersion(aiSDK)
3803
3971
  };
@@ -4613,6 +4781,14 @@ function createRaindropAISDK(opts) {
4613
4781
  traceShipper
4614
4782
  });
4615
4783
  },
4784
+ createSelfDiagnosticsTool(options = {}) {
4785
+ var _a2;
4786
+ return createStandaloneSelfDiagnosticsTool({
4787
+ options,
4788
+ eventShipper,
4789
+ debug: ((_a2 = opts.events) == null ? void 0 : _a2.debug) === true || envDebug
4790
+ });
4791
+ },
4616
4792
  createTelemetryIntegration(contextOrOptions) {
4617
4793
  const FLAT_CONTEXT_KEYS = [
4618
4794
  "userId",
@@ -4743,5 +4919,12 @@ function createRaindropAISDK(opts) {
4743
4919
  }
4744
4920
  };
4745
4921
  }
4922
+ function raindrop(options = {}) {
4923
+ var _a;
4924
+ const { context, subagentWrapping, writeKey, ...rest } = options;
4925
+ const resolvedWriteKey = writeKey != null ? writeKey : typeof process !== "undefined" ? (_a = process.env) == null ? void 0 : _a.RAINDROP_WRITE_KEY : void 0;
4926
+ const client = createRaindropAISDK({ ...rest, writeKey: resolvedWriteKey });
4927
+ return client.createTelemetryIntegration({ context, subagentWrapping });
4928
+ }
4746
4929
 
4747
- 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 };
4930
+ 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, raindrop, readRaindropCallMetadataFromArgs, redactJsonAttributeValue, redactSecretsInObject, runWithParentToolContext, runWithRaindropCallMetadata, withCurrent };