import { createLogger } from "../logger.js";
const log = createLogger("server");
async function tryConnectDaemon(port, host) {
  const url = `http://${host}:${port}/health`;
  try {
    const response = await fetch(url, {
      signal: AbortSignal.timeout(2e3)
    });
    if (!response.ok) {
      log.debug("Daemon health check returned non-OK status", { status: response.status });
      return null;
    }
    const report = await response.json();
    log.debug("Daemon is running", { port, host, status: report.status });
    return report;
  } catch {
    log.debug("No daemon running", { port, host });
    return null;
  }
}
class DaemonProxy {
  baseUrl;
  constructor(url) {
    this.baseUrl = url;
  }
  async callTool(toolName, args) {
    const url = `${this.baseUrl}/mcp`;
    try {
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          jsonrpc: "2.0",
          method: "tools/call",
          id: Date.now(),
          params: {
            name: toolName,
            arguments: args
          }
        }),
        signal: AbortSignal.timeout(6e4)
      });
      if (!response.ok) {
        const text = await response.text().catch(() => "");
        throw new Error(`Daemon returned HTTP ${response.status}: ${text}`);
      }
      return response.json();
    } catch (err) {
      if (err instanceof Error && err.message.startsWith("Daemon returned")) throw err;
      throw new Error(`Failed to call tool via daemon: ${err instanceof Error ? err.message : String(err)}`);
    }
  }
  async checkHealth() {
    try {
      const response = await fetch(`${this.baseUrl}/health`, {
        signal: AbortSignal.timeout(2e3)
      });
      if (!response.ok) return null;
      return response.json();
    } catch {
      return null;
    }
  }
  async listTools() {
    const url = `${this.baseUrl}/mcp`;
    try {
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          jsonrpc: "2.0",
          method: "tools/list",
          id: Date.now(),
          params: {}
        }),
        signal: AbortSignal.timeout(1e4)
      });
      if (!response.ok) return null;
      return response.json();
    } catch {
      return null;
    }
  }
}
export {
  DaemonProxy,
  tryConnectDaemon
};
//# sourceMappingURL=proxy.js.map