// @bun
var __defProp = Object.defineProperty;
var __returnValue = (v) => v;
function __exportSetter(name, newValue) {
  this[name] = __returnValue.bind(null, newValue);
}
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, {
      get: all[name],
      enumerable: true,
      configurable: true,
      set: __exportSetter.bind(all, name)
    });
};
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = import.meta.require;

// src/tools/subagent-tool.ts
import { readUIMessageStream, tool } from "ai";
import { z } from "zod";
function toReadableStream(iterable) {
  if (iterable instanceof ReadableStream) {
    return iterable;
  }
  return new ReadableStream({
    async start(controller) {
      try {
        for await (const chunk of iterable) {
          controller.enqueue(chunk);
        }
      } finally {
        controller.close();
      }
    }
  });
}
function createSubagentTool(options) {
  const {
    subagent,
    description = "Research a topic or question in depth.",
    taskParam = "task",
    toModelSummary = true,
    passConversationHistory = false
  } = options;
  const inputSchema = z.object({
    [taskParam]: z.string().describe("The research task to complete")
  });
  const execute = async function* (input, options2) {
    const task = String(input[taskParam] ?? input.task ?? "");
    const { abortSignal, messages } = options2 ?? {};
    if (passConversationHistory && messages && messages.length > 0 && typeof subagent.generate === "function") {
      const result2 = await subagent.generate({
        messages: [...messages, { role: "user", content: task }],
        abortSignal
      });
      yield { parts: [{ type: "text", text: result2.text }] };
      return;
    }
    const result = await subagent.stream({
      prompt: task,
      abortSignal
    });
    const uiStream = result.toUIMessageStream();
    const stream = toReadableStream(uiStream);
    for await (const message of readUIMessageStream({
      stream
    })) {
      yield message;
    }
  };
  const toolOptions = {
    description,
    inputSchema,
    execute,
    ...toModelSummary && {
      toModelOutput: ({
        output
      }) => {
        const parts = output?.parts;
        if (!Array.isArray(parts)) {
          return { type: "text", value: "Task completed." };
        }
        const lastTextPart = [...parts].reverse().find((p) => p?.type === "text");
        return {
          type: "text",
          value: lastTextPart?.text ?? "Task completed."
        };
      }
    }
  };
  return tool(toolOptions);
}
var init_subagent_tool = () => {};
init_subagent_tool();

export {
  createSubagentTool
};
