import * as crypto from 'crypto';
import * as fs from 'fs';
import { existsSync } from 'fs';
import { homedir } from 'os';
import * as path from 'path';

class TurnBuilder {
  current = null;
  messages = [];
  /** Messages flushed so far (excludes the still-open run). */
  completed() {
    return this.messages;
  }
  flush() {
    if (this.current && this.current.parts.length > 0) {
      this.messages.push({
        id: `codex-${this.messages.length}`,
        parts: this.current.parts,
        role: this.current.role,
        timestamp: this.current.timestamp
      });
    }
    this.current = null;
  }
  push(role, part, timestamp) {
    const category = role === "user" ? "user" : part.type === "tool_result" ? "system" : "assistant";
    const messageRole = category === "system" ? "system" : role;
    if (this.current?.category !== category) {
      this.flush();
      this.current = { category, parts: [], role: messageRole, timestamp };
    }
    this.current.parts.push(part);
  }
  result() {
    this.flush();
    return this.messages;
  }
}
function parseCodexMeta(line) {
  try {
    const entry = JSON.parse(line);
    if (!isRecord$3(entry) || entry.type !== "session_meta" || !isRecord$3(entry.payload)) {
      return null;
    }
    const p = entry.payload;
    if (!str(p, "id") || !str(p, "cwd")) {
      return null;
    }
    return {
      cliVersion: str(p, "cli_version"),
      cwd: str(p, "cwd"),
      id: str(p, "id"),
      model: str(p, "model") || str(p, "model_provider"),
      startedAt: str(p, "timestamp") || str(entry, "timestamp")
    };
  } catch {
    return null;
  }
}
function parseCodexRollout(text) {
  const builder = new TurnBuilder();
  let meta = null;
  for (const line of text.split("\n")) {
    const trimmed = line.trim();
    if (!trimmed) {
      continue;
    }
    let entry;
    try {
      entry = JSON.parse(trimmed);
    } catch {
      continue;
    }
    if (!isRecord$3(entry)) {
      continue;
    }
    const ts = str(entry, "timestamp");
    if (entry.type === "session_meta") {
      meta = parseCodexMeta(trimmed);
      continue;
    }
    if (entry.type !== "response_item" || !isRecord$3(entry.payload)) {
      continue;
    }
    const mapped = responseItemToPart(entry.payload);
    if (mapped) {
      builder.push(mapped.role, mapped.part, ts);
    }
  }
  return { messages: builder.result(), meta };
}
function isRecord$3(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function joinMessageText(content) {
  if (!Array.isArray(content)) {
    return typeof content === "string" ? content : "";
  }
  return content.filter((c) => isRecord$3(c)).filter((c) => c.type === "input_text" || c.type === "output_text" || c.type === "text").map((c) => str(c, "text")).join("\n").trim();
}
function parseToolInput(raw) {
  if (isRecord$3(raw)) {
    return raw;
  }
  if (typeof raw === "string") {
    try {
      const parsed = JSON.parse(raw);
      return isRecord$3(parsed) ? parsed : { raw };
    } catch {
      return { raw };
    }
  }
  return {};
}
function reasoningText(payload) {
  const summary = payload.summary;
  if (Array.isArray(summary) && summary.length > 0) {
    const text = summary.map((s) => typeof s === "string" ? s : isRecord$3(s) ? str(s, "text") : "").join("\n").trim();
    if (text) {
      return text;
    }
  }
  return typeof payload.content === "string" ? payload.content.trim() : "";
}
function responseItemToPart(p) {
  switch (p.type) {
    case "custom_tool_call":
    case "function_call": {
      const args = p.type === "function_call" ? p.arguments : p.input;
      return {
        part: {
          id: str(p, "call_id"),
          input: parseToolInput(args),
          toolName: str(p, "name") || "tool",
          type: "tool_use"
        },
        role: "assistant"
      };
    }
    case "custom_tool_call_output":
    case "function_call_output":
    case "tool_search_output": {
      const output = typeof p.output === "string" ? p.output : JSON.stringify(p.output ?? "");
      return {
        part: {
          isError: /exit code:\s*[1-9]/i.test(output),
          output: output.slice(0, 2e3),
          toolUseId: str(p, "call_id"),
          type: "tool_result"
        },
        role: "assistant"
      };
    }
    case "message": {
      if (p.role === "developer") {
        return null;
      }
      const content = joinMessageText(p.content);
      return content ? { part: { content, type: "text" }, role: p.role === "user" ? "user" : "assistant" } : null;
    }
    case "reasoning": {
      const think = reasoningText(p);
      return think ? { part: { content: think, type: "thinking" }, role: "assistant" } : null;
    }
    case "tool_search_call":
    case "web_search_call":
      return {
        part: {
          id: str(p, "call_id"),
          input: parseToolInput(p.action ?? p.query),
          toolName: str(p, "type"),
          type: "tool_use"
        },
        role: "assistant"
      };
    default:
      return null;
  }
}
function str(obj, key) {
  const v = obj[key];
  return typeof v === "string" ? v : "";
}
const LIST_PREFIX_BYTES = 256 * 1024;
const MAX_FULL_READ_BYTES$2 = 16 * 1024 * 1024;
const APPROX_BYTES_PER_MESSAGE = 3e3;
const SYNTHETIC_PROMPT_PREFIXES = ["<environment_context>", "<user_instructions>", "<permissions"];
function detectActiveCodexSessions(thresholdMs) {
  const cutoff = Date.now() - thresholdMs;
  const out = [];
  for (const filePath of collectRolloutFiles()) {
    try {
      const stat = fs.statSync(filePath);
      if (stat.mtimeMs < cutoff) {
        continue;
      }
      const meta = parseCodexMeta(readPrefix$3(filePath).split("\n")[0] ?? "");
      if (meta) {
        out.push({ cwd: meta.cwd, id: meta.id, startedAt: stat.birthtimeMs });
      }
    } catch {
    }
  }
  return out;
}
function findCodexRolloutById(sessionId) {
  if (!/^[0-9a-f-]+$/i.test(sessionId)) {
    return null;
  }
  const suffix = `-${sessionId}.jsonl`;
  return collectRolloutFiles().find((p) => path.basename(p).endsWith(suffix)) ?? null;
}
function findCodexRolloutForCwd(cwd, sinceMs) {
  let best = null;
  for (const filePath of collectRolloutFiles()) {
    try {
      const stat = fs.statSync(filePath);
      if (stat.birthtimeMs <= sinceMs) {
        continue;
      }
      const meta = parseCodexMeta(readPrefix$3(filePath).split("\n")[0] ?? "");
      if (meta?.cwd === cwd && (!best || stat.birthtimeMs > best.birthtime)) {
        best = { birthtime: stat.birthtimeMs, path: filePath };
      }
    } catch {
    }
  }
  return best?.path ?? null;
}
function getCodexConversation(sessionId, offset = 0, limit = 200) {
  const filePath = findCodexRolloutById(sessionId);
  if (!filePath || !fs.existsSync(filePath)) {
    return [];
  }
  try {
    const { messages } = parseCodexRollout(readBoundedRolloutText(filePath));
    if (offset === 0 && messages.length > limit) {
      let startIdx = messages.length - limit;
      while (startIdx > 0 && messages[startIdx].role !== "user") {
        startIdx--;
      }
      return messages.slice(startIdx);
    }
    return messages.slice(offset, offset + limit);
  } catch (error) {
    console.error("[codex] Failed to read conversation:", error);
    return [];
  }
}
function listCodexProjects() {
  const files = collectRolloutFiles();
  const byCwd = /* @__PURE__ */ new Map();
  for (const filePath of files) {
    let stat;
    try {
      stat = fs.statSync(filePath);
    } catch {
      continue;
    }
    let prefix;
    try {
      prefix = readPrefix$3(filePath);
    } catch {
      continue;
    }
    const nlIdx = prefix.indexOf("\n");
    const firstLine = nlIdx === -1 ? prefix : prefix.slice(0, nlIdx);
    const meta = parseCodexMeta(firstLine);
    if (!meta) {
      continue;
    }
    const session = {
      created: meta.startedAt || stat.birthtime.toISOString(),
      gitBranch: "",
      id: meta.id,
      messageCount: Math.max(1, Math.round(stat.size / APPROX_BYTES_PER_MESSAGE)),
      modified: stat.mtime.toISOString(),
      projectPath: meta.cwd,
      source: "codex",
      summary: "",
      title: cleanTitle$2(firstUserPrompt(prefix))
    };
    const bucket = byCwd.get(meta.cwd);
    if (bucket) {
      bucket.push(session);
    } else {
      byCwd.set(meta.cwd, [session]);
    }
  }
  const projects = [];
  for (const [cwd, sessions] of byCwd) {
    sessions.sort((a, b) => new Date(b.modified).getTime() - new Date(a.modified).getTime());
    const segments = cwd.split("/").filter(Boolean);
    projects.push({
      fullPath: cwd,
      id: shortHash$5(cwd),
      lastModified: sessions[0]?.modified ?? "",
      name: segments.slice(-2).join("/"),
      sessionCount: sessions.length,
      sessions
    });
  }
  return projects.sort(
    (a, b) => new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime()
  );
}
function readBoundedRolloutText(filePath) {
  const stat = fs.statSync(filePath);
  if (stat.size <= MAX_FULL_READ_BYTES$2) {
    return fs.readFileSync(filePath, "utf-8");
  }
  const head = readPrefix$3(filePath).split("\n")[0] ?? "";
  const fd = fs.openSync(filePath, "r");
  try {
    const start = stat.size - MAX_FULL_READ_BYTES$2;
    const buf = Buffer.alloc(MAX_FULL_READ_BYTES$2);
    const bytesRead = fs.readSync(fd, buf, 0, MAX_FULL_READ_BYTES$2, start);
    const tail = buf.toString("utf-8", 0, bytesRead);
    return `${head}
${tail.slice(tail.indexOf("\n") + 1)}`;
  } finally {
    fs.closeSync(fd);
  }
}
function cleanTitle$2(prompt) {
  const firstLine = prompt.replace(/\s+/g, " ").trim().split("\n")[0]?.trim() ?? "";
  if (!firstLine) {
    return "Untitled Session";
  }
  return firstLine.length > 80 ? `${firstLine.slice(0, 77)}...` : firstLine;
}
function codexSessionsDirs() {
  const home = homedir();
  return [path.join(home, ".codex", "sessions"), path.join(home, ".codex", "archived_sessions")];
}
function collectRolloutFiles() {
  const out = [];
  const walk = (dir) => {
    let entries;
    try {
      entries = fs.readdirSync(dir, { withFileTypes: true });
    } catch {
      return;
    }
    for (const entry of entries) {
      const full = path.join(dir, entry.name);
      if (entry.isDirectory()) {
        walk(full);
      } else if (entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl")) {
        out.push(full);
      }
    }
  };
  for (const root of codexSessionsDirs()) {
    walk(root);
  }
  return out;
}
function firstUserPrompt(prefixText) {
  for (const line of prefixText.split("\n")) {
    const trimmed = line.trim();
    if (!trimmed || !trimmed.includes('"type":"message"') || !trimmed.includes('"role":"user"')) {
      continue;
    }
    try {
      const entry = JSON.parse(trimmed);
      const text = (entry.payload?.content ?? []).filter((c) => c.type === "input_text" && typeof c.text === "string").map((c) => c.text ?? "").join("\n").trim();
      if (text && !SYNTHETIC_PROMPT_PREFIXES.some((p) => text.startsWith(p))) {
        return text;
      }
    } catch {
      continue;
    }
  }
  return "";
}
function readPrefix$3(filePath) {
  const fd = fs.openSync(filePath, "r");
  try {
    const buf = Buffer.alloc(LIST_PREFIX_BYTES);
    const bytesRead = fs.readSync(fd, buf, 0, LIST_PREFIX_BYTES, 0);
    const text = buf.toString("utf-8", 0, bytesRead);
    const lastNl = text.lastIndexOf("\n");
    return lastNl === -1 ? text : text.slice(0, lastNl);
  } finally {
    fs.closeSync(fd);
  }
}
function shortHash$5(input) {
  return crypto.createHash("sha256").update(input).digest("hex").slice(0, 8);
}
const AMP_THREADS = path.join(homedir(), ".local", "share", "amp", "threads");
const MAX_FILE_BYTES = 64 * 1024 * 1024;
const THREAD_FILE_RE = /^T-(.+)\.json$/;
const SESSION_ID_RE$1 = /^[A-Za-z0-9_.-]+$/;
function detectActiveAmpSessions(thresholdMs) {
  const cutoff = Date.now() - thresholdMs;
  const out = [];
  for (const filePath of collectThreadFiles()) {
    try {
      const stat = fs.statSync(filePath);
      if (stat.mtimeMs < cutoff) {
        continue;
      }
      const doc = readThreadDoc(filePath);
      if (!doc) {
        continue;
      }
      const id = threadId(filePath, doc);
      const cwd = projectCwd(doc);
      if (id && cwd) {
        out.push({ cwd, id, startedAt: stat.birthtimeMs });
      }
    } catch {
    }
  }
  return out;
}
function getAmpConversation(sessionId, offset = 0, limit = 200) {
  if (!SESSION_ID_RE$1.test(sessionId)) {
    return [];
  }
  const filePath = path.join(AMP_THREADS, `T-${sessionId}.json`);
  if (!fs.existsSync(filePath)) {
    return [];
  }
  try {
    const doc = readThreadDoc(filePath);
    if (!doc) {
      return [];
    }
    const rawMessages = Array.isArray(doc.messages) ? doc.messages : [];
    const messages = [];
    let idx = 0;
    for (const raw of rawMessages) {
      const msg = ampMessageToConversationMessage(raw, idx);
      if (msg) {
        messages.push(msg);
        idx++;
      }
    }
    if (offset === 0 && messages.length > limit) {
      let startIdx = messages.length - limit;
      while (startIdx > 0 && messages[startIdx]?.role !== "user") {
        startIdx--;
      }
      return messages.slice(startIdx);
    }
    return messages.slice(offset, offset + limit);
  } catch (err) {
    console.error("[amp] Failed to read conversation:", err);
    return [];
  }
}
function listAmpProjects() {
  const byCwd = /* @__PURE__ */ new Map();
  for (const filePath of collectThreadFiles()) {
    let stat;
    try {
      stat = fs.statSync(filePath);
    } catch {
      continue;
    }
    const doc = readThreadDoc(filePath);
    if (!doc) {
      continue;
    }
    const id = threadId(filePath, doc);
    if (!id) {
      continue;
    }
    const cwd = projectCwd(doc) || id;
    const modified = lastModified(doc, stat);
    const created = typeof doc.created === "string" && doc.created ? doc.created : stat.birthtime.toISOString();
    const rawMessages = Array.isArray(doc.messages) ? doc.messages : [];
    const session = {
      created,
      gitBranch: "",
      id,
      messageCount: rawMessages.length,
      modified,
      projectPath: cwd,
      source: "amp",
      summary: "",
      title: cleanTitle$1(typeof doc.title === "string" ? doc.title : "")
    };
    const bucket = byCwd.get(cwd);
    if (bucket) {
      bucket.push(session);
    } else {
      byCwd.set(cwd, [session]);
    }
  }
  const projects = [];
  for (const [cwd, sessions] of byCwd) {
    sessions.sort((a, b) => new Date(b.modified).getTime() - new Date(a.modified).getTime());
    const segments = cwd.split("/").filter(Boolean);
    projects.push({
      fullPath: cwd,
      id: shortHash$4(cwd),
      lastModified: sessions[0]?.modified ?? "",
      name: segments.slice(-2).join("/") || cwd,
      sessionCount: sessions.length,
      sessions
    });
  }
  return projects.sort(
    (a, b) => new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime()
  );
}
function resolveAmpSessionFile(sessionId) {
  if (!SESSION_ID_RE$1.test(sessionId)) {
    return null;
  }
  const filePath = path.join(AMP_THREADS, `T-${sessionId}.json`);
  return fs.existsSync(filePath) ? filePath : null;
}
function ampBlockToPart(block) {
  switch (block.type) {
    case "text":
      return { content: typeof block.text === "string" ? block.text : "", type: "text" };
    case "thinking":
      return {
        content: typeof block.thinking === "string" ? block.thinking : "",
        type: "thinking"
      };
    case "tool_result": {
      const output = extractToolResultText(block.content);
      return {
        isError: typeof block.is_error === "boolean" ? block.is_error : false,
        output: output.slice(0, 2e3),
        toolUseId: typeof block.tool_use_id === "string" ? block.tool_use_id : "",
        type: "tool_result"
      };
    }
    case "tool_use":
      return {
        id: typeof block.id === "string" ? block.id : "",
        input: isRecord$2(block.input) ? block.input : {},
        toolName: typeof block.name === "string" ? block.name : "tool",
        type: "tool_use"
      };
    default:
      return null;
  }
}
function ampMessageToConversationMessage(raw, index) {
  if (!isRecord$2(raw)) {
    return null;
  }
  const role = raw.role;
  if (role !== "user" && role !== "assistant") {
    return null;
  }
  const parts = contentToParts(raw.content);
  if (parts.length === 0) {
    return null;
  }
  const msgRole = role === "user" ? "user" : "assistant";
  return {
    id: `amp-${msgRole}-${index}`,
    parts,
    role: msgRole,
    timestamp: ""
  };
}
function cleanTitle$1(raw) {
  const first = raw.replace(/\s+/g, " ").trim().split("\n")[0]?.trim() ?? "";
  if (!first) {
    return "Untitled Session";
  }
  return first.length > 80 ? `${first.slice(0, 77)}...` : first;
}
function collectThreadFiles() {
  let entries;
  try {
    entries = fs.readdirSync(AMP_THREADS, { withFileTypes: true });
  } catch {
    return [];
  }
  const files = [];
  for (const entry of entries) {
    if (!entry.isFile() || !THREAD_FILE_RE.test(entry.name)) {
      continue;
    }
    const full = path.join(AMP_THREADS, entry.name);
    try {
      const stat = fs.statSync(full);
      files.push({ mtime: stat.mtimeMs, path: full });
    } catch {
    }
  }
  files.sort((a, b) => b.mtime - a.mtime);
  return files.map((f) => f.path);
}
function contentToParts(content) {
  if (typeof content === "string" && content) {
    return [{ content, type: "text" }];
  }
  if (!Array.isArray(content)) {
    return [];
  }
  const parts = [];
  for (const item of content) {
    if (!isRecord$2(item)) {
      continue;
    }
    const part = ampBlockToPart(item);
    if (part) {
      parts.push(part);
    }
  }
  return parts;
}
function extractToolResultText(content) {
  if (typeof content === "string") {
    return content;
  }
  if (!Array.isArray(content)) {
    return "";
  }
  return content.filter((c) => isRecord$2(c) && c.type === "text").map((c) => typeof c.text === "string" ? c.text : "").join("\n");
}
function isRecord$2(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function lastModified(doc, stat) {
  if (isRecord$2(doc.meta)) {
    const traces = doc.meta.traces;
    if (Array.isArray(traces) && traces.length > 0) {
      const last = traces[traces.length - 1];
      if (isRecord$2(last)) {
        const et = last.endTime;
        if (typeof et === "string" && et) {
          return et;
        }
        if (typeof et === "number" && et > 0) {
          return new Date(et).toISOString();
        }
      }
    }
  }
  return stat.mtime.toISOString();
}
function projectCwd(doc) {
  if (isRecord$2(doc.env) && isRecord$2(doc.env.initial)) {
    const trees = doc.env.initial.trees;
    if (Array.isArray(trees) && trees.length > 0 && isRecord$2(trees[0])) {
      const dn = trees[0].displayName;
      if (typeof dn === "string" && dn) {
        return dn;
      }
    }
  }
  return "";
}
function readThreadDoc(filePath) {
  try {
    if (fs.statSync(filePath).size > MAX_FILE_BYTES) {
      return null;
    }
    const parsed = JSON.parse(fs.readFileSync(filePath, "utf-8"));
    return isRecord$2(parsed) ? parsed : null;
  } catch {
    return null;
  }
}
function shortHash$4(input) {
  return crypto.createHash("sha256").update(input).digest("hex").slice(0, 8);
}
function threadId(filePath, doc) {
  const m = THREAD_FILE_RE.exec(path.basename(filePath));
  if (m?.[1]) {
    return m[1];
  }
  if (typeof doc.id === "string" && doc.id) {
    return doc.id;
  }
  return "";
}
const PREFIX_BYTES$2 = 64 * 1024;
const MAX_FULL_READ_BYTES$1 = 16 * 1024 * 1024;
const COPILOT_SESSION_STATE = path.join(homedir(), ".copilot", "session-state");
const SESSION_ID_RE = /^[A-Za-z0-9_.-]+$/;
function detectActiveCopilotSessions(thresholdMs) {
  const cutoff = Date.now() - thresholdMs;
  const out = [];
  for (const filePath of collectCopilotFiles()) {
    try {
      const stat = fs.statSync(filePath);
      if (stat.mtimeMs < cutoff) {
        continue;
      }
      const meta = readMeta$1(readPrefix$2(filePath), filePath);
      if (meta) {
        out.push({ cwd: meta.cwd, id: meta.id, startedAt: stat.birthtimeMs });
      }
    } catch {
    }
  }
  return out;
}
function getCopilotConversation(sessionId, offset = 0, limit = 200) {
  if (!SESSION_ID_RE.test(sessionId)) {
    return [];
  }
  const filePath = resolveCopilotSessionFile(sessionId);
  if (!filePath) {
    return [];
  }
  try {
    const text = readBounded$1(filePath);
    const messages = parseCopilotText(text);
    if (offset === 0 && messages.length > limit) {
      let startIdx = messages.length - limit;
      while (startIdx > 0 && messages[startIdx]?.role !== "user") {
        startIdx--;
      }
      return messages.slice(startIdx);
    }
    return messages.slice(offset, offset + limit);
  } catch (error) {
    console.error("[copilot] Failed to read conversation:", error);
    return [];
  }
}
function listCopilotProjects() {
  const byCwd = /* @__PURE__ */ new Map();
  for (const filePath of collectCopilotFiles()) {
    let stat;
    try {
      stat = fs.statSync(filePath);
    } catch {
      continue;
    }
    const prefix = safeReadPrefix(filePath);
    if (!prefix) {
      continue;
    }
    const meta = readMeta$1(prefix, filePath);
    if (!meta) {
      continue;
    }
    const session = {
      created: stat.birthtime.toISOString(),
      gitBranch: meta.gitBranch,
      id: meta.id,
      messageCount: 0,
      modified: stat.mtime.toISOString(),
      projectPath: meta.cwd,
      source: "copilot",
      summary: "",
      title: meta.title || "Untitled Session"
    };
    const bucket = byCwd.get(meta.cwd);
    if (bucket) {
      bucket.push(session);
    } else {
      byCwd.set(meta.cwd, [session]);
    }
  }
  const projects = [];
  for (const [cwd, sessions] of byCwd) {
    sessions.sort((a, b) => new Date(b.modified).getTime() - new Date(a.modified).getTime());
    const segments = cwd.split("/").filter(Boolean);
    projects.push({
      fullPath: cwd,
      id: shortHash$3(cwd),
      lastModified: sessions[0]?.modified ?? "",
      name: segments.slice(-2).join("/"),
      sessionCount: sessions.length,
      sessions
    });
  }
  return projects.sort(
    (a, b) => new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime()
  );
}
function resolveCopilotSessionFile(sessionId) {
  if (!SESSION_ID_RE.test(sessionId)) {
    return null;
  }
  for (const filePath of collectCopilotFiles()) {
    if (sessionIdFromFilePath(filePath) === sessionId) {
      return filePath;
    }
  }
  return null;
}
function collectCopilotFiles() {
  const out = [];
  let entries;
  try {
    entries = fs.readdirSync(COPILOT_SESSION_STATE, { withFileTypes: true });
  } catch {
    return out;
  }
  for (const entry of entries) {
    const full = path.join(COPILOT_SESSION_STATE, entry.name);
    if (entry.isFile() && entry.name.endsWith(".jsonl")) {
      out.push(full);
    } else if (entry.isDirectory()) {
      const eventsPath = path.join(full, "events.jsonl");
      try {
        fs.statSync(eventsPath);
        out.push(eventsPath);
      } catch {
      }
    }
  }
  return out;
}
function copilotEventToMessage(entry, pendingToolUseId) {
  const type = typeof entry.type === "string" ? entry.type : "";
  const ts = typeof entry.timestamp === "string" ? entry.timestamp : "";
  const data = isRecord$1(entry.data) ? entry.data : entry;
  if (type === "user.message") {
    const content = typeof data.content === "string" ? data.content : "";
    if (!content) {
      return null;
    }
    const id = typeof data.id === "string" ? data.id : `copilot-user-${ts}`;
    return {
      id,
      parts: [{ content, type: "text" }],
      role: "user",
      timestamp: ts
    };
  }
  if (type === "assistant.reasoning") {
    const text = typeof data.text === "string" ? data.text : "";
    if (!text) {
      return null;
    }
    const id = typeof data.id === "string" ? data.id : `copilot-reasoning-${ts}`;
    return {
      id,
      parts: [{ content: text, type: "thinking" }],
      role: "assistant",
      timestamp: ts
    };
  }
  if (type === "assistant.message") {
    const content = typeof data.content === "string" ? data.content : "";
    const parts = [];
    const reasoningText2 = typeof data.reasoningText === "string" ? data.reasoningText : "";
    if (reasoningText2) {
      parts.push({ content: reasoningText2, type: "thinking" });
    }
    if (content) {
      parts.push({ content, type: "text" });
    }
    if (Array.isArray(data.toolRequests)) {
      for (const req of data.toolRequests) {
        if (!isRecord$1(req)) {
          continue;
        }
        const toolId = typeof req.toolCallId === "string" ? req.toolCallId : `copilot-tool-${ts}`;
        pendingToolUseId.value = toolId;
        let input = {};
        if (isRecord$1(req.arguments)) {
          input = req.arguments;
        } else if (typeof req.arguments === "string") {
          try {
            const parsed = JSON.parse(req.arguments);
            if (isRecord$1(parsed)) {
              input = parsed;
            }
          } catch {
          }
        }
        parts.push({
          id: toolId,
          input,
          toolName: typeof req.name === "string" ? req.name : "tool",
          type: "tool_use"
        });
      }
    }
    if (parts.length === 0) {
      return null;
    }
    const id = typeof data.id === "string" ? data.id : `copilot-assistant-${ts}`;
    return {
      id,
      parts,
      role: "assistant",
      timestamp: ts
    };
  }
  if (type === "tool.execution_complete") {
    const rawResult = data.result;
    const result = typeof rawResult === "string" ? rawResult : JSON.stringify(rawResult ?? "");
    const isError = data.isError === true || data.success === false;
    const toolCallId = typeof data.toolCallId === "string" ? data.toolCallId : pendingToolUseId.value;
    const toolUseId = toolCallId || pendingToolUseId.value || "unknown";
    const id = typeof data.id === "string" ? data.id : `copilot-tool-result-${ts}`;
    return {
      id,
      parts: [
        {
          isError,
          output: result.slice(0, 2e3),
          toolUseId,
          type: "tool_result"
        }
      ],
      role: "system",
      timestamp: ts
    };
  }
  return null;
}
function isRecord$1(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function parseCopilotText(text) {
  const messages = [];
  const pendingToolUseId = { value: "" };
  for (const line of text.split("\n")) {
    const trimmed = line.trim();
    if (!trimmed) {
      continue;
    }
    try {
      const entry = JSON.parse(trimmed);
      const msg = copilotEventToMessage(entry, pendingToolUseId);
      if (msg) {
        messages.push(msg);
        if (msg.parts[0]?.type === "tool_result") {
          pendingToolUseId.value = "";
        }
      }
    } catch {
    }
  }
  return messages;
}
function readBounded$1(filePath) {
  const stat = fs.statSync(filePath);
  if (stat.size <= MAX_FULL_READ_BYTES$1) {
    return fs.readFileSync(filePath, "utf-8");
  }
  const head = readPrefix$2(filePath).split("\n")[0] ?? "";
  const fd = fs.openSync(filePath, "r");
  try {
    const start = stat.size - MAX_FULL_READ_BYTES$1;
    const buf = Buffer.alloc(MAX_FULL_READ_BYTES$1);
    const bytesRead = fs.readSync(fd, buf, 0, MAX_FULL_READ_BYTES$1, start);
    const tail = buf.toString("utf-8", 0, bytesRead);
    return `${head}
${tail.slice(tail.indexOf("\n") + 1)}`;
  } finally {
    fs.closeSync(fd);
  }
}
function readMeta$1(prefix, filePath) {
  let cwd = "";
  let gitBranch = "";
  let title = "";
  const id = sessionIdFromFilePath(filePath);
  for (const line of prefix.split("\n")) {
    const trimmed = line.trim();
    if (!trimmed) {
      continue;
    }
    let entry;
    try {
      entry = JSON.parse(trimmed);
    } catch {
      continue;
    }
    const type = typeof entry.type === "string" ? entry.type : "";
    const data = isRecord$1(entry.data) ? entry.data : entry;
    if (type === "session.start") {
      const context = isRecord$1(data.context) ? data.context : data;
      if (!cwd && typeof context.cwd === "string") {
        cwd = context.cwd;
      }
      if (!gitBranch && typeof context.branch === "string") {
        gitBranch = context.branch;
      }
    }
    if (!title && type === "user.message" && typeof data.content === "string") {
      title = data.content.split("\n")[0]?.slice(0, 80) ?? "";
    }
    if (cwd && title) {
      break;
    }
  }
  return cwd ? { cwd, gitBranch, id, title } : null;
}
function readPrefix$2(filePath) {
  const fd = fs.openSync(filePath, "r");
  try {
    const buf = Buffer.alloc(PREFIX_BYTES$2);
    const n = fs.readSync(fd, buf, 0, PREFIX_BYTES$2, 0);
    const text = buf.toString("utf-8", 0, n);
    const lastNl = text.lastIndexOf("\n");
    return lastNl === -1 ? text : text.slice(0, lastNl);
  } finally {
    fs.closeSync(fd);
  }
}
function safeReadPrefix(filePath) {
  try {
    return readPrefix$2(filePath);
  } catch {
    return "";
  }
}
function sessionIdFromFilePath(filePath) {
  const base = path.basename(filePath);
  if (base === "events.jsonl") {
    return path.basename(path.dirname(filePath));
  }
  return base.replace(/\.jsonl$/, "");
}
function shortHash$3(input) {
  return crypto.createHash("sha256").update(input).digest("hex").slice(0, 8);
}
const CURSOR_PROJECTS = path.join(homedir(), ".cursor", "projects");
const PREFIX_BYTES$1 = 64 * 1024;
const MAX_FULL_READ_BYTES = 16 * 1024 * 1024;
function detectActiveCursorSessions(thresholdMs) {
  const cutoff = Date.now() - thresholdMs;
  const out = [];
  for (const { encodedDir, filePath } of collectTranscriptFiles()) {
    try {
      const stat = fs.statSync(filePath);
      if (stat.mtimeMs < cutoff) {
        continue;
      }
      const id = transcriptId(filePath);
      if (!id) {
        continue;
      }
      out.push({
        cwd: decodeCursorProjectDir(encodedDir),
        id,
        startedAt: stat.birthtimeMs
      });
    } catch {
    }
  }
  return out;
}
function getCursorConversation(sessionId, offset = 0, limit = 200) {
  if (!/^[A-Za-z0-9_.-]+$/.test(sessionId)) {
    return [];
  }
  const found = collectTranscriptFiles().find((e) => transcriptId(e.filePath) === sessionId);
  if (!found) {
    return [];
  }
  try {
    const messages = parseTranscriptFile(found.filePath);
    if (offset === 0 && messages.length > limit) {
      let startIdx = messages.length - limit;
      while (startIdx > 0 && messages[startIdx]?.role !== "user") {
        startIdx--;
      }
      return messages.slice(startIdx);
    }
    return messages.slice(offset, offset + limit);
  } catch (error) {
    console.error("[cursor] Failed to read conversation:", error);
    return [];
  }
}
function listCursorProjects() {
  const byCwd = /* @__PURE__ */ new Map();
  for (const { encodedDir, filePath } of collectTranscriptFiles()) {
    let stat;
    try {
      stat = fs.statSync(filePath);
    } catch {
      continue;
    }
    const id = transcriptId(filePath);
    if (!id) {
      continue;
    }
    const cwd = decodeCursorProjectDir(encodedDir);
    const title = extractTitle(filePath);
    const session = {
      created: stat.birthtime.toISOString(),
      gitBranch: "",
      id,
      messageCount: estimateMessageCount(filePath, stat),
      modified: stat.mtime.toISOString(),
      projectPath: cwd,
      source: "cursor",
      summary: "",
      title
    };
    const bucket = byCwd.get(cwd);
    if (bucket) {
      bucket.push(session);
    } else {
      byCwd.set(cwd, [session]);
    }
  }
  const projects = [];
  for (const [cwd, sessions] of byCwd) {
    sessions.sort((a, b) => new Date(b.modified).getTime() - new Date(a.modified).getTime());
    const segments = cwd.split("/").filter(Boolean);
    projects.push({
      fullPath: cwd,
      id: shortHash$2(cwd),
      lastModified: sessions[0]?.modified ?? "",
      name: segments.slice(-2).join("/"),
      sessionCount: sessions.length,
      sessions
    });
  }
  return projects.sort(
    (a, b) => new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime()
  );
}
function resolveCursorSessionFile(sessionId) {
  if (!/^[A-Za-z0-9_.-]+$/.test(sessionId)) {
    return null;
  }
  const found = collectTranscriptFiles().find((e) => transcriptId(e.filePath) === sessionId);
  return found ? found.filePath : null;
}
function collectTranscriptFiles() {
  const out = [];
  let projectDirs;
  try {
    projectDirs = fs.readdirSync(CURSOR_PROJECTS, { withFileTypes: true });
  } catch {
    return out;
  }
  for (const dir of projectDirs) {
    if (!dir.isDirectory()) {
      continue;
    }
    const transcriptsDir = path.join(CURSOR_PROJECTS, dir.name, "agent-transcripts");
    let entries;
    try {
      entries = fs.readdirSync(transcriptsDir, { withFileTypes: true });
    } catch {
      continue;
    }
    const jsonlStems = /* @__PURE__ */ new Set();
    for (const entry of entries) {
      if (!entry.isFile()) {
        continue;
      }
      if (entry.name.endsWith(".jsonl")) {
        jsonlStems.add(entry.name.slice(0, -6));
        out.push({ encodedDir: dir.name, filePath: path.join(transcriptsDir, entry.name) });
      }
    }
    for (const entry of entries) {
      if (!entry.isFile() || !entry.name.endsWith(".txt")) {
        continue;
      }
      const stem = entry.name.slice(0, -4);
      if (!jsonlStems.has(stem)) {
        out.push({ encodedDir: dir.name, filePath: path.join(transcriptsDir, entry.name) });
      }
    }
  }
  return out;
}
function decodeCursorProjectDir(encoded) {
  if (encoded.includes("%2F") || encoded.includes("%2f")) {
    try {
      const decoded = decodeURIComponent(encoded.replace(/%2f/gi, "/"));
      if (decoded.startsWith("/")) {
        return decoded;
      }
    } catch {
    }
  }
  if (encoded.startsWith("-")) {
    const candidate = encoded.replace(/-/g, "/");
    return candidate;
  }
  return encoded;
}
function estimateMessageCount(filePath, stat) {
  const ext = path.extname(filePath);
  const avgBytesPerLine = ext === ".txt" ? 200 : 500;
  return Math.max(1, Math.round(stat.size / avgBytesPerLine));
}
function extractTitle(filePath) {
  try {
    const prefix = readPrefix$1(filePath);
    const ext = path.extname(filePath);
    if (ext === ".jsonl") {
      return titleFromJsonl(prefix);
    }
    return titleFromTxt(prefix);
  } catch {
    return "Untitled Session";
  }
}
function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function jsonlLineToMessage(entry, idx) {
  const role = resolveRole(entry);
  if (!role) {
    return null;
  }
  const messageField = entry.message;
  if (!isRecord(messageField)) {
    return null;
  }
  const rawContent = messageField.content;
  if (rawContent === void 0 || rawContent === null) {
    return null;
  }
  const parts = [];
  if (typeof rawContent === "string") {
    if (!rawContent) {
      return null;
    }
    parts.push({ content: rawContent, type: "text" });
  } else if (Array.isArray(rawContent)) {
    for (const block of rawContent) {
      if (!isRecord(block)) {
        continue;
      }
      const blockType = strOf(block, "type");
      if (blockType === "text") {
        const text = strOf(block, "text");
        if (text) {
          parts.push({ content: text, type: "text" });
        }
      } else if (blockType === "thinking") {
        const thinking = strOf(block, "thinking");
        if (thinking) {
          parts.push({ content: thinking, type: "thinking" });
        }
      } else if (blockType === "tool_use") {
        const input = block.input;
        parts.push({
          id: strOf(block, "id"),
          input: isRecord(input) ? input : {},
          toolName: strOf(block, "name") || "Unknown",
          type: "tool_use"
        });
      } else if (blockType === "tool_result") {
        const resultContent = block.content;
        let output = "";
        if (typeof resultContent === "string") {
          output = resultContent;
        } else if (Array.isArray(resultContent)) {
          output = resultContent.filter((c) => isRecord(c) && c.type === "text").map((c) => {
            const t = c.text;
            return typeof t === "string" ? t : "";
          }).join("\n");
        }
        const isErr = block.is_error;
        parts.push({
          isError: typeof isErr === "boolean" ? isErr : false,
          output: output.slice(0, 2e3),
          toolUseId: strOf(block, "tool_use_id"),
          type: "tool_result"
        });
      }
    }
  } else {
    return null;
  }
  if (parts.length === 0) {
    return null;
  }
  const id = strOf(entry, "id") || strOf(entry, "uuid") || `cursor-${role}-${String(idx)}`;
  const timestamp = strOf(entry, "timestamp") || strOf(entry, "createdAt") || "";
  return { id, parts, role, timestamp };
}
function jsonlToMessages(text) {
  const messages = [];
  let idx = 0;
  for (const raw of text.split("\n")) {
    const trimmed = raw.trim();
    if (!trimmed) {
      continue;
    }
    try {
      const entry = JSON.parse(trimmed);
      if (!isRecord(entry)) {
        continue;
      }
      const msg = jsonlLineToMessage(entry, idx);
      if (msg) {
        messages.push(msg);
        idx++;
      }
    } catch {
    }
  }
  return messages;
}
function parseTranscriptFile(filePath) {
  const ext = path.extname(filePath);
  const text = readBounded(filePath);
  if (ext === ".jsonl") {
    return jsonlToMessages(text);
  }
  return parseTxtTranscript(text);
}
function parseTxtTranscript(text) {
  const messages = [];
  let currentRole = null;
  const currentLines = [];
  let idx = 0;
  const flush = () => {
    if (!currentRole || currentLines.length === 0) {
      return;
    }
    const content = currentLines.join("\n").trim();
    if (content) {
      messages.push({
        id: `cursor-${currentRole}-${String(idx)}`,
        parts: [{ content, type: "text" }],
        role: currentRole,
        timestamp: ""
      });
      idx++;
    }
    currentLines.length = 0;
  };
  for (const line of text.split("\n")) {
    if (line.startsWith("user:")) {
      flush();
      currentRole = "user";
      const rest = line.slice(5).trim();
      if (rest) {
        currentLines.push(rest);
      }
    } else if (line.startsWith("assistant:")) {
      flush();
      currentRole = "assistant";
      const rest = line.slice(10).trim();
      if (rest) {
        currentLines.push(rest);
      }
    } else if (currentRole) {
      currentLines.push(line);
    }
  }
  flush();
  return messages;
}
function readBounded(filePath) {
  const stat = fs.statSync(filePath);
  if (stat.size <= MAX_FULL_READ_BYTES) {
    return fs.readFileSync(filePath, "utf-8");
  }
  const fd = fs.openSync(filePath, "r");
  try {
    const start = stat.size - MAX_FULL_READ_BYTES;
    const buf = Buffer.alloc(MAX_FULL_READ_BYTES);
    const n = fs.readSync(fd, buf, 0, MAX_FULL_READ_BYTES, start);
    const tail = buf.toString("utf-8", 0, n);
    return tail.slice(tail.indexOf("\n") + 1);
  } finally {
    fs.closeSync(fd);
  }
}
function readPrefix$1(filePath) {
  const fd = fs.openSync(filePath, "r");
  try {
    const buf = Buffer.alloc(PREFIX_BYTES$1);
    const n = fs.readSync(fd, buf, 0, PREFIX_BYTES$1, 0);
    const text = buf.toString("utf-8", 0, n);
    const lastNl = text.lastIndexOf("\n");
    return lastNl === -1 ? text : text.slice(0, lastNl);
  } finally {
    fs.closeSync(fd);
  }
}
function resolveRole(entry) {
  const raw = strOf(entry, "role") || strOf(entry, "type");
  switch (raw.toLowerCase()) {
    case "assistant":
    case "bot":
    case "model":
      return "assistant";
    case "human":
    case "user":
      return "user";
    default:
      return null;
  }
}
function shortHash$2(input) {
  return crypto.createHash("sha256").update(input).digest("hex").slice(0, 8);
}
function strOf(obj, key) {
  const v = obj[key];
  return typeof v === "string" ? v : "";
}
function titleFromJsonl(prefix) {
  for (const raw of prefix.split("\n")) {
    const trimmed = raw.trim();
    if (!trimmed) {
      continue;
    }
    try {
      const entry = JSON.parse(trimmed);
      if (!isRecord(entry) || resolveRole(entry) !== "user") {
        continue;
      }
      const messageField = entry.message;
      if (!isRecord(messageField)) {
        continue;
      }
      const rawContent = messageField.content;
      let text = "";
      if (typeof rawContent === "string") {
        text = rawContent;
      } else if (Array.isArray(rawContent)) {
        for (const block of rawContent) {
          if (isRecord(block) && block.type === "text") {
            const t = block.text;
            if (typeof t === "string" && t) {
              text = t;
              break;
            }
          }
        }
      }
      if (text) {
        return truncateTitle(text);
      }
    } catch {
    }
  }
  return "Untitled Session";
}
function titleFromTxt(prefix) {
  for (const line of prefix.split("\n")) {
    if (line.startsWith("user:")) {
      const text = line.slice(5).trim();
      if (text) {
        return truncateTitle(text);
      }
    }
  }
  return "Untitled Session";
}
function transcriptId(filePath) {
  const base = path.basename(filePath);
  const stem = base.endsWith(".jsonl") ? base.slice(0, -6) : base.endsWith(".txt") ? base.slice(0, -4) : null;
  if (!stem || !/^[A-Za-z0-9_.-]+$/.test(stem)) {
    return null;
  }
  return stem;
}
function truncateTitle(text) {
  const first = text.replace(/\s+/g, " ").trim().split("\n")[0]?.trim() ?? "";
  if (!first) {
    return "Untitled Session";
  }
  return first.length > 80 ? `${first.slice(0, 77)}...` : first;
}
const MAX_GEMINI_FILE_BYTES = 64 * 1024 * 1024;
const GEMINI_TMP = path.join(homedir(), ".gemini", "tmp");
const GEMINI_PROJECTS_JSON = path.join(homedir(), ".gemini", "projects.json");
function detectActiveGeminiSessions(thresholdMs) {
  const cutoff = Date.now() - thresholdMs;
  const projectHashToCwd = buildHashToCwdMap();
  const projectDirs = collectProjectHashDirs();
  const out = [];
  for (const hashDir of projectDirs) {
    const hash = path.basename(hashDir);
    const cwd = projectHashToCwd.get(hash) ?? hash;
    const chatFiles = collectChatFiles(hashDir);
    for (const chatFile of chatFiles) {
      try {
        const stat = fs.statSync(chatFile);
        if (stat.mtimeMs < cutoff) {
          continue;
        }
        const record = readChatFile(chatFile);
        if (record) {
          out.push({
            cwd,
            id: record.sessionId,
            startedAt: new Date(record.startTime).getTime()
          });
        }
      } catch {
      }
    }
    const logsPath = path.join(hashDir, "logs.json");
    try {
      const stat = fs.statSync(logsPath);
      if (stat.mtimeMs < cutoff) {
        continue;
      }
      const entries = readLogsJson(logsPath);
      if (entries.length > 0) {
        const last = entries[entries.length - 1];
        if (last) {
          const alreadyAdded = out.some((o) => o.id === last.sessionId && o.cwd === cwd);
          if (!alreadyAdded) {
            out.push({
              cwd,
              id: last.sessionId,
              startedAt: new Date(entries[0]?.timestamp ?? last.timestamp).getTime()
            });
          }
        }
      }
    } catch {
    }
  }
  return out;
}
function getGeminiConversation(sessionId, offset = 0, limit = 200) {
  const projectDirs = collectProjectHashDirs();
  for (const hashDir of projectDirs) {
    const chatFile = findChatFileForSession(hashDir, sessionId);
    if (chatFile) {
      return conversationFromChatFile(chatFile, offset, limit);
    }
  }
  for (const hashDir of projectDirs) {
    const messages = conversationFromLogsJson(hashDir, sessionId);
    if (messages.length > 0) {
      if (offset === 0 && messages.length > limit) {
        return messages.slice(messages.length - limit);
      }
      return messages.slice(offset, offset + limit);
    }
  }
  return [];
}
function listGeminiProjects() {
  const projectHashToCwd = buildHashToCwdMap();
  const projectDirs = collectProjectHashDirs();
  const byCwd = /* @__PURE__ */ new Map();
  for (const hashDir of projectDirs) {
    const hash = path.basename(hashDir);
    const cwd = projectHashToCwd.get(hash) ?? hash;
    const chatSessions = collectChatSessions(hashDir, cwd);
    if (chatSessions.length > 0) {
      for (const session of chatSessions) {
        appendToMap(byCwd, cwd, session);
      }
      continue;
    }
    const logSessions = sessionsFromLogsJson(hashDir, cwd);
    for (const session of logSessions) {
      appendToMap(byCwd, cwd, session);
    }
  }
  const projects = [];
  for (const [cwd, sessions] of byCwd) {
    sessions.sort((a, b) => new Date(b.modified).getTime() - new Date(a.modified).getTime());
    const segments = cwd.split("/").filter(Boolean);
    const isRawHash = /^[0-9a-f]{64}$/i.test(cwd);
    projects.push({
      fullPath: cwd,
      id: shortHash$1(cwd),
      lastModified: sessions[0]?.modified ?? "",
      name: isRawHash ? `Gemini (${cwd.slice(0, 8)})` : segments.slice(-2).join("/"),
      sessionCount: sessions.length,
      sessions
    });
  }
  return projects.sort(
    (a, b) => new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime()
  );
}
function resolveGeminiSessionFile(sessionId) {
  for (const hashDir of collectProjectHashDirs()) {
    const chatFile = findChatFileForSession(hashDir, sessionId);
    if (chatFile !== null) {
      return chatFile;
    }
  }
  return null;
}
function appendToMap(map, key, value) {
  let bucket = map.get(key);
  if (!bucket) {
    bucket = [];
    map.set(key, bucket);
  }
  bucket.push(value);
}
function buildHashToCwdMap() {
  const map = /* @__PURE__ */ new Map();
  try {
    const raw = fs.readFileSync(GEMINI_PROJECTS_JSON, "utf-8");
    const data = JSON.parse(raw);
    for (const [slugOrHash, absolutePath] of Object.entries(data)) {
      map.set(slugOrHash, absolutePath);
      const computed = crypto.createHash("sha256").update(absolutePath).digest("hex");
      map.set(computed, absolutePath);
    }
  } catch {
  }
  return map;
}
function cleanTitle(text) {
  const first = text.replace(/\s+/g, " ").trim().split("\n")[0]?.trim() ?? "";
  if (!first) {
    return "Untitled Session";
  }
  return first.length > 80 ? `${first.slice(0, 77)}...` : first;
}
function collectChatFiles(hashDir) {
  const chatsDir = path.join(hashDir, "chats");
  try {
    return fs.readdirSync(chatsDir, { withFileTypes: true }).filter((e) => e.isFile() && e.name.startsWith("session-") && e.name.endsWith(".json")).map((e) => path.join(chatsDir, e.name));
  } catch {
    return [];
  }
}
function collectChatSessions(hashDir, cwd) {
  const chatFiles = collectChatFiles(hashDir);
  const sessions = [];
  for (const chatFile of chatFiles) {
    try {
      const stat = fs.statSync(chatFile);
      const record = readChatFile(chatFile);
      if (!record) {
        continue;
      }
      const userMessages = record.messages.filter((m) => m.type === "user");
      const firstUserMsg = userMessages[0];
      let title = "Untitled Session";
      if (firstUserMsg) {
        title = cleanTitle(extractTextFromContent(firstUserMsg.content));
      }
      sessions.push({
        created: record.startTime,
        gitBranch: "",
        id: record.sessionId,
        messageCount: record.messages.length,
        modified: stat.mtime.toISOString(),
        projectPath: cwd,
        source: "gemini",
        summary: record.summary ?? "",
        title
      });
    } catch {
    }
  }
  return sessions;
}
function collectProjectHashDirs() {
  try {
    return fs.readdirSync(GEMINI_TMP, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => path.join(GEMINI_TMP, e.name));
  } catch {
    return [];
  }
}
function conversationFromChatFile(chatFile, offset, limit) {
  try {
    const record = readChatFile(chatFile);
    if (!record) {
      return [];
    }
    const messages = record.messages.filter((m) => m.type === "user" || m.type === "gemini").map(messageRecordToMessage);
    if (offset === 0 && messages.length > limit) {
      let startIdx = messages.length - limit;
      while (startIdx > 0 && messages[startIdx]?.role !== "user") {
        startIdx--;
      }
      return messages.slice(startIdx);
    }
    return messages.slice(offset, offset + limit);
  } catch (err) {
    console.error("[gemini] Failed to read chat file:", err);
    return [];
  }
}
function conversationFromLogsJson(hashDir, sessionId) {
  const logsPath = path.join(hashDir, "logs.json");
  const entries = readLogsJson(logsPath);
  return entries.filter((e) => e.sessionId === sessionId).map(
    (entry) => ({
      id: `${entry.sessionId}-${String(entry.messageId)}`,
      parts: [{ content: entry.message, type: "text" }],
      role: "user",
      timestamp: entry.timestamp
    })
  );
}
function extractTextFromContent(content) {
  if (typeof content === "string") {
    return content;
  }
  return content.filter((p) => "text" in p).map((p) => p.text).join(" ");
}
function findChatFileForSession(hashDir, sessionId) {
  if (!sessionId) {
    return null;
  }
  const chatsDir = path.join(hashDir, "chats");
  let names;
  try {
    names = fs.readdirSync(chatsDir, { withFileTypes: true }).filter((e) => e.isFile() && e.name.startsWith("session-") && e.name.endsWith(".json")).map((e) => e.name);
  } catch {
    return null;
  }
  const shortId = sessionId.slice(0, 8);
  names.sort((a, b) => Number(b.includes(shortId)) - Number(a.includes(shortId)));
  for (const name of names) {
    const full = path.join(chatsDir, name);
    if (readChatFile(full)?.sessionId === sessionId) {
      return full;
    }
  }
  return null;
}
function isGeminiLogEntry(v) {
  if (typeof v !== "object" || v === null) {
    return false;
  }
  const obj = v;
  return typeof obj.sessionId === "string" && typeof obj.messageId === "number" && typeof obj.message === "string" && typeof obj.timestamp === "string";
}
function messageRecordToMessage(record) {
  const role = record.type === "user" ? "user" : "assistant";
  const parts = [];
  if (record.type === "gemini" && record.thoughts) {
    for (const thought of record.thoughts) {
      parts.push({ content: thought.summary ?? "", type: "thinking" });
    }
  }
  const rawContent = record.content;
  const contentParts = typeof rawContent === "string" ? [{ text: rawContent }] : rawContent;
  for (const part of contentParts) {
    if ("functionCall" in part) {
      parts.push({
        id: part.functionCall.id ?? part.functionCall.name,
        input: part.functionCall.args,
        toolName: part.functionCall.name,
        type: "tool_use"
      });
    } else if ("thought" in part && part.thought === true) {
      parts.push({ content: part.text, type: "thinking" });
    } else if ("text" in part) {
      parts.push({ content: part.text, type: "text" });
    }
  }
  if (record.type === "gemini" && record.toolCalls) {
    for (const tc of record.toolCalls) {
      const alreadyInParts = parts.some((p) => p.type === "tool_use" && p.id === tc.id);
      if (!alreadyInParts) {
        parts.push({
          id: tc.id,
          input: tc.args,
          toolName: tc.name,
          type: "tool_use"
        });
      }
    }
  }
  return {
    id: record.id,
    parts,
    role,
    timestamp: record.timestamp
  };
}
function readChatFile(filePath) {
  try {
    if (fs.statSync(filePath).size > MAX_GEMINI_FILE_BYTES) {
      return null;
    }
    return JSON.parse(fs.readFileSync(filePath, "utf-8"));
  } catch {
    return null;
  }
}
function readLogsJson(logsPath) {
  try {
    if (fs.statSync(logsPath).size > MAX_GEMINI_FILE_BYTES) {
      return [];
    }
    const parsed = JSON.parse(fs.readFileSync(logsPath, "utf-8"));
    return Array.isArray(parsed) ? parsed.filter(isGeminiLogEntry) : [];
  } catch {
    return [];
  }
}
function sessionsFromLogsJson(hashDir, cwd) {
  const logsPath = path.join(hashDir, "logs.json");
  let stat;
  try {
    stat = fs.statSync(logsPath);
  } catch {
    return [];
  }
  const entries = readLogsJson(logsPath);
  if (entries.length === 0) {
    return [];
  }
  const bySession = /* @__PURE__ */ new Map();
  for (const entry of entries) {
    let bucket = bySession.get(entry.sessionId);
    if (!bucket) {
      bucket = [];
      bySession.set(entry.sessionId, bucket);
    }
    bucket.push(entry);
  }
  const sessions = [];
  for (const [sessionId, sessionEntries] of bySession) {
    const first = sessionEntries[0];
    const last = sessionEntries[sessionEntries.length - 1];
    sessions.push({
      created: first?.timestamp ?? stat.birthtime.toISOString(),
      gitBranch: "",
      id: sessionId,
      messageCount: sessionEntries.length,
      modified: last?.timestamp ?? stat.mtime.toISOString(),
      projectPath: cwd,
      source: "gemini",
      summary: "",
      title: cleanTitle(first?.message ?? "")
    });
  }
  return sessions;
}
function shortHash$1(input) {
  return crypto.createHash("sha256").update(input).digest("hex").slice(0, 8);
}
function resolveOpenCodeDbPath() {
  const home = process.env.HOME || "";
  const candidates = [];
  if (process.env.XDG_DATA_HOME) {
    candidates.push(path.join(process.env.XDG_DATA_HOME, "opencode", "opencode.db"));
  }
  candidates.push(path.join(home, ".local", "share", "opencode", "opencode.db"));
  if (process.platform === "darwin") {
    candidates.push(path.join(home, "Library", "Application Support", "opencode", "opencode.db"));
  }
  for (const candidate of candidates) {
    if (existsSync(candidate)) {
      return candidate;
    }
  }
  return candidates[0] ?? path.join(home, ".local", "share", "opencode", "opencode.db");
}
const QWEN_PROJECTS = path.join(homedir(), ".qwen", "projects");
const PREFIX_BYTES = 64 * 1024;
const MAX_QWEN_FILE_BYTES = 16 * 1024 * 1024;
const SYSTEM_TAG_PREFIXES = [
  "<command-name>",
  "<local-command",
  "<system-reminder>",
  "<task-notification>"
];
function detectActiveQwenSessions(thresholdMs) {
  const cutoff = Date.now() - thresholdMs;
  const out = [];
  for (const filePath of collectQwenFiles()) {
    try {
      const stat = fs.statSync(filePath);
      if (stat.mtimeMs < cutoff) {
        continue;
      }
      const meta = readMeta(readPrefix(filePath));
      if (meta) {
        out.push({ cwd: meta.cwd, id: meta.id, startedAt: stat.birthtimeMs });
      }
    } catch {
    }
  }
  return out;
}
function getQwenConversation(sessionId, offset = 0, limit = 200) {
  if (!/^[A-Za-z0-9_-]+$/.test(sessionId)) {
    return [];
  }
  const filePath = collectQwenFiles().find((p) => path.basename(p) === `${sessionId}.jsonl`);
  if (!filePath) {
    return [];
  }
  try {
    const messages = readQwenMessages(filePath);
    if (offset === 0 && messages.length > limit) {
      let startIdx = messages.length - limit;
      while (startIdx > 0 && messages[startIdx].role !== "user") {
        startIdx--;
      }
      return messages.slice(startIdx);
    }
    return messages.slice(offset, offset + limit);
  } catch (error) {
    console.error("[qwen] Failed to read conversation:", error);
    return [];
  }
}
function listQwenProjects() {
  const byCwd = /* @__PURE__ */ new Map();
  for (const filePath of collectQwenFiles()) {
    let stat;
    try {
      stat = fs.statSync(filePath);
    } catch {
      continue;
    }
    const meta = readMeta(readPrefix(filePath));
    if (!meta) {
      continue;
    }
    const session = {
      created: meta.started || stat.birthtime.toISOString(),
      gitBranch: meta.gitBranch,
      id: meta.id,
      messageCount: 0,
      modified: stat.mtime.toISOString(),
      projectPath: meta.cwd,
      source: "qwen",
      summary: "",
      title: meta.title || "Untitled Session"
    };
    const bucket = byCwd.get(meta.cwd);
    if (bucket) {
      bucket.push(session);
    } else {
      byCwd.set(meta.cwd, [session]);
    }
  }
  const projects = [];
  for (const [cwd, sessions] of byCwd) {
    sessions.sort((a, b) => new Date(b.modified).getTime() - new Date(a.modified).getTime());
    const segments = cwd.split("/").filter(Boolean);
    projects.push({
      fullPath: cwd,
      id: shortHash(cwd),
      lastModified: sessions[0]?.modified ?? "",
      name: segments.slice(-2).join("/"),
      sessionCount: sessions.length,
      sessions
    });
  }
  return projects.sort(
    (a, b) => new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime()
  );
}
function resolveQwenSessionFile(sessionId) {
  if (!/^[A-Za-z0-9_-]+$/.test(sessionId)) {
    return null;
  }
  return collectQwenFiles().find((p) => path.basename(p) === `${sessionId}.jsonl`) ?? null;
}
function collectQwenFiles() {
  const out = [];
  let projectDirs;
  try {
    projectDirs = fs.readdirSync(QWEN_PROJECTS, { withFileTypes: true });
  } catch {
    return out;
  }
  for (const dir of projectDirs) {
    if (!dir.isDirectory()) {
      continue;
    }
    const chatsDir = path.join(QWEN_PROJECTS, dir.name, "chats");
    try {
      for (const f of fs.readdirSync(chatsDir)) {
        if (f.endsWith(".jsonl")) {
          out.push(path.join(chatsDir, f));
        }
      }
    } catch {
    }
  }
  return out;
}
function qwenLineToMessage(entry) {
  const type = entry.type;
  if (type !== "user" && type !== "assistant") {
    return null;
  }
  const message = entry.message ?? {};
  const rawParts = Array.isArray(message.parts) ? message.parts : [];
  const parts = [];
  for (const raw of rawParts) {
    if (typeof raw !== "object" || raw === null) {
      continue;
    }
    const p = raw;
    if (p.functionCall && typeof p.functionCall === "object") {
      const fc = p.functionCall;
      const toolName = typeof fc.name === "string" ? fc.name : "tool";
      parts.push({
        id: typeof fc.id === "string" ? fc.id : toolName,
        input: fc.args ?? {},
        toolName,
        type: "tool_use"
      });
    } else if (p.thought === true && typeof p.text === "string") {
      parts.push({ content: p.text, type: "thinking" });
    } else if (typeof p.text === "string") {
      parts.push({ content: p.text, type: "text" });
    }
  }
  if (parts.length === 0 && typeof message.content === "string" && message.content) {
    parts.push({ content: message.content, type: "text" });
  }
  if (parts.length === 0) {
    return null;
  }
  return {
    id: typeof entry.uuid === "string" ? entry.uuid : `qwen-${type}`,
    parts,
    role: type === "user" ? "user" : "assistant",
    timestamp: typeof entry.timestamp === "string" ? entry.timestamp : ""
  };
}
function readMeta(prefix) {
  let cwd = "";
  let id = "";
  let gitBranch = "";
  let started = "";
  let title = "";
  for (const line of prefix.split("\n")) {
    const trimmed = line.trim();
    if (!trimmed) {
      continue;
    }
    let entry;
    try {
      entry = JSON.parse(trimmed);
    } catch {
      continue;
    }
    if (!cwd && typeof entry.cwd === "string") {
      cwd = entry.cwd;
    }
    if (!id && typeof entry.sessionId === "string") {
      id = entry.sessionId;
    }
    if (!gitBranch && typeof entry.gitBranch === "string") {
      gitBranch = entry.gitBranch;
    }
    if (!started && typeof entry.timestamp === "string") {
      started = entry.timestamp;
    }
    if (!title && entry.type === "user") {
      const msg = entry.message;
      let text = typeof msg?.content === "string" ? msg.content : "";
      if (!text && Array.isArray(msg?.parts)) {
        text = msg.parts.map(
          (p) => p && typeof p === "object" && typeof p.text === "string" ? p.text : ""
        ).join(" ").trim();
      }
      if (text && !SYSTEM_TAG_PREFIXES.some((p) => text.startsWith(p))) {
        title = text.split("\n")[0]?.slice(0, 80) ?? "";
      }
    }
  }
  return id && cwd ? { cwd, gitBranch, id, started, title } : null;
}
function readPrefix(filePath) {
  const fd = fs.openSync(filePath, "r");
  try {
    const buf = Buffer.alloc(PREFIX_BYTES);
    const n = fs.readSync(fd, buf, 0, PREFIX_BYTES, 0);
    const text = buf.toString("utf-8", 0, n);
    const lastNl = text.lastIndexOf("\n");
    return lastNl === -1 ? text : text.slice(0, lastNl);
  } finally {
    fs.closeSync(fd);
  }
}
function readQwenMessages(filePath) {
  const messages = [];
  for (const line of readQwenTextBounded(filePath).split("\n")) {
    const trimmed = line.trim();
    if (!trimmed) {
      continue;
    }
    try {
      const msg = qwenLineToMessage(JSON.parse(trimmed));
      if (msg) {
        messages.push(msg);
      }
    } catch {
    }
  }
  return messages;
}
function readQwenTextBounded(filePath) {
  const size = fs.statSync(filePath).size;
  if (size <= MAX_QWEN_FILE_BYTES) {
    return fs.readFileSync(filePath, "utf-8");
  }
  const fd = fs.openSync(filePath, "r");
  try {
    const buf = Buffer.alloc(MAX_QWEN_FILE_BYTES);
    const n = fs.readSync(fd, buf, 0, MAX_QWEN_FILE_BYTES, size - MAX_QWEN_FILE_BYTES);
    const tail = buf.toString("utf-8", 0, n);
    return tail.slice(tail.indexOf("\n") + 1);
  } finally {
    fs.closeSync(fd);
  }
}
function shortHash(input) {
  return crypto.createHash("sha256").update(input).digest("hex").slice(0, 8);
}

export { detectActiveGeminiSessions as a, detectActiveQwenSessions as b, detectActiveCursorSessions as c, detectActiveCodexSessions as d, detectActiveCopilotSessions as e, detectActiveAmpSessions as f, getCodexConversation as g, listGeminiProjects as h, getGeminiConversation as i, listQwenProjects as j, getQwenConversation as k, listCodexProjects as l, listCursorProjects as m, getCursorConversation as n, listCopilotProjects as o, getCopilotConversation as p, listAmpProjects as q, resolveOpenCodeDbPath as r, getAmpConversation as s, findCodexRolloutForCwd as t, resolveQwenSessionFile as u, resolveGeminiSessionFile as v, resolveCursorSessionFile as w, resolveCopilotSessionFile as x, resolveAmpSessionFile as y };
//# sourceMappingURL=qwen-reader-DGfUbKaJ.js.map
