import { H as M, d as R, f as v } from "./stream-CtDBTPgX.js";
import { m as U } from "./transformers-BLTCfl6l.js";
import { C as u, I as _ } from "./context-chat-message-DzjJbTBD.js";
import { T as k } from "./tool-message-list-B1XEM-VL.js";
import { d as $ } from "./shared-types-CIxCt9tj.js";
import { b as A } from "./telemetry-Bf0GI6nJ.js";
import { C as z } from "./token-estimator-B45EKs9J.js";
import { a as l } from "./logger-CTb8_yz9.js";
const C = A($.Agent, "Context");
class f {
  messages = [];
  constructor(e = []) {
    this.messages = e;
  }
  /**
   * Creates an empty context
   */
  static empty() {
    return new f();
  }
  /**
   * Creates a new context with an additional message
   */
  withNewMessage(e) {
    return new f([...this.messages, e]).removeDuplicateFiles();
  }
  /**
   * Create or extend message
   */
  withExtendedMessage(e) {
    const t = this.messages[this.messages.length - 1];
    if (t && t.role === e.role) {
      const s = [...t.entries, ...e.entries], n = new u(
        e.role,
        s,
        t.messageId,
        e.forcedRole
      );
      return this.withReplacedMessageById(t.messageId, n);
    } else
      return this.withNewMessage(e);
  }
  /**
   * Creates a new context with environment state information added
   * @returns A new ModelContext with current editor state information
   */
  withEnvironmentState() {
    const e = [...this.messages.slice(0, this.messages.length - 1)], t = this.messages.at(-1);
    return t && e.push(t.withEnvironmentInfo()), new f(e);
  }
  /**
   * Creates a new context with a merged message
   * @param message The message to merge with an existing message with the same ID
   * @returns A new ModelContext with the merged message
   */
  withMergedMessage(e) {
    const s = [...this.messages].find((o) => o.messageId === e.messageId);
    if (!s)
      return this.withNewMessage(e);
    let n = s.entries;
    n = [...n, ...e.entries];
    const a = e.entries.filter((o) => o.type === "toolUse");
    if (a.length > 0) {
      const o = new Map(a.map((i) => [i.id, i]));
      n = n.map((i) => {
        if (i.type === "toolUse") {
          const p = o.get(i.id);
          if (p)
            return p;
        }
        return i;
      });
      const g = new Set(n.filter((i) => i.type === "toolUse").map((i) => i.id)), d = a.filter((i) => !g.has(i.id));
      n = [...n, ...d];
    }
    let r;
    switch (e.role) {
      case "human":
        r = u.fromHuman(e.messageId);
        break;
      case "bot":
        r = u.fromAI(e.messageId);
        break;
      case "tool":
        r = u.fromTool(e.messageId);
        break;
      default:
        throw new _(e.role);
    }
    return r = n.reduce((o, g) => {
      const d = JSON.stringify(g);
      return o.entries.find((i) => JSON.stringify(i) === d) ? o : o.withEntry(g);
    }, r), this.withReplacedMessageById(e.messageId, r);
  }
  /**
   * Creates a new context with the specified message removed
   */
  withRemovedMessage(e) {
    const t = this.messages.filter((s) => s.messageId !== e);
    return new f(t);
  }
  /**
   * Replaces the given message in context with a new message
   */
  withReplacedMessageById(e, t) {
    const s = [...this.messages], n = s.findIndex((a) => a.messageId === e);
    return s[n] = new u(t.role, t.entries, e), new f(s).removeDuplicateFiles();
  }
  /**
   * Get Last Message Id
   */
  getLastMessageId() {
    return this.messages.at(-1)?.messageId;
  }
  /**
   * Find a message by the ID
   */
  getMessageById(e) {
    return this.messages.find((t) => t.messageId === e);
  }
  /**
   * Serializes the context to a string format
   */
  async serializeToContext(e) {
    const t = [];
    this.messages.length > 0 && this.messages[0].role !== "human" && t.push(await u.fromHuman().serializeToContext(e));
    for (const s of this.messages)
      t.push(await s.serializeToContext(e));
    return t;
  }
  /**
   * Gets all workspace files referenced in this context
   */
  getWorkspaceFiles() {
    const e = [];
    for (const t of this.messages)
      for (const s of t.entries) {
        if (s.type === "document" && s.document.type === "file" && e.push(s.document), s.type === "toolUse" && s.name === "readFile") {
          const { path: n } = s.args;
          this.isValidPath(n) ? e.push({ type: "file", path: n }) : C.reportCountMetrics({ InvalidFilePathInReadFile: 1 });
        }
        if (s.type === "toolUse" && s.name === "readMultipleFiles")
          for (const n of s.args.paths)
            this.isValidPath(n) ? e.push({ type: "file", path: n }) : C.reportCountMetrics({ InvalidFilePathInReadMultipleFiles: 1 });
      }
    return e;
  }
  /**
   * Gets all context objects referenced in this context
   */
  getContextObjects() {
    const e = [];
    for (const t of this.messages)
      for (const s of t.entries)
        s.type === "document" && e.push(s.document);
    return e;
  }
  /**
   * Gets all workspace steering information from this context
   */
  getWorkspaceSteering() {
    const e = [];
    for (const t of this.messages)
      for (const s of t.entries)
        s.type === "document" && s.document.type === "steering" && e.push(s.document);
    return e;
  }
  /**
   * Serializes the context to a langchain format
   */
  async serializeToLangChain(e, t) {
    const n = (await this.serializeToContext(e)).map(this.serializeMessage.bind(this)), a = U(n);
    for (const r of n)
      r.additional_kwargs.conversationId = t.conversationId, t.continuationId && (r.additional_kwargs.continuationId = t.continuationId), t.taskType && (r.additional_kwargs.taskType = t.taskType);
    return a;
  }
  isValidPath(e) {
    return e != null && typeof e == "string";
  }
  serializeMessage(e) {
    const t = [];
    if (t.push({
      type: "text",
      text: e.content
    }), e.images)
      for (const s of e.images)
        t.push({
          type: "image_url",
          image_url: s
        });
    if (e.documentAttachments)
      for (const s of e.documentAttachments)
        t.push({
          type: "document_url",
          document_url: s
        });
    switch (e.role) {
      case "bot": {
        const s = new v({ content: t });
        return s.tool_calls = e.toolUses?.map((n) => ({
          id: n.id,
          name: n.name,
          args: n.args
        })), e.reasoningContent && (s.additional_kwargs.reasoningContent = e.reasoningContent), e.reasoningSignature && (s.additional_kwargs.reasoningSignature = e.reasoningSignature), e.reasoningModelId && (s.additional_kwargs.reasoningModelId = e.reasoningModelId), s;
      }
      case "human":
        return new M({ content: t });
      case "tool":
        if (e.toolUseResponses) {
          const s = e.toolUseResponses.map((n) => {
            const a = [];
            if (n.message && a.push({
              type: "text",
              text: n.message
            }), n.imageBase64Urls)
              for (const g of n.imageBase64Urls)
                t.push({
                  type: "image_url",
                  image_url: g
                });
            const r = new R({
              content: a,
              tool_call_id: n.id,
              name: n.name
            }), o = r.additional_kwargs ?? {};
            return r.additional_kwargs = { ...o, success: n.success }, r;
          });
          return new k({
            toolMessages: s,
            content: t
          });
        }
        return new k({
          content: t,
          toolMessages: []
        });
      default:
        return new M({ content: t });
    }
  }
  /**
   * Serializes the context to JSON
   */
  serializeToObject() {
    return { messages: this.messages.map((e) => e.serializeToObject()) };
  }
  /**
   * Serializes context into a test format (concatenated string)
   */
  async serializeForTesting(e) {
    return (await this.serializeToContext(e)).map((s) => `${s.role} ${"-".repeat(100)} 

${s.content}
`).join(`
`);
  }
  /**
   * Removes duplicate file documents from the context
   */
  removeDuplicateFiles() {
    const e = /* @__PURE__ */ new Set(), t = this.messages.map((s) => {
      const n = s.entries.filter((a) => {
        if (a.type === "document" && a.document.type === "file") {
          if (e.has(a.document.path))
            return !1;
          e.add(a.document.path);
        }
        return !0;
      });
      return new u(s.role, n, s.messageId, s.forcedRole);
    });
    return new f(t);
  }
  /**
   * Set implicit rules for this context
   * Instead of storing rules separately, we add them as actual messages in the conversation
   * This ensures they're preserved in the graph state and don't create dynamic content during serialization
   */
  withImplicitRules(e) {
    if (!e || e.getRules().length === 0)
      return new f([...this.messages]);
    const t = e.getCombinedRulesContent();
    if (!t)
      return new f([...this.messages]);
    if (this.messages.some(
      (r) => r.entries.some((o) => o.type === "text" && o.text.includes(t))
    ))
      return new f([...this.messages]);
    const n = [...this.messages], a = n[n.length - 1];
    if (a.role === "human") {
      const r = [...a.entries, { type: "text", text: t }];
      n[n.length - 1] = new u(
        a.role,
        r,
        a.messageId,
        a.forcedRole
      );
    }
    return new f(n);
  }
  /**
   * Creates a new context from serialized JSON
   */
  static fromSerializedJson(e) {
    return new f(
      e.messages.map((t) => new u(t.role, t.entries, t.messageId))
    );
  }
}
const E = {
  enabled: !0,
  compactionThreshold: 0.6,
  preserveRecentRounds: 2,
  enableAutoMonitoring: !0,
  defaultTargetTokens: 8e3,
  defaultCompressionRatio: 0.5,
  maxCompactionTimeMs: 6e4,
  // 60 seconds
  preserveUserMessages: !0,
  preserveToolResults: !0,
  provider: "qdev",
  analysisModel: "CLAUDE_3_7_SONNET_20250219_V1_0",
  strategies: {
    "compression-tagging": {
      enabled: !0,
      priority: 2,
      parameters: {}
    },
    "simple-strategy": {
      enabled: !0,
      priority: 1,
      parameters: {}
    }
  },
  tokenEstimation: {
    defaultTokenizer: "generic",
    cacheSize: 1e3,
    cacheTTL: 300 * 1e3,
    // 5 minutes
    enableBatching: !0,
    batchSize: 10
  }
};
let m = { ...E };
function T() {
  return { ...m };
}
function G(c) {
  c.strategies && (m.strategies = {
    ...m.strategies,
    ...c.strategies
  }, delete c.strategies), c.tokenEstimation && (m.tokenEstimation = {
    ...m.tokenEstimation,
    ...c.tokenEstimation
  }, delete c.tokenEstimation), m = {
    ...m,
    ...c
  };
}
function X() {
  m = { ...E };
}
function O(c) {
  return {
    enabled: !1,
    priority: 0,
    parameters: {}
  };
}
function F(c, e) {
  m.strategies[c] || (m.strategies[c] = {
    enabled: !0,
    priority: 0,
    parameters: {}
  }), m.strategies[c] = {
    ...m.strategies[c],
    ...e
  };
}
function Q() {
  return { ...m.tokenEstimation };
}
function Y(c) {
  m.tokenEstimation = {
    ...m.tokenEstimation,
    ...c
  };
}
class Z {
  /**
   * Get strategy configuration
   */
  getConfig() {
    return O(this.name);
  }
  /**
   * Update strategy configuration
   */
  updateConfig(e) {
    F(this.name, e);
  }
  /**
   * Default canHandle implementation
   * Can handle any context if the strategy is enabled
   */
  // eslint-disable-next-line @typescript-eslint/require-await
  async canHandle(e, t) {
    return this.getConfig().enabled;
  }
}
class D {
  strategies = /* @__PURE__ */ new Map();
  defaultStrategy = null;
  /**
   * Register a strategy
   */
  register(e) {
    this.strategies.set(e.name, e), this.defaultStrategy === null && (this.defaultStrategy = e.name);
  }
  /**
   * Set the default strategy
   */
  setDefaultStrategy(e) {
    if (!this.strategies.has(e))
      throw new Error(`Strategy '${e}' not found`);
    this.defaultStrategy = e;
  }
  /**
   * Get a strategy
   */
  getStrategy(e) {
    const t = this.strategies.get(e);
    if (!t)
      throw new Error(`Strategy '${e}' not found`);
    return t;
  }
  /**
   * Get the default strategy
   */
  getDefaultStrategy() {
    if (this.defaultStrategy === null)
      throw new Error("No default strategy set");
    return this.getStrategy(this.defaultStrategy);
  }
  /**
   * Get all strategies
   */
  getAllStrategies() {
    return Array.from(this.strategies.values());
  }
  /**
   * Get all strategy names
   */
  getAllStrategyNames() {
    return Array.from(this.strategies.keys());
  }
  /**
   * Clear all strategies
   */
  clear() {
    this.strategies.clear(), this.defaultStrategy = null;
  }
}
let h = null;
function S() {
  return h === null && (h = new D()), h;
}
function x() {
  h && h.clear(), h = null;
}
class N {
  /**
   * Execute compression operation
   * @param context Context to compress
   * @param options Compression options
   * @returns Compression result
   */
  async compact(e, t) {
    const s = T();
    if (!s.enabled)
      return {
        context: e,
        metrics: {
          originalTokens: 0,
          finalTokens: 0,
          originalMessageCount: e.messages.length,
          finalMessageCount: e.messages.length,
          compactionTimeMs: 0,
          strategyUsed: "none",
          compressionRatio: 0
        }
      };
    const n = S(), a = n.getAllStrategies();
    if (a.length === 0)
      return l.warn("[Compactor] No compression strategies available"), {
        context: e,
        metrics: {
          originalTokens: 0,
          finalTokens: 0,
          originalMessageCount: e.messages.length,
          finalMessageCount: e.messages.length,
          compactionTimeMs: 0,
          strategyUsed: "none",
          compressionRatio: 0
        }
      };
    let r = null;
    try {
      const o = n.getDefaultStrategy();
      await o.canHandle(e, t) && (r = o, l.info(`[Compactor] Using default strategy: ${o.name}`));
    } catch (o) {
      l.warn("[Compactor] Error checking default strategy:", o);
    }
    if (!r)
      for (const o of a)
        try {
          if (await o.canHandle(e, t)) {
            r = o, l.info(`[Compactor] Using strategy: ${o.name}`);
            break;
          }
        } catch (g) {
          l.warn(`[Compactor] Error checking strategy ${o.name}:`, g);
        }
    if (!r)
      return l.warn("[Compactor] No suitable compression strategy found"), {
        context: e,
        metrics: {
          originalTokens: 0,
          finalTokens: 0,
          originalMessageCount: e.messages.length,
          finalMessageCount: e.messages.length,
          compactionTimeMs: 0,
          strategyUsed: "none",
          compressionRatio: 0
        }
      };
    try {
      const o = Date.now(), g = new Promise((P, b) => {
        setTimeout(() => {
          b(new z("Compaction operation timed out", r.name || "unknown"));
        }, s.maxCompactionTimeMs);
      }), d = r.compact(e, t), i = await Promise.race([d, g]), p = Date.now();
      return i.metrics.compactionTimeMs = p - o, l.info(`[Compactor] Compaction completed using strategy ${r.name}`, {
        originalTokens: i.metrics.originalTokens,
        finalTokens: i.metrics.finalTokens,
        compressionRatio: i.metrics.compressionRatio,
        timeMs: i.metrics.compactionTimeMs
      }), i;
    } catch (o) {
      return l.error(`[Compactor] Compaction failed with strategy ${r.name}:`, o), {
        context: e,
        metrics: {
          originalTokens: 0,
          finalTokens: 0,
          originalMessageCount: e.messages.length,
          finalMessageCount: e.messages.length,
          compactionTimeMs: 0,
          strategyUsed: `${r.name} (failed)`,
          compressionRatio: 0,
          strategyMetrics: {
            error: o instanceof Error ? o.message : String(o)
          }
        }
      };
    }
  }
  /**
   * Estimate token count for context
   * @param context Context to estimate
   * @param modelName Model name
   * @returns Estimated token count
   */
  async estimateTokens(e, t) {
    const s = S();
    try {
      return await s.getDefaultStrategy().estimateTokens(e, t);
    } catch (n) {
      l.warn("[Compactor] Error estimating tokens with default strategy:", n);
      const a = s.getAllStrategies();
      for (const r of a)
        try {
          return await r.estimateTokens(e, t);
        } catch (o) {
          l.warn(`[Compactor] Error estimating tokens with strategy ${r.name}:`, o);
        }
      return e.messages.length * 100;
    }
  }
}
let y = null;
function I() {
  return y === null && (y = new N()), y;
}
function ee() {
  y = null;
}
class H {
  /**
   * Check if compression is needed
   * @param context Context to check
   * @param modelName Model name
   * @param maxTokens Model's maximum token count
   * @returns Whether compression is needed
   */
  async isCompactionNeeded(e, t, s) {
    try {
      const n = T();
      if (!n.enabled)
        return !1;
      const r = await I().estimateTokens(e, t), o = s * n.compactionThreshold, g = r > o;
      return g && l.info(
        `[TokenMonitor] Compression needed: ${r} tokens exceeds ${n.compactionThreshold * 100}% threshold (${o} tokens)`,
        { estimatedTokens: r, threshold: o, maxTokens: s }
      ), g;
    } catch (n) {
      return l.error("[TokenMonitor] Error checking if compression is needed:", n), !1;
    }
  }
  /**
   * Monitor and compress context when needed
   * @param context Context to monitor
   * @param modelName Model name
   * @param maxTokens Model's maximum token count
   * @returns Original or compressed context
   */
  async monitorAndCompact(e, t, s) {
    try {
      const n = T(), a = I(), r = await a.estimateTokens(e, t), o = Math.floor(s * 0.25), g = Math.floor(s * 0.15), d = {
        maxTokens: s,
        targetTokens: o,
        modelName: t,
        preserveRecent: n.preserveRecentRounds,
        minMessagesToKeep: n.preserveRecentRounds * 2,
        // Keep at least this many messages
        compactionTokens: g
        // Specify to compress only the earliest portion
      };
      l.info("[TokenMonitor] Executing context compression", d);
      const i = await a.compact(e, d), p = await a.estimateTokens(i.context, t);
      return l.info(
        `[TokenMonitor] Compression completed: ${r} → ${p} tokens (${Math.round((1 - p / r) * 100)}% reduction)`,
        { originalTokens: r, finalTokens: p }
      ), i.context;
    } catch (n) {
      return l.error("[TokenMonitor] Error monitoring and compressing context:", n), e;
    }
  }
}
let w = null;
function te() {
  return w === null && (w = new H()), w;
}
function se() {
  w = null;
}
function ne(c) {
  const e = {};
  if (e[c])
    return e[c];
  for (const [t, s] of Object.entries(e))
    if (c.toLowerCase().includes(t.toLowerCase()))
      return s;
  return 2e5;
}
export {
  Z as B,
  N as C,
  E as D,
  f as M,
  D as S,
  H as T,
  T as a,
  ne as b,
  O as c,
  S as d,
  Q as e,
  te as f,
  I as g,
  X as h,
  x as i,
  se as j,
  F as k,
  Y as l,
  ee as r,
  G as u
};
//# sourceMappingURL=token-monitor-QTYxqQ8j.js.map
