import { B as A, a as N, M as O, b as D, f as U, u as _, d as k, g as L } from "../../token-monitor-Di2YJYfq.js";
import { C as ne, D as re, S as ae, T as ie, c as ce, e as me, r as le, h as ue, i as ge, j as pe, k as de, l as fe } from "../../token-monitor-Di2YJYfq.js";
import { a as I, C as y } from "../../token-estimator-B45EKs9J.js";
import { S as he, T as ye } from "../../token-estimator-B45EKs9J.js";
import { C as R } from "../../context-chat-message-C7_HInOo.js";
import { l as w } from "../../model-provider-DwyIQZZf.js";
import { H as v } from "../../stream-CtDBTPgX.js";
import "../../base-BCJFoMV_.js";
import "uuid";
import "../../string-BZO3_EzG.js";
import { a as l } from "../../logger-CTb8_yz9.js";
class F extends A {
  name = "compression-tagging";
  description = "LLM-driven summarization using importance scoring and tagging rules";
  tokenEstimator;
  constructor() {
    super(), this.tokenEstimator = new I({
      defaultTokenizer: "generic",
      cacheSize: 1e3,
      cacheTtl: 300 * 1e3,
      // 5 minutes
      enableBatching: !0,
      batchSize: 10
    });
  }
  /**
   * Estimate token count for context
   */
  async estimateTokens(e, s) {
    return this.tokenEstimator.estimateContextTokens(e, s);
  }
  /**
   * Check if this strategy can handle the given context
   */
  async canHandle(e, s) {
    return e.messages.length === 0 ? !1 : e.messages.length >= 3;
  }
  /**
   * Execute compression operation
   */
  async compact(e, s) {
    const r = Date.now(), t = await this.estimateTokens(e, s.modelName), i = e.messages.length;
    try {
      const o = await this.generateCompressedContext(e, s), m = await this.estimateTokens(o, s.modelName), p = o.messages.length, d = (t - m) / t, g = Date.now() - r;
      return {
        context: o,
        metrics: {
          originalTokens: t,
          finalTokens: m,
          originalMessageCount: i,
          finalMessageCount: p,
          compactionTimeMs: g,
          strategyUsed: this.name,
          compressionRatio: d,
          strategyMetrics: {
            importanceScoresCalculated: i
          }
        }
      };
    } catch (o) {
      throw new y(
        `LLM-driven conversation summarization failed: ${o instanceof Error ? o.message : String(o)}`,
        this.name,
        { originalTokens: t, originalMessageCount: i }
      );
    }
  }
  /**
   * Format chat entry for analysis
   */
  formatEntryForAnalysis(e) {
    switch (e.type) {
      case "text":
        return {
          type: "text",
          content: e.text,
          containsCode: e.text.includes("```")
        };
      case "image":
        return {
          type: "image",
          description: `[Image: ${e.image || "No description"}]`,
          isRecoverable: !0
          // Images are usually converted to text, so usually recoverable
        };
      case "document":
        return {
          type: "document",
          documentType: e.document.type,
          isRecoverable: !0
          // Documents are usually recoverable, can be read again
        };
      case "toolDefinition":
        return {
          type: "toolDefinition",
          toolName: e.tool.id,
          toolDescription: e.tool.description,
          isRecoverable: !0
          // Tool definitions are usually recoverable
        };
      case "toolUse":
        return {
          type: "toolUse",
          toolName: e.name,
          args: e.args,
          isRecoverable: this.isToolCallRecoverable(e.name)
        };
      case "toolUseResponse":
        return {
          type: "toolUseResponse",
          toolName: e.name,
          message: e.message || "No message",
          isRecoverable: !1
          // Tool responses usually contain important information
        };
      case "AgentAction":
        return {
          type: "AgentAction",
          actionId: e.actionId,
          isRecoverable: !0
          // Agent actions can usually be inferred
        };
      case "AgentActionSuccess":
        return {
          type: "AgentActionSuccess",
          actionId: e.actionId,
          isRecoverable: !0
        };
      case "AgentActionError":
        return {
          type: "AgentActionError",
          actionId: e.actionId,
          error: e.error,
          isRecoverable: !1
          // Error information is important and should be preserved
        };
      case "AgentActionInvalidInput":
        return {
          type: "AgentActionInvalidInput",
          actionId: e.actionId,
          error: e.error,
          isRecoverable: !1
          // Invalid input is important for understanding the problem
        };
      case "agentInvoke":
        return {
          type: "agentInvoke",
          executionId: e.executionId,
          isRecoverable: !0
        };
      default:
        return {
          type: e.type,
          isRecoverable: !0
          // Default unknown types as recoverable
        };
    }
  }
  /**
   * Determine if a tool call is recoverable based on tool name
   */
  isToolCallRecoverable(e) {
    const s = [
      "fs_read_file",
      "read_file",
      "list_directory",
      "search_files",
      "get_current_weather",
      "search_web",
      "browse_web"
    ], r = [
      "execute_code",
      "run_shell",
      "execute_shell",
      "database_query",
      "api_call",
      "generate_image"
    ];
    return s.some((t) => e.includes(t)) ? !0 : (r.some((t) => e.includes(t)), !1);
  }
  /**
   * Generate compressed context using a single LLM call
   */
  async generateCompressedContext(e, s) {
    const r = N(), t = e.messages.length, i = [], o = [], m = [];
    if (t < 5)
      return e;
    for (let a = 0; a < 4; a++)
      o.push(e.messages[a]);
    let p = 0, d = 0;
    const g = Math.floor(s.maxTokens * 0.15);
    for (let a = 4; a < t && d < 10; a++) {
      const u = e.messages[a], h = this.tokenEstimator.estimateMessageTokens(u, s.modelName);
      if (u.role === "human" && p >= g && i.length > 0) {
        for (let f = a; f < t; f++)
          m.push(e.messages[f]);
        break;
      }
      if (i.push(u), p += h, d++, a === t - 1)
        break;
    }
    if (i.length === 0)
      return e;
    const T = i.map((a, u) => {
      const h = a.role === "human" ? "User" : a.role === "bot" ? "Assistant" : "Tool", f = a.role === "human", E = a.entries.map((c) => this.formatEntryForAnalysis(c));
      return {
        id: a.messageId,
        role: h,
        entries: E,
        isProtected: r.preserveUserMessages && f,
        position: {
          isFirst: u === 0,
          isLast: u === i.length - 1,
          index: u
        }
      };
    }), C = `
    [SYSTEM NOTE: This is an automated summarization request, not from the user]

    FORMAT REQUIREMENTS: Create a structured, concise summary in bullet-point format. DO NOT respond conversationally. DO NOT address the user directly.

    Your task is to create a structured summary document containing:
    1) A bullet-point list of key topics/questions covered
    2) Bullet points for all significant tools executed and their results
    3) Bullet points for any code or technical information shared
    4) A section of key insights gained

    FORMAT THE SUMMARY IN THIRD PERSON, NOT AS A DIRECT RESPONSE. Example format:

    ## CONVERSATION SUMMARY
    * Topic 1: Key information
    * Topic 2: Key information

    ## TOOLS EXECUTED
    * Tool X: Result Y

    Remember this is a DOCUMENT not a chat response.
    FILTER OUT CHAT CONVENTIONS (greetings, offers to help, etc).
    CONVERSATION TO ANALYZE AND COMPRESS:
    ${JSON.stringify(T, null, 2)}`;
    try {
      const a = r.provider, u = r.analysisModel, E = (await w(a, u, "summarization", { forceRefresh: !0 }).invoke([new v(C)])).content;
      let c = O.empty();
      for (const S of o)
        c = c.withNewMessage(S);
      const b = R.fromHuman().withText(`Previous conversation summary: ${E}`), x = R.fromAI().withText("I understand the previous conversation context.");
      c = c.withNewMessage(b), c = c.withNewMessage(x);
      for (const S of m)
        c = c.withNewMessage(S);
      return c;
    } catch (a) {
      throw new y(
        `Failed to generate compressed context: ${a instanceof Error ? a.message : String(a)}`,
        this.name,
        { messageCount: e.messages.length }
      );
    }
  }
}
const z = "readFile", P = "readMultipleFiles";
class $ extends A {
  name = "simple-strategy";
  description = "Q CLI Compaction:";
  tokenEstimator;
  constructor() {
    super(), this.tokenEstimator = new I({
      defaultTokenizer: "generic",
      cacheSize: 1e3,
      cacheTtl: 300 * 1e3,
      // 5 minutes
      enableBatching: !0,
      batchSize: 10
    });
  }
  /**
   * Estimate token count for context
   */
  async estimateTokens(e, s) {
    return this.tokenEstimator.estimateContextTokens(e, s);
  }
  /**
   * Check if this strategy can handle the given context
   */
  async canHandle(e, s) {
    return e.messages.length === 0 ? !1 : e.messages.length >= 5;
  }
  /**
   * Execute compression operation
   */
  async compact(e, s) {
    const r = Date.now(), t = await this.estimateTokens(e, s.modelName), i = e.messages.length;
    try {
      const o = await this.generateCompressedContext(e, s), m = await this.estimateTokens(o, s.modelName), p = o.messages.length, d = (t - m) / t, g = Date.now() - r;
      return {
        context: o,
        metrics: {
          originalTokens: t,
          finalTokens: m,
          originalMessageCount: i,
          finalMessageCount: p,
          compactionTimeMs: g,
          strategyUsed: this.name,
          compressionRatio: d,
          strategyMetrics: {
            preservedRounds: 1
          }
        }
      };
    } catch (o) {
      throw new y(
        `Simple conversation compaction failed: ${o instanceof Error ? o.message : String(o)}`,
        this.name,
        { originalTokens: t, originalMessageCount: i }
      );
    }
  }
  /**
   * Extract useful information from execution results context and build structured summary
   */
  extractUsefulInformation(e) {
    const s = [];
    for (const r of e)
      for (const t of r.entries) {
        if (r.role === "human" && t.type === "text" && "text" in t && s.push(`User message: ${t.text} 
`), r.role === "bot" && t.type === "text" && "text" in t && s.push(`Assistant message: ${t.text} 
`), r.role === "bot" && t.type === "toolUse" && "name" in t && "args" in t) {
          const i = Object.keys(t.args).length > 0 ? JSON.stringify(t.args) : "no args";
          s.push(`Tool: ${t.name || "unknown"} - ${i} 
`);
        }
        if (r.role === "tool" && t.type === "toolUseResponse" && "success" in t) {
          const i = t.success ? "SUCCESS" : "FAILED";
          let o = "";
          t.name === z || t.name === P || t.name.startsWith("mcp_") ? o = " - Tool response contents truncated for brevity" : "message" in t && t.message && (o = ` - ${t.message}`), s.push(`ToolResult: ${i}${o} 
 `);
        }
      }
    return {
      structuredSummary: s.join(`
`)
    };
  }
  /**
   * Generate compressed context using a single LLM call
   */
  async generateCompressedContext(e, s) {
    const r = N(), t = this.extractUsefulInformation(e.messages.filter((o) => !o.forcedRole));
    l.info("conversationToSummarize", t.structuredSummary);
    const i = `
    [SYSTEM NOTE: This is an automated summarization request, not from the user]
    FORMAT REQUIREMENTS: Create a structured, concise summary in bullet-point format. DO NOT respond conversationally. DO NOT address the user directly.
    Your task is to create a structured summary document containing:
    1) A bullet-point list of key topics/questions covered.
    2) Bullet points for all significant tools executed and their results.
    3) Bullet points for any code or technical information shared. Summarize code snippets where they add clarity. 
    4) Bullet points for specific files and code sections examined, modified, or created for the task continuation. Pay special attention to the most recent messages and changes.
    5) Bullet points for problems solved thus far and any ongoing troubleshooting efforts.
    FORMAT THE SUMMARY IN THIRD PERSON, NOT AS A DIRECT RESPONSE. 
    Strictly follow the output format below:
    Example format:
    CONVERSATION SUMMARY
    Topic 1: Key information
    Topic 2: Key information

    TOOLS EXECUTED
    Tool X: Result Y

    RELEVANT FILES
    File 1
    File 2

    CODE IMPLEMENTED
    Part1: Key implementation
    Part2: Key implementation

    PROBLEMS SOLVED
    Problem 1: solution
    Problem 2: solution

    Remember this is a nice formatted PLAIN TEXT DOCUMENT not a chat response.
    FILTER OUT CHAT CONVENTIONS (greetings, offers to help, etc).
    STRUCTURED CONVERSATION DATA TO ANALYZE AND COMPRESS:
    ${t.structuredSummary}`;
    try {
      const o = r.provider, m = r.analysisModel, g = (await w(o, m, "summarization", { forceRefresh: !0 }).invoke([new v(i)])).content;
      l.info("summaryText", g);
      let T = O.empty();
      const C = R.fromAI().withText(g);
      return T = T.withNewMessage(C), T;
    } catch (o) {
      throw new y(
        `Failed to generate compressed context: ${o instanceof Error ? o.message : String(o)}`,
        this.name,
        { messageCount: e.messages.length }
      );
    }
  }
}
function B() {
  try {
    const n = new F();
    M(n);
    const e = new $();
    M(e), Y(e.name), l.info(
      "[CompactionInit] Compression system initialization completed, registered strategies:",
      [n.name, e.name].join(", ")
    );
  } catch (n) {
    l.error("[CompactionInit] Failed to initialize compression system:", n);
  }
}
function W(n) {
  try {
    n && _({
      compactionThreshold: n.compactionThreshold,
      preserveRecentRounds: n.preserveRecentRounds,
      enableAutoMonitoring: n.enableAutoMonitoring,
      defaultTargetTokens: n.defaultTargetTokens
    }), B(), l.info("[ContextCompaction] Successfully initialized context compression system");
  } catch (e) {
    l.error("[ContextCompaction] Failed to initialize context compression system:", e);
  }
}
async function H(n, e, s, r) {
  return r.isCompactionNeeded(n, e, s);
}
async function ee(n, e) {
  try {
    const s = D(e), r = U();
    return await H(n, e, s, r) ? (l.info("[ContextCompaction] Compression needed, executing compression"), await r.monitorAndCompact(n, e, s)) : n;
  } catch (s) {
    return l.error("[ContextCompaction] Error during compression process:", s), n;
  }
}
function M(n) {
  k().register(n), l.info(`[ContextCompaction] Registered compression strategy: ${n.name}`);
}
function Y(n) {
  k().setDefaultStrategy(n), l.info(`[ContextCompaction] Set default compression strategy: ${n}`);
}
async function te(n, e) {
  return L().estimateTokens(n, e);
}
export {
  A as BaseCompactionStrategy,
  y as CompactionError,
  ne as Compactor,
  re as DEFAULT_COMPACTION_CONFIG,
  $ as SimpleStrategy,
  he as StrategyNotFoundError,
  ae as StrategyRegistry,
  ye as TokenEstimationError,
  I as TokenEstimator,
  ie as TokenMonitor,
  ee as compactIfNeeded,
  te as estimateTokens,
  L as getCompactor,
  N as getConfig,
  D as getModelMaxTokens,
  ce as getStrategyConfig,
  k as getStrategyRegistry,
  me as getTokenEstimationConfig,
  U as getTokenMonitor,
  W as initializeCompaction,
  B as initializeCompactionSystem,
  H as needsCompaction,
  M as registerStrategy,
  le as resetCompactor,
  ue as resetConfig,
  ge as resetStrategyRegistry,
  pe as resetTokenMonitor,
  Y as setDefaultStrategy,
  _ as updateConfig,
  de as updateStrategyConfig,
  fe as updateTokenEstimationConfig
};
//# sourceMappingURL=index.js.map
