#!/usr/bin/env node
import { createRequire } from "module"; const require = createRequire(import.meta.url);


// src/mcp/stdio-mcp-server.ts
import * as readline from "node:readline";
function runStdioMcpServer(options) {
  const rl = readline.createInterface({ input: process.stdin, terminal: false });
  rl.on("line", (line) => {
    void handleLine(line);
  });
  async function handleLine(line) {
    const trimmed = line.trim();
    if (!trimmed) return;
    let msg;
    try {
      msg = JSON.parse(trimmed);
    } catch {
      return;
    }
    if (msg.jsonrpc !== "2.0" || typeof msg.method !== "string") return;
    const id = msg.id;
    const respond = (result) => {
      if (id === void 0) return;
      process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}
`);
    };
    const respondError = (message) => {
      if (id === void 0) return;
      process.stdout.write(
        `${JSON.stringify({ jsonrpc: "2.0", id, error: { code: -32603, message } })}
`
      );
    };
    try {
      switch (msg.method) {
        case "initialize":
          respond({
            protocolVersion: "2024-11-05",
            capabilities: { tools: {} },
            serverInfo: { name: options.serverName, version: options.serverVersion }
          });
          return;
        case "notifications/initialized":
          return;
        case "tools/list":
          respond({ tools: options.tools });
          return;
        case "tools/call": {
          const name = typeof msg.params?.name === "string" ? msg.params.name : "";
          const args = msg.params?.arguments != null && typeof msg.params.arguments === "object" && !Array.isArray(msg.params.arguments) ? msg.params.arguments : {};
          if (!name) {
            respondError("Tool name required");
            return;
          }
          const result = await options.callTool(name, args);
          respond(result);
          return;
        }
        default:
          if (id !== void 0) respondError(`Unknown method: ${msg.method}`);
      }
    } catch (err) {
      respondError(err instanceof Error ? err.message : String(err));
    }
  }
}

// src/mcp/fork-history-constants.ts
var FORK_HISTORY_MCP_SERVER_NAME = "buildautomaton-fork-history";
var FORK_HISTORY_TOOL_LIST_TURNS = "list_forked_session_turns";
var FORK_HISTORY_TOOL_GET_TURN_TRANSCRIPT = "get_forked_session_turn_transcript";

// src/mcp/fork-history-mcp-server.ts
var ipcPort = Number.parseInt(process.env.BA_MCP_IPC_PORT ?? "", 10);
var parentSessionId = (process.env.BA_FORK_PARENT_SESSION_ID ?? "").trim();
async function ipcRequest(body) {
  if (!Number.isFinite(ipcPort) || ipcPort <= 0) {
    throw new Error("BA_MCP_IPC_PORT is not configured");
  }
  const res = await fetch(`http://127.0.0.1:${ipcPort}/fork-history`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body)
  });
  const json = await res.json();
  if (!json.ok) {
    throw new Error(json.error ?? "Fork history IPC request failed");
  }
  return json.data;
}
var tools = [
  {
    name: FORK_HISTORY_TOOL_LIST_TURNS,
    description: "List prompt turns from the parent session this fork continues from. Returns summaries and previews for each turn.",
    inputSchema: { type: "object", properties: {}, additionalProperties: false }
  },
  {
    name: FORK_HISTORY_TOOL_GET_TURN_TRANSCRIPT,
    description: "Fetch the full transcript for a specific turn from the parent session. Use turnId from list_forked_session_turns.",
    inputSchema: {
      type: "object",
      properties: {
        turnId: { type: "string", description: "Turn id from list_forked_session_turns" }
      },
      required: ["turnId"],
      additionalProperties: false
    }
  }
];
runStdioMcpServer({
  serverName: FORK_HISTORY_MCP_SERVER_NAME,
  serverVersion: "0.1.0",
  tools,
  callTool: async (name, args) => {
    if (!parentSessionId) {
      throw new Error("This MCP server is only available for forked sessions");
    }
    if (name === FORK_HISTORY_TOOL_LIST_TURNS) {
      const data = await ipcRequest({ parentSessionId, action: "list_turns" });
      return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
    }
    if (name === FORK_HISTORY_TOOL_GET_TURN_TRANSCRIPT) {
      const turnId = typeof args.turnId === "string" ? args.turnId.trim() : "";
      if (!turnId) throw new Error("turnId is required");
      const data = await ipcRequest({ parentSessionId, action: "get_turn_transcript", turnId });
      return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
    }
    throw new Error(`Unknown tool: ${name}`);
  }
});
//# sourceMappingURL=fork-history-mcp-server.js.map
