#!/usr/bin/env node
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};

// src/cli/detect-tools.ts
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
function which(bin) {
  try {
    if (process.platform === "win32") {
      const out2 = execFileSync("where", [bin], {
        encoding: "utf8",
        timeout: 3e3,
        stdio: ["ignore", "pipe", "ignore"]
      });
      const first = out2.split(/\r?\n/).find((line) => line.trim().length > 0);
      return first?.trim() ?? null;
    }
    const out = execFileSync("sh", ["-c", `command -v ${bin}`], {
      encoding: "utf8",
      timeout: 3e3,
      stdio: ["ignore", "pipe", "ignore"]
    });
    return out.trim() || null;
  } catch {
    return null;
  }
}
function tryDir(path) {
  return existsSync(path) ? path : null;
}
function detectClaudeCode() {
  const configDir = tryDir(join(homedir(), ".claude"));
  const bin = which("claude");
  if (configDir === null && bin === null) return { found: false };
  return { found: true, path: configDir ?? bin ?? "" };
}
function detectOpenCode() {
  const configDir = tryDir(join(homedir(), ".config", "opencode"));
  const bin = which("opencode");
  if (configDir === null && bin === null) return { found: false };
  return { found: true, path: configDir ?? bin ?? "" };
}
function detectMiMo() {
  const configDir = tryDir(join(homedir(), ".mimo"));
  const bin = which("mimo");
  if (configDir === null && bin === null) return { found: false };
  return { found: true, path: configDir ?? bin ?? "" };
}
function detectCursor() {
  const configDir = tryDir(join(homedir(), ".cursor"));
  const bin = which("cursor");
  if (configDir === null && bin === null) return { found: false };
  return { found: true, path: configDir ?? bin ?? "" };
}
function detectCody() {
  const configDir = tryDir(join(homedir(), ".config", "cody"));
  const bin = which("cody");
  if (configDir === null && bin === null) return { found: false };
  return { found: true, path: configDir ?? bin ?? "" };
}
function detectAll() {
  return DETECTORS.map(({ id, displayName, detect }) => ({
    id,
    displayName,
    result: detect()
  }));
}
function detectFirst() {
  for (const entry of DETECTORS) {
    const result = entry.detect();
    if (result.found) return { id: entry.id, displayName: entry.displayName, result };
  }
  return null;
}
var DETECTORS;
var init_detect_tools = __esm({
  "src/cli/detect-tools.ts"() {
    "use strict";
    DETECTORS = [
      { id: "claude-code", displayName: "Claude Code", detect: detectClaudeCode },
      { id: "opencode", displayName: "OpenCode", detect: detectOpenCode },
      { id: "mimo", displayName: "MiMo Code", detect: detectMiMo },
      { id: "cursor", displayName: "Cursor", detect: detectCursor },
      { id: "cody", displayName: "Cody", detect: detectCody }
    ];
  }
});

// src/cli/templates/command-onboard.ts
function renderCommandOnboard() {
  return `---
description: Walk through llm-inspector setup \u2014 start the proxy, wire your AI tool, capture your first request.
---

Invoke the \`llm-inspector-onboard\` skill and follow its phases.

The user wants to set up llm-inspector. If they have specific context (e.g. "I'm on Windows", "I already added my API key"), honor it \u2014 but otherwise just run the skill end-to-end and let the \`EXPLAIN / DO / PAUSE\` markers drive the conversation.
`;
}
var init_command_onboard = __esm({
  "src/cli/templates/command-onboard.ts"() {
    "use strict";
  }
});

// src/cli/templates/skill-onboard.ts
function renderSkillOnboard(ctx) {
  const { version, port, detectedSummary } = ctx;
  return `---
name: llm-inspector-onboard
description: Guided setup for llm-inspector v${version} \u2014 start the proxy, wire your AI coding tool, capture your first request, and learn the Web UI.
metadata:
  author: llm-inspector
  version: ${version}
---

# llm-inspector onboard

Guide the user from "I just installed llm-inspector" to "I can see my AI tool's traffic in the Web UI". This is a teaching experience \u2014 you'll do real work in their environment while explaining each step.

Environment detected by the installer:
${detectedSummary || "  (no known AI tool detected \u2014 the user can still use the generic curl example in Phase 4)"}

Default proxy port: \`${port}\` (override with \`PORT=<n> llm-inspector\` or \`--port <n>\`).

---

## Preflight

Before starting, verify the environment.

**EXPLAIN:** "Let's make sure everything we need is in place. Two quick checks."

**DO:** Run the platform-appropriate commands below. The user can copy-paste, or you can run them yourself if you have shell access.

\`\`\`bash
# Unix / macOS / WSL
node --version                  # expect >= 18
test -d "$HOME/.claude" && echo "claude-code: present" || echo "claude-code: not detected"
\`\`\`

\`\`\`powershell
# Windows PowerShell
node --version                  # expect >= 18
if (Test-Path "$env:USERPROFILE\\.claude") { Write-Host "claude-code: present" } else { Write-Host "claude-code: not detected" }
\`\`\`

**PAUSE** \u2014 if Node is older than 18, ask the user to install a newer version (https://nodejs.org) before continuing.

---

## Phase 1: Welcome

**EXPLAIN:**

\`\`\`
## Welcome to llm-inspector!

llm-inspector is a transparent HTTP proxy + Web UI for AI coding tools. Point your tool at it, and you'll see every request and response \u2014 system prompts, tool definitions, message history, SSE streaming chunks, and token counts \u2014 captured live in a browser tab.

**What we'll do in the next ~10 minutes:**
1. Add your first LLM provider (Anthropic or OpenAI key)
2. Start the proxy
3. Wire your AI tool to use it
4. Capture a first request end-to-end
5. Tour the key UI affordances

Ready? Let's start with the provider.
\`\`\`

**PAUSE** \u2014 wait for the user to confirm.

---

## Phase 2: Provider setup

**EXPLAIN:** "A 'provider' is an upstream LLM endpoint \u2014 Anthropic, OpenAI, MiniMax, etc. llm-inspector routes each request to the right upstream based on the model name. You need at least one provider configured for the proxy to forward traffic."

**DO:** Open (or create) \`~/.llm-inspector/config.json\` in the user's editor. If the file doesn't exist, create it with the structure below. Walk the user through filling in their API key for their provider of choice.

\`\`\`json
{
  "providers": [
    {
      "id": "anthropic",
      "type": "anthropic",
      "apiKey": "sk-ant-...",
      "baseUrl": "https://api.anthropic.com"
    }
  ]
}
\`\`\`

Alternative (avoid touching the config file): point the user at the Web UI \u2192 top-right Settings button \u2192 Providers tab, which has a form-driven flow.

**PAUSE** \u2014 wait for the user to confirm they have at least one provider with a key.

---

## Phase 3: Start proxy

**EXPLAIN:** "Time to start the proxy. It binds to port ${port} by default, kills any process already on that port, and prints the URL."

**DO:** Start the proxy in the background so you can keep working.

\`\`\`bash
# Unix / macOS / WSL
nohup llm-inspector --no-open > /tmp/llm-inspector.log 2>&1 &
\`\`\`

\`\`\`powershell
# Windows PowerShell
Start-Process -FilePath "llm-inspector" -ArgumentList "--no-open" -RedirectStandardOutput "$env:TEMP\\llm-inspector.log" -RedirectStandardError "$env:TEMP\\llm-inspector.err.log" -WindowStyle Hidden
\`\`\`

Then wait for the port to be ready:

\`\`\`bash
# Wait up to 10s for the port to come up
for i in $(seq 1 20); do
  curl -fsS "http://localhost:${port}/api/health" >/dev/null 2>&1 && echo "ready" && break
  sleep 0.5
done
\`\`\`

**DO:** Hit the health endpoint to confirm the proxy is alive:

\`\`\`bash
curl -sS "http://localhost:${port}/api/health"
\`\`\`

**PAUSE** \u2014 if the health check fails, show the user the log file (\`/tmp/llm-inspector.log\` or \`%TEMP%\\\\llm-inspector.log\`) and diagnose. Common issues: another process on the port, firewall, missing providers.

---

## Phase 4: Wire tool

**EXPLAIN:** "Now we tell your AI tool to send traffic through the proxy instead of directly to the upstream API. The exact env var depends on which tool you have."

**DO:** Based on the \`Environment detected\` block at the top of this skill, print the matching wiring command. Examples for each supported tool:

\`\`\`bash
# Claude Code
export ANTHROPIC_BASE_URL=http://localhost:${port}/proxy
claude

# OpenCode
export LLM_BASE_URL=http://localhost:${port}/proxy
opencode

# MiMo Code
export OPENAI_BASE_URL=http://localhost:${port}/proxy
mimo

# Cursor / Cody \u2014 set the OpenAI base URL in each tool's settings panel to http://localhost:${port}/proxy
\`\`\`

For a tool that wasn't auto-detected, fall through to the generic curl test in the next phase \u2014 the user can wire their tool later.

**PAUSE** \u2014 wait for the user to confirm they've set the env var (or that they're going to use the curl test instead).

---

## Phase 4.5: Wire MCP server

**EXPLAIN:** "The proxy also exposes an MCP server at \`http://localhost:${port}/api/mcp\`. Your AI agent can query logs, replay requests, and test providers through it \u2014 no need to leave the editor. We'll add an \`mcpServers\` entry so your agent picks it up automatically."

**DO:** Add (or merge) an \`mcpServers\` entry in the user's Claude Code config. The file is \`~/.claude.json\` on all platforms; the MCP spec entry uses HTTP Streamable transport:

\`\`\`json
// ~/.claude.json  (merge into existing mcpServers)
{
  "mcpServers": {
    "llm-inspector": {
      "type": "http",
      "url": "http://localhost:${port}/api/mcp"
    }
  }
}
\`\`\`

If \`mcpServers\` already exists, add \`llm-inspector\` as a new key \u2014 don't clobber existing entries.

PowerShell one-liner that creates the file if missing, or merges if present:

\`\`\`powershell
$cfg = Join-Path $env:USERPROFILE ".claude.json"
if (Test-Path $cfg) {
  $doc = Get-Content $cfg -Raw | ConvertFrom-Json
} else {
  $doc = [pscustomobject]@{ mcpServers = [pscustomobject]@{} }
}
if (-not ($doc.PSObject.Properties.Name -contains "mcpServers")) {
  $doc | Add-Member -NotePropertyName mcpServers -NotePropertyValue ([pscustomobject]@{})
}
$doc.mcpServers | Add-Member -NotePropertyName "llm-inspector" -NotePropertyValue ([pscustomobject]@{
  type = "http"
  url  = "http://localhost:${port}/api/mcp"
}) -Force
$doc | ConvertTo-Json -Depth 10 | Set-Content $cfg -Encoding UTF8
\`\`\`

**DO:** Verify the handshake. The MCP \`initialize\` request should return 200 with a \`serverInfo\` payload \u2014 that proves the server is mounted and reachable:

\`\`\`bash
curl -sS -X POST "http://localhost:${port}/api/mcp" \\
  -H "Content-Type: application/json" \\
  -H "Accept: application/json, text/event-stream" \\
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2025-03-26",
      "capabilities": {},
      "clientInfo": { "name": "onboard-check", "version": "0" }
    }
  }'
# expect: HTTP 200, body contains "result" with serverInfo.name = "llm-inspector"
\`\`\`

After the handshake, issue a \`tools/list\` to confirm the tool catalog is reachable:

\`\`\`bash
SESSION=<session-id-from-initialize-response>
curl -sS -X POST "http://localhost:${port}/api/mcp" \\
  -H "Content-Type: application/json" \\
  -H "Accept: application/json, text/event-stream" \\
  -H "mcp-session-id: $SESSION" \\
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}'
# expect: a result.tools array with at least 1 entry
\`\`\`

**PAUSE** \u2014 if \`initialize\` returns non-200, show the user the proxy log and re-check the JSON syntax. If it returns 200 but \`tools/list\` fails, the server is up but the session wasn't carried over \u2014 re-use the \`mcp-session-id\` header from the first response.

---

## Phase 5: First capture

**EXPLAIN:** "Let's prove the proxy works end-to-end. We'll send one real request through it and confirm the log shows up in the API. A 401/403 from the upstream is fine \u2014 the point is that the *request* reaches the proxy."

**DO:** Fire a minimal Anthropic-format request through the proxy. This works regardless of which tool the user wired up:

\`\`\`bash
curl -sS -X POST "http://localhost:${port}/proxy/v1/messages" \\
  -H "Content-Type: application/json" \\
  -H "anthropic-version: 2023-06-01" \\
  -H "x-api-key: \${LLM_INSPECTOR_API_KEY:-sk-no-key-needed-for-routing}" \\
  -d '{"model":"claude-3-5-sonnet-20241022","max_tokens":1,"messages":[{"role":"user","content":"ping"}]}'
\`\`\`

**DO:** Poll the logs API for up to 5 seconds. A 200 with at least one entry means success:

\`\`\`bash
for i in $(seq 1 10); do
  resp=$(curl -sS "http://localhost:${port}/api/logs?limit=1")
  count=$(echo "$resp" | grep -o '"total":[0-9]*' | head -1 | grep -o '[0-9]*$')
  if [ "\${count:-0}" -ge 1 ]; then
    echo "captured"
    break
  fi
  sleep 0.5
done
\`\`\`

**PAUSE** \u2014 show the user the captured log entry (id, status, model, elapsed). If the count never reached 1, the proxy didn't see the request \u2014 re-check the env var and the proxy log.

---

## Phase 6: Tour & wrap

**EXPLAIN:** "Everything's working. Here's the cheat sheet for the Web UI and the supporting surfaces:"

- **Web UI**: \`http://localhost:${port}/\` \u2014 collapsible log rows, per-tab Copy/Expand in the log header, Diff with Raw (request body), Diff with Previous (compare adjacent requests), Replay (re-send a request), Export (JSON ZIP).
- **MCP server**: \`http://localhost:${port}/api/mcp\` \u2014 connect from your coding agent to query logs, replay, and test providers without leaving the editor. Look for the "MCP Ready" badge in the Web UI header.
- **REST API**: \`/api/logs\`, \`/api/sessions\`, \`/api/providers\` \u2014 for scripting and shell-based inspection.
- **Stop the proxy**:

  \`\`\`bash
  # Unix / macOS
  lsof -ti:${port} | xargs -r kill -9

  # Windows PowerShell
  Get-NetTCPConnection -LocalPort ${port} | ForEach-Object { Stop-Process -Id \\$_.OwningProcess -Force }
  \`\`\`

- **Re-run onboard**: \`llm-inspector onboard --force\` refreshes this skill.
- **Full docs**: see the project README (linked from the Web UI footer).

**PAUSE** \u2014 let the user know they can come back to this skill at any time via \`/llm-inspector:onboard\` if they want a refresher, and call out that \`/llm-inspector:onboard --skip-tool-wire\` is the way to re-run later phases without re-detecting the tool.

You're done. Happy inspecting.
`;
}
var REQUIRED_PHASE_HEADINGS;
var init_skill_onboard = __esm({
  "src/cli/templates/skill-onboard.ts"() {
    "use strict";
    REQUIRED_PHASE_HEADINGS = [
      "Preflight",
      "Phase 1: Welcome",
      "Phase 2: Provider setup",
      "Phase 3: Start proxy",
      "Phase 4: Wire tool",
      "Phase 4.5: Wire MCP server",
      "Phase 5: First capture",
      "Phase 6: Tour & wrap"
    ];
  }
});

// src/cli/onboard.ts
var onboard_exports = {};
__export(onboard_exports, {
  runOnboard: () => runOnboard
});
import { mkdirSync, writeFileSync, existsSync as existsSync2, readFileSync } from "node:fs";
import { homedir as homedir2 } from "node:os";
import { dirname, join as join2 } from "node:path";
import { fileURLToPath } from "node:url";
function parseFlags(argv) {
  const flags = {
    force: false,
    dryRun: false,
    skipProvider: false,
    skipToolWire: false,
    skillDir: null
  };
  for (let i = 0; i < argv.length; i++) {
    const arg = argv[i];
    switch (arg) {
      case void 0:
        continue;
      case "--force":
        flags.force = true;
        break;
      case "--dry-run":
        flags.dryRun = true;
        break;
      case "--skip-provider":
        flags.skipProvider = true;
        break;
      case "--skip-tool-wire":
        flags.skipToolWire = true;
        break;
      case "--skill-dir": {
        const next = argv[i + 1];
        if (next === void 0) {
          process.stderr.write("llm-inspector onboard: --skill-dir requires a path argument\n");
          process.exit(2);
        }
        flags.skillDir = next;
        i++;
        break;
      }
      case "--help":
      case "-h":
        printHelp();
        process.exit(0);
        break;
      default:
        process.stderr.write(`llm-inspector onboard: unknown flag: ${arg}
`);
        process.exit(2);
    }
  }
  return flags;
}
function printHelp() {
  process.stdout.write(`llm-inspector onboard \u2014 install the llm-inspector Claude Code skill

Usage:
  llm-inspector onboard [options]

Options:
  --force              Overwrite the existing skill and slash command if they exist
  --dry-run            Print target paths and a template preview, write nothing
  --skip-provider      Skip the provider-setup phase in the skill body
  --skip-tool-wire     Skip the wire-tool phase in the skill body
  --skill-dir <path>   Override the target skill directory (default: ~/.claude/skills)
  -h, --help           Show this help

Exit codes:
  0  success (or already installed)
  2  invalid arguments
  1  write failed
`);
}
function resolveTargets(flags) {
  const claudeRoot = flags.skillDir ?? join2(homedir2(), ".claude");
  const skillDir = join2(claudeRoot, "skills", SKILL_DIR_NAME);
  const commandsDir = join2(claudeRoot, "commands");
  return {
    skillFile: join2(skillDir, SKILL_FILE_NAME),
    commandFile: join2(commandsDir, COMMAND_FILE_NAME)
  };
}
function isObject(value) {
  return typeof value === "object" && value !== null;
}
function buildDetectedSummary() {
  const entries = detectAll();
  const present = entries.filter((e) => e.result.found);
  const absent = entries.filter((e) => !e.result.found);
  const presentList = present.map((e) => e.displayName).join(", ") || "(none)";
  const absentList = absent.map((e) => e.displayName).join(", ") || "(none)";
  return `  - Detected: ${presentList}
  - Not detected: ${absentList}`;
}
function runOnboard(argv) {
  try {
    return Promise.resolve(runOnboardSync(argv));
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    process.stderr.write(`llm-inspector onboard: ${msg}
`);
    process.stderr.write(
      "(postinstall skill install skipped \u2014 run `llm-inspector onboard` later)\n"
    );
    return Promise.resolve(0);
  }
}
function runOnboardSync(argv) {
  const flags = parseFlags(argv);
  const { skillFile, commandFile } = resolveTargets(flags);
  if (!flags.force && existsSync2(skillFile)) {
    process.stdout.write(`llm-inspector onboard: already installed at ${skillFile}
`);
    process.stdout.write("Re-run with --force to refresh.\n");
    return 0;
  }
  let version = "0.0.0";
  try {
    const raw = JSON.parse(readFileSync(join2(__dirname, "..", "package.json"), "utf8"));
    if (isObject(raw) && typeof raw["version"] === "string") {
      version = raw["version"];
    }
  } catch {
  }
  const detectedSummary = buildDetectedSummary();
  const skillBody = renderSkillOnboard({
    version,
    port: DEFAULT_PORT,
    detectedSummary
  });
  const commandBody = renderCommandOnboard();
  if (flags.dryRun) {
    process.stdout.write(`llm-inspector onboard --dry-run

`);
    process.stdout.write(`Skill target:     ${skillFile}
`);
    process.stdout.write(`Command target:   ${commandFile}

`);
    process.stdout.write(`Skill preview (first 5 lines + headings):
`);
    const previewLines = skillBody.split("\n").slice(0, 5);
    process.stdout.write(`${previewLines.join("\n")}
`);
    process.stdout.write(`...
`);
    for (const heading of REQUIRED_PHASE_HEADINGS) {
      process.stdout.write(`  - ${heading}
`);
    }
    process.stdout.write(`
Detected tools:
${detectedSummary}
`);
    process.stdout.write(`
No files were written.
`);
    return 0;
  }
  mkdirSync(join2(skillFile, ".."), { recursive: true });
  mkdirSync(join2(commandFile, ".."), { recursive: true });
  try {
    writeFileSync(skillFile, skillBody, "utf8");
    writeFileSync(commandFile, commandBody, "utf8");
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    process.stderr.write(`llm-inspector onboard: failed to write files: ${msg}
`);
    return 1;
  }
  const firstTool = detectFirst();
  const toolHint = firstTool !== null ? firstTool.displayName : "no known tool detected";
  process.stdout.write(`Installed skill to:   ${skillFile}
`);
  process.stdout.write(`Installed command to: ${commandFile}
`);
  process.stdout.write(`
Next steps:
`);
  process.stdout.write(`  - Open Claude Code and run: /llm-inspector:onboard
`);
  process.stdout.write(`  - Or refresh later: llm-inspector onboard --force
`);
  process.stdout.write(`  - Detected primary tool: ${toolHint}
`);
  return 0;
}
var __filename, __dirname, DEFAULT_PORT, SKILL_DIR_NAME, SKILL_FILE_NAME, COMMAND_FILE_NAME;
var init_onboard = __esm({
  "src/cli/onboard.ts"() {
    "use strict";
    init_detect_tools();
    init_command_onboard();
    init_skill_onboard();
    __filename = fileURLToPath(import.meta.url);
    __dirname = dirname(__filename);
    DEFAULT_PORT = 25947;
    SKILL_DIR_NAME = "llm-inspector-onboard";
    SKILL_FILE_NAME = "SKILL.md";
    COMMAND_FILE_NAME = process.platform === "win32" ? "llm-inspector-onboard.md" : "llm-inspector:onboard.md";
  }
});

// src/cli.ts
import { spawn, execSync } from "node:child_process";
import { fileURLToPath as fileURLToPath2 } from "node:url";
import { dirname as dirname2, join as join3 } from "node:path";
var __filename2 = fileURLToPath2(import.meta.url);
var __dirname2 = dirname2(__filename2);
var DEFAULT_PORT2 = 25947;
var subcommand = process.argv[2];
if (subcommand === "onboard") {
  const { runOnboard: runOnboard2 } = await Promise.resolve().then(() => (init_onboard(), onboard_exports));
  const code = await runOnboard2(process.argv.slice(3));
  process.exit(code);
}
runStart(process.argv.slice(2));
function runStart(args) {
  const envPort = process.env["PORT"];
  const portDefault = envPort !== void 0 ? Number(envPort) : DEFAULT_PORT2;
  let port = portDefault;
  let open = true;
  let configDir;
  let providersJson;
  for (let i = 0; i < args.length; i++) {
    const arg = args[i] ?? "";
    switch (arg) {
      case "--port":
      case "-p":
        port = Number(args[i + 1]);
        i++;
        break;
      case "--no-open":
        open = false;
        break;
      case "--open":
        open = true;
        break;
      case "--config-dir":
        configDir = args[i + 1];
        i++;
        break;
      case "--providers":
        providersJson = args[i + 1];
        i++;
        break;
      default:
        break;
    }
  }
  function killProcessOnPort(targetPort) {
    const platform = process.platform;
    try {
      let pids = [];
      if (platform === "win32") {
        const output = execSync(`netstat -ano | findstr :${targetPort}`, {
          encoding: "utf8",
          timeout: 5e3
        });
        const lines = output.trim().split("\n");
        for (const line of lines) {
          const parts = line.trim().split(/\s+/);
          if (parts.length >= 5) {
            const localAddress = parts[1] ?? "";
            const pidStr = parts[4] ?? "";
            if (localAddress !== "" && pidStr !== "" && localAddress.includes(`:${targetPort}`)) {
              const pid = parseInt(pidStr, 10);
              if (!isNaN(pid) && pid > 0) {
                pids.push(pid);
              }
            }
          }
        }
        pids = [...new Set(pids)];
        for (const pid of pids) {
          try {
            console.log(`Killing process ${pid} on port ${port}...`);
            execSync(`taskkill /PID ${pid} /F`, { encoding: "utf8", timeout: 5e3 });
          } catch {
          }
        }
      } else {
        const output = execSync(`lsof -ti:${targetPort}`, { encoding: "utf8", timeout: 5e3 });
        const lines = output.trim().split("\n");
        for (const line of lines) {
          const pid = parseInt(line.trim(), 10);
          if (!isNaN(pid) && pid > 0) {
            pids.push(pid);
          }
        }
        pids = [...new Set(pids)];
        for (const pid of pids) {
          try {
            console.log(`Killing process ${pid} on port ${port}...`);
            execSync(`kill -9 ${pid}`, { encoding: "utf8", timeout: 5e3 });
          } catch {
          }
        }
      }
    } catch {
    }
  }
  process.env["PORT"] = String(port);
  killProcessOnPort(port);
  const url = `http://localhost:${port}`;
  console.log(`Server running at ${url}`);
  console.log(`   Proxy: ${url}/proxy`);
  console.log(``);
  console.log(`Route AI coding tools through the proxy:`);
  console.log(`   Claude Code:  ANTHROPIC_BASE_URL=${url}/proxy claude`);
  console.log(`   OpenCode:     LLM_BASE_URL=${url}/proxy opencode`);
  console.log(`   MiMo Code:    OPENAI_BASE_URL=${url}/proxy mimo`);
  console.log(
    `   Direct HTTP:  curl ${url}/proxy/v1/messages -d '{"model":"...","messages":[...]}'`
  );
  console.log(``);
  console.log(`Routing environment variables:`);
  console.log(`   ROUTES            JSON map of model prefix -> upstream URL`);
  console.log(`   DEFAULT_UPSTREAM  Fallback upstream for unmatched models`);
  console.log(
    `   Example: ROUTES='{"claude-":"https://api.anthropic.com","MiniMax":"https://api.minimaxi.com/anthropic"}'`
  );
  const openBrowser = (targetUrl) => {
    let command;
    switch (process.platform) {
      case "darwin":
        command = ["open", targetUrl];
        break;
      case "linux":
        command = ["xdg-open", targetUrl];
        break;
      case "win32":
        command = ["cmd", "/c", "start", targetUrl];
        break;
      default:
        break;
    }
    if (command === void 0) return;
    const [bin, ...cmdArgs] = command;
    if (bin === void 0) return;
    spawn(bin, cmdArgs, { stdio: "ignore", detached: true });
  };
  if (open) {
    openBrowser(url);
  }
  const outputDir = __dirname2;
  const serverPath = join3(outputDir, "../.output/server/index.mjs");
  const serverEnv = { ...process.env };
  if (configDir !== void 0) {
    let resolvedPath = join3(configDir, "config.json");
    if (resolvedPath.startsWith("\\c\\")) {
      resolvedPath = "C:" + resolvedPath;
    }
    serverEnv["LLM_INSPECTOR_CONFIG_PATH"] = resolvedPath;
  }
  if (providersJson !== void 0) {
    serverEnv["LLM_INSPECTOR_PROVIDERS_JSON"] = providersJson;
  }
  const serverProcess = spawn(process.execPath, [serverPath], {
    stdio: ["ignore", "inherit", "inherit"],
    detached: true,
    env: serverEnv
  });
  serverProcess.unref();
}
