import { tool } from "@opencode-ai/plugin";

const internalBaseUrl =
  process.env.TJWATER_AGENT_INTERNAL_BASE_URL ?? "http://127.0.0.1:8787";
const internalToken = process.env.TJWATER_AGENT_INTERNAL_TOKEN ?? "";

export default tool({
  description:
    "搜索当前用户和项目范围内的历史会话 transcript。适合回忆过去讨论过的案例、约束和结论，避免把一次性案例写入 memory。",
  args: {
    reason: tool.schema
      .string()
      .describe("Why prior session history is needed for the current request."),
    query: tool.schema
      .string()
      .describe("What to search for in prior session history."),
    max_results: tool.schema
      .number()
      .int()
      .positive()
      .optional()
      .describe("Optional maximum number of hits to return."),
  },
  async execute(args, context) {
    const response = await fetch(
      `${internalBaseUrl}/internal/tools/session-search`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-agent-internal-token": internalToken,
        },
        body: JSON.stringify({
          max_results: args.max_results,
          query: args.query,
          session_id: context.sessionID,
        }),
      },
    );
    const text = await response.text();
    if (!response.ok) {
      throw new Error(text);
    }
    return text;
  },
});
