import { randomUUID as w } from "crypto";
import { a as u } from "./logger-CTb8_yz9.js";
import { a as K, b as Y } from "./autonomy-mode-CooE4oAK.js";
import { Y as J, T as X } from "./disclose-context-DwhVRwE7.js";
import { b as v } from "./telemetry-Bf0GI6nJ.js";
import { d as C, O as I, K as G, I as q } from "./shared-types-CIxCt9tj.js";
import { M as _ } from "./token-monitor-QTYxqQ8j.js";
import { C as h } from "./context-chat-message-DzjJbTBD.js";
import "./stream-CtDBTPgX.js";
import "./base-BCJFoMV_.js";
import "uuid";
import "./string-BZO3_EzG.js";
import "./prompt-DuC9mWRH.js";
import "os";
import "dedent";
import "vscode-uri";
import "path";
import "zod";
import { A as B, a as ee, p as z, d as te, E as ne, F as R, c as y, g as D } from "./sub-agent-BpZpYDp-.js";
import { Annotation as P, StateGraph as ie, START as oe, Command as x, END as f } from "@langchain/langgraph";
import { e as se, h as re, m as ae, a as ce } from "./clarification-handler-Zo3AuRjE.js";
import { minimatch as k } from "minimatch";
import { a as ue } from "./pending-changes-BF3vCKkj.js";
import { c as b } from "./prompts-DfcXHzAI.js";
import { a as F, l as U } from "./file-context-ClFefQMc.js";
import { S as de, u as W, d as le, s as pe, y as me, f as ge, e as he, h as Ee, j as fe, k as Ie, l as Te, O as Ae, g as xe } from "./index-D89vEqep.js";
import { p as L } from "./message-parts-D8WKxpG9.js";
import { I as Q } from "./intent-detection-service-DV14tv5n.js";
import "./pruning-service-DJ-mli7u.js";
import "@kiro/context-providers";
import "./message-analyzer-BAqw8PNp.js";
import "./number-coercion-CeAOJ7Po.js";
import "@aws/codewhisperer-streaming-client";
import "./index-C-CV5vnh.js";
import "axios";
import "axios-retry";
import "@mozilla/readability";
import "jsdom";
import "./types-DThkhnH-.js";
import { g as Se, m as we, a as Ne } from "./spec-agent-OdZ7esxm.js";
const H = v(C.Agent, "AgentController");
class Rt {
  workspace;
  model;
  // Queue of active executions
  executionQueue = new Array();
  // Queue of active executions
  chatAgentExecutionQueue = new Array();
  // Reference to currently active chat agent execution
  activeChatExecution;
  // Reference to currently active agent execution
  activeExecution;
  // Events emitted by the controller
  onEventSubscribers = /* @__PURE__ */ new Map();
  // Registry of active subagent executions (keyed by executionId)
  subAgentExecutions = /* @__PURE__ */ new Map();
  /**
   * Clean up the controller state.
   */
  cleanup() {
    this.activeChatExecution && this.isActive(this.activeChatExecution) && this.activeChatExecution.abort(), this.activeExecution && this.isActive(this.activeExecution) && this.activeExecution.abort(), this.subAgentExecutions.clear();
  }
  /**
   * Configures the agent controller with workspace and model settings
   * @param config - Configuration parameters including workspace and model settings
   */
  configure(e) {
    this.workspace = e.workspace, this.model = e.model;
  }
  /**
   * Updates the AI model configuration for future agent invocations
   * @param model - New model configuration to be used
   */
  updateModel(e) {
    this.model = e;
  }
  /**
   * Gets the currently active agent execution, if any
   * @returns The current active AgentExecution instance or undefined if no agent is active
   */
  getCurrentExecution() {
    return this.activeChatExecution || this.activeExecution;
  }
  /**
   * Gets the agent execution with the specified execution ID
   * @param executionId - The ID of the execution to find
   * @returns The matching AgentExecution instance or undefined if not found
   */
  getExecutionsForId(e) {
    const n = this.subAgentExecutions.get(e);
    if (n)
      return n;
    const i = this.chatAgentExecutionQueue.find((s) => s.executionId === e);
    return i || (this.activeExecution?.executionId === e ? this.activeExecution : this.executionQueue.find((s) => s.executionId === e));
  }
  /**
   * Registers a subagent execution so it can be looked up for response routing
   */
  registerSubAgentExecution(e) {
    this.subAgentExecutions.set(e.executionId, e);
  }
  /**
   * Unregisters a subagent execution when it completes
   */
  unregisterSubAgentExecution(e) {
    this.subAgentExecutions.delete(e);
  }
  isActive(e) {
    return e.isRunning() || e.isQueued() || e.isYielded();
  }
  /**
   * Gets the agentExecutions for a given chatSessionId
   * @returns The current active AgentExecution instance or undefined if no agent is active
   */
  getActiveExecutionsForChatSession(e) {
    const n = [], i = (r) => r.filter((s) => s.chatSessionId === e && this.isActive(s));
    return n.push(...i(this.chatAgentExecutionQueue)), n.push(...i(this.executionQueue)), e === this.activeExecution?.chatSessionId && n.push(this.activeExecution), n;
  }
  /**
   * Adds a new execution to the queue and processes it
   * @param execution - The agent execution to be added to the queue
   * @returns The added execution instance
   * @template In - The type of input parameters for the execution
   * @template Out - The type of output parameters for the execution
   */
  consumeNewExecution(e) {
    return this.getActiveExecutionsForChatSession(e.chatSessionId).length > 0 && (u.warn(`[agent-controller] Parallel execution detected in session ${e.chatSessionId}`), H.reportCountMetrics({ parallelExecutionDetected: 1 })), e.agentWorkflowType === K.ChatAgent ? (this.chatAgentExecutionQueue.push(e), this.activeChatExecution = e, e.invoke(), e) : (this.executionQueue.push(e), this.emitAgentEvent({
      type: "AgentExecutionQueued",
      executionId: e.executionId,
      agentWorkflowType: e.agentWorkflowType,
      autonomyMode: e.autonomyMode,
      chatSessionId: e.chatSessionId,
      title: e.simulatedTurnMessage,
      input: {
        data: e.input,
        documents: e.inputDocuments
      },
      isNewSession: e.isNewSession()
    }), this.progressModelQueue(), e);
  }
  /**
   * Reassesses the state of the execution queue and starts agent if possible
   */
  progressModelQueue() {
    if (u.info("[agent-controller] Progressing model queue", {
      activeExecution: !!this.activeExecution,
      queueSize: this.executionQueue.length
    }), H.reportCountMetrics({
      queueSize: this.executionQueue.length
    }), !this.activeExecution) {
      if (this.executionQueue.length === 0)
        return;
      this.activeExecution = this.executionQueue.shift(), this.activeExecution && this.activeExecution.isQueued() && this.activeExecution.invoke();
    }
    this.activeChatExecution && this.activeChatExecution.isCompleted() ? (this.activeChatExecution = void 0, this.chatAgentExecutionQueue.shift(), this.progressModelQueue()) : this.activeExecution && this.activeExecution.isCompleted() && (this.activeExecution = void 0, this.progressModelQueue());
  }
  /**
   * Emits an event to all subscribers without awaiting a response
   * @param event - The event to emit to all subscribers
   */
  emitAgentEvent(e) {
    e.type === "AgentExecutionAction" && (e.emittedAt = Date.now());
    for (const n of this.onEventSubscribers.values())
      n(e);
  }
  /**
   * Publishes an event to all subscribers, awaiting a response.
   * @param event - The event to emit to all subscribers
   */
  async publishAgentEvent(e) {
    e.type === "AgentExecutionAction" && (e.emittedAt = Date.now());
    for (const n of this.onEventSubscribers.values())
      await n(e);
  }
  /**
   * Subscribes to agent execution events
   * @param subscriber - The callback function to receive events
   * @returns Subscription ID used for unsubscribing
   */
  subscribeToEvents(e) {
    const n = w();
    return this.onEventSubscribers.set(n, e), n;
  }
  /**
   * Unsubscribes from agent execution events
   * @param id - The subscription ID to unsubscribe
   */
  unsubscribeFromEvents(e) {
    this.onEventSubscribers.delete(e);
  }
  /**
   * Triggers a new agent execution with the given input options
   * @param agent - The definition for invoking the agent
   * @returns The created agent execution instance
   * @template In - The type of input parameters
   * @template Out - The type of output parameters
   */
  trigger(e, n) {
    u.info(`[agent-controller] Triggered new agent: ${e.type} (autonomyMode=${e.autonomyMode})`);
    const [i, r] = [this.model, this.workspace];
    if (!i || !r)
      throw new J("Agent needs to be configured before invocation.");
    return this.consumeNewExecution(
      new X({
        workflowId: e.type,
        workspace: r,
        model: i,
        controller: this,
        input: e.input,
        definition: e,
        inputDocuments: e.inputDocuments,
        imageBase64Urls: e.imageBase64Urls,
        documentAttachments: e.documentAttachments,
        state: e.state,
        autonomyMode: e.autonomyMode,
        agentModeOverride: e.agentModeOverride,
        skipHooks: e.skipHooks,
        hookId: e.hookId,
        handler: (s) => e.invoke(s),
        executionId: e.executionId,
        chatSessionId: e.chatSessionId,
        simulatedTurnMessage: e.simulatedTurnMessage,
        titlePrompt: e.titlePrompt,
        title: e.title,
        hideSimulatedTurnMessage: e.hideSimulatedTurnMessage,
        signal: n
      })
    );
  }
}
function Oe(t = [], e) {
  if (t.length === 0 && !e)
    return;
  const n = "**/.kiro/specs/**/*.md", i = e && k(e, n), a = t.filter((p) => e !== p).filter((p) => k(p, n)).length > 0, c = {
    chat: 1,
    do: 1,
    spec: 1
  };
  if (i && (u.debug("Overriding weights with active spec file"), c.spec += 3), a && (u.debug("Overriding weights with open spec file"), c.spec += 0.4), !(c.chat === 1 && c.do === 1 && c.spec === 1))
    return c;
}
const A = /* @__PURE__ */ new Map(), ve = (t) => t.classification === "spec" ? {
  question: "I see you're working on a task that's optimized for spec sessions. Would you like to start a dedicated spec session for the best experience?",
  clarificationOptions: ["No", "Yes"]
} : {
  question: void 0,
  clarificationOptions: []
};
async function Ce(t) {
  u.info("[AgentIterator] Detecting intent");
  let e = {
    executionId: t.execution.executionId,
    actionId: w(),
    actionType: "intentClassification",
    actionState: I.Running,
    chatSessionId: t.chatSessionId
  };
  t.execution.emit({
    type: "AgentExecutionAction",
    ...e
  });
  try {
    if (!S(t.execution.input)) {
      u.info("[INTENT_DETECTION] Prompt input mode, skipping intent detection");
      return;
    }
    const n = t.execution.input.messages, i = se(n);
    if (!i) {
      u.warn("[INTENT_DETECTION] No user message found, skipping intent detection");
      return;
    }
    const r = Oe(t.openFiles, t.activeFile);
    r && u.info("[Agent Classifier] using weight overrides", r);
    const s = t.intentDetectionService.detectLocalIntent(i), a = await t.intentDetectionService.detectLLMIntent(
      i,
      t.context.messages,
      t.execution.abortController.signal,
      t.chatSessionId,
      t.continuationId
    ), c = t.intentDetectionService.finalizeIntent(s, a, r);
    c.classification === "ambiguous" && (c.classification = "chat");
    const p = ve(c);
    e = {
      ...e,
      actionState: p.question ? I.PendingAction : I.Success,
      intentResult: c,
      userInputOptions: p.clarificationOptions,
      userQuestion: p.question
    }, t.execution.emit({
      type: "AgentExecutionAction",
      ...e
    }), a?.usageSummaryEntry && t.execution.emit({
      type: "AgentExecutionSummarizeUsage",
      ...e,
      usageSummaryEntry: a.usageSummaryEntry
    }), u.info("[Agent Classifier] classification result", {
      intentResult: c,
      userInputOptions: p.clarificationOptions,
      userQuestion: p.question
    });
    const d = {
      actionEvent: e,
      intentResult: c,
      clarification: p,
      state: "computed"
    };
    A.set(t.execution.executionId, d);
  } catch (n) {
    u.error("[Agent Classifier] error during intent computation", n), e = {
      ...e,
      actionState: I.Canceled
    }, t.execution.emit({
      type: "AgentExecutionAction",
      ...e
    });
    const i = {
      actionEvent: e,
      intentResult: {
        localIntent: { chat: 1, do: 0, spec: 0 },
        llmIntent: { chat: 1, do: 0, spec: 0 },
        finalIntent: { chat: 1, do: 0, spec: 0 },
        classification: "chat"
      },
      clarification: { clarificationOptions: [] },
      state: "failed"
    };
    A.set(t.execution.executionId, i);
  }
}
async function Me(t) {
  u.info("[AgentIterator] Processing intent detection result");
  const e = A.get(t.execution.executionId);
  if (!e)
    return;
  if (e.state === "failed") {
    A.delete(t.execution.executionId);
    return;
  }
  if (e.state !== "computed")
    return;
  const { clarification: n, intentResult: i, actionEvent: r } = e;
  let s = { ...r };
  if (n.question)
    try {
      const a = await re(t, n.question);
      if (a.response && a.response.type === "answered") {
        const c = a.response.answer;
        i.classification = ae(i, c), i.finalIntent = ce(i.classification), i.clarificationQuestion = n.question, i.rawResponseText = a.response.answer, s = {
          ...s,
          userResponse: c
        }, u.info("[Agent Classifier] user clarification result", {
          intentResult: i
        });
      }
    } catch (a) {
      throw u.error("[Agent Classifier] error handling clarification", a), s = {
        ...s,
        actionState: I.Canceled,
        intentResult: i,
        userInputOptions: void 0,
        userQuestion: void 0
      }, t.execution.emit({
        type: "AgentExecutionAction",
        ...s
      }), A.delete(t.execution.executionId), a;
    }
  if (i.classification === "spec") {
    const a = ue();
    a.setSessionType && await a.setSessionType(t.chatSessionId, "spec");
    const c = Se();
    c.onModeChange && await c.onModeChange({
      sessionId: t.chatSessionId,
      workspacePaths: t.execution.workspace.listWorkspaceFolders().folders.map((p) => p.uri.fsPath),
      fromMode: "agent",
      toMode: "spec",
      reason: "Intent classification determined spec mode"
    });
  }
  return s = {
    ...s,
    actionState: I.Success,
    intentResult: i,
    userInputOptions: void 0,
    userQuestion: void 0
  }, t.execution.emit({
    type: "AgentExecutionAction",
    ...s
  }), A.delete(t.execution.executionId), i;
}
function _e(t) {
  return {
    autonomyMode: t.autonomyMode,
    hookId: t.hookId,
    imageBase64Urls: t.imageBase64Urls
  };
}
class Re extends G {
  /**
   * Creates a new NoUserMessagesError instance
   */
  constructor() {
    super("No user messages found in context");
  }
  /**
   * Required for error translation of session errors.
   * This is the string that will be shown the user if this error fails an execution.
   */
  get userFacingSessionErrorMessage() {
    return "At least one user message is required in chat history.";
  }
}
class ye extends G {
  /**
   * Required for error translation of session errors.
   * This is the string that will be shown the user if this error fails an execution.
   */
  get userFacingSessionErrorMessage() {
    return "Chat history must end in a user message.";
  }
}
async function De(t) {
  const { context: e } = t, n = [];
  for (const l of e.messages)
    l.role === "human" && !l.forcedRole && n.push(l);
  if (n.length === 0)
    throw new Re();
  const i = n[n.length - 1], r = i.entries.filter((l) => l.type === "text").map((l) => l.text).join(`

`), s = i.entries.filter((l) => l.type === "image").map((l) => l.image), a = i.entries.filter((l) => l.type === "documentAttachment").map((l) => ({ data: l.data, name: l.name, mimeType: l.mimeType })), c = S(t.execution.input) ? we(t.execution.input.messages) : [], p = await Ne(c), d = _e(t.execution), m = w();
  return {
    ...d,
    input: {
      userPrompt: r,
      previousMessages: p
    },
    chatSessionId: t.chatSessionId,
    inputDocuments: e.getWorkspaceFiles(),
    executionId: m,
    imageBase64Urls: s.length > 0 ? s : t.execution.imageBase64Urls,
    documentAttachments: a.length > 0 ? a : t.execution.documentAttachments,
    previousMessages: p,
    nested: !0,
    preservedContinuationId: t.continuationId
  };
}
async function Pe(t) {
  const e = await De(t);
  t.context = t.context.withNewMessage(
    h.fromAI().withForcedRole().withAgentInvoke(e.executionId)
  ), t.execution.saveState(t);
  const n = w();
  try {
    t.execution.emit({
      type: "AgentExecutionAction",
      executionId: t.execution.executionId,
      actionId: n,
      actionState: I.Running,
      actionType: "specAgent",
      output: { executionId: e.executionId },
      chatSessionId: e.chatSessionId
    }), t.execution.forceSuccess({
      status: B.Success,
      executionId: t.execution.executionId,
      result: {}
    });
    const i = new de(e);
    t.execution.getController().trigger(i, t.execution.abortController.signal);
  } catch (i) {
    u.error("Error executing Do agent: ", i);
  }
  return {};
}
function ke(t) {
  return u.info("[AgentIterator] Checking for intent overrides"), t.execution.agentModeOverride ? {
    intentClassificationOverride: t.execution.agentModeOverride
  } : {};
}
const E = v(C.Agent, "ChatAgentGraph"), be = P.Root({
  ...ee,
  execution: P()
});
let o = new ie(be);
o = o.addEdge(oe, "USER_HOOK_ON_PROMPTS");
o = o.addNode("USER_HOOK_ON_PROMPTS", async (t) => t.execution.skipHooks ? t : W(t, [q.UserPrompt]));
o = o.addEdge("USER_HOOK_ON_PROMPTS", "INTENT_OVERRIDE");
o = o.addNode(
  "INTENT_OVERRIDE",
  E.wrapTrace("IntentOverrideNode", (t) => {
    const e = {
      ...t
    };
    return ke(e);
  })
);
function Fe(t) {
  return t.intentClassificationOverride === "chat" || t.intentClassificationOverride === "do" ? "MODEL_INVOKE" : t.intentClassificationOverride === "spec" ? "INVOKE_SPEC_AGENT" : ["INTENT_DETECTION", "MODEL_INVOKE"];
}
o = o.addConditionalEdges("INTENT_OVERRIDE", Fe, [
  "INTENT_DETECTION",
  "INVOKE_SPEC_AGENT",
  "MODEL_INVOKE"
]);
o = o.addNode(
  "INTENT_DETECTION",
  E.wrapTrace("IntentDetectionNode", (t) => {
    Ce(t);
  })
);
o = o.addNode(
  "MODEL_INVOKE",
  E.wrapTrace("ModelInvokeNode", async (t) => {
    u.info("[AgentIterator] Parallel invoking agent"), t = await z(t), t.execution.state = t;
    let e = t.context;
    const n = t.execution.consumeQueuedUserMessage();
    if (n) {
      u.info("[ModelInvoke] Appending queued user message to context");
      const s = h.fromHuman().withText(n);
      e = e.withNewMessage(s);
    }
    const { responseStream: i, abortController: r } = await t.execution.modelStream2(
      e,
      t.execution.workspace.getChatTools()
    );
    return {
      context: e,
      responseStream: i,
      responseStreamAbortController: r
    };
  })
);
o = o.addNode(
  "ROUTE_INTENT",
  E.wrapTrace("RouteIntentNode", async (t) => {
    u.info("[AgentIterator] Synchronizing results");
    const e = await Me(t);
    if (!e || e.classification === "chat" || e.classification === "do")
      return new x({
        goto: "PROCESS_MODEL_STREAM"
      });
    if (!t.responseStreamAbortController)
      return u.error("[ChatAgent] A response stream was created without an abort controller"), new x({
        goto: f
      });
    if (u.info(`[ChatAgent] Detected non-chat intent: ${e.classification}. Switching agents.`), t.responseStreamAbortController.abort(), e.classification === "spec")
      return u.info("[ChatAgent] routing to Spec agent"), new x({
        goto: "INVOKE_SPEC_AGENT"
      });
    {
      u.error("[ChatAgent] Intent was not clarified with user");
      let n = t.context;
      return e.clarificationQuestion && (n = n.withNewMessage(h.fromAI().withText(e.clarificationQuestion))), e.rawResponseText && (n = n.withNewMessage(h.fromHuman().withText(e.rawResponseText))), new x({
        update: {
          context: n
        },
        goto: "INTENT_OVERRIDE"
      });
    }
  }),
  {
    ends: [f, "PROCESS_MODEL_STREAM", "INVOKE_SPEC_AGENT", "INTENT_OVERRIDE"]
  }
);
o = o.addEdge("INTENT_DETECTION", "ROUTE_INTENT");
o = o.addEdge("MODEL_INVOKE", "ROUTE_INTENT");
o = o.addNode("INVOKE_SPEC_AGENT", Pe).addEdge("INVOKE_SPEC_AGENT", f);
o = o.addNode(
  "PROCESS_MODEL_STREAM",
  E.wrapTrace("ProcessModelStreamNode", async (t) => {
    if (u.info("[ChatAgent] Processing model response stream"), !t.responseStream) {
      u.warn("[ChatAgent] tried to process stream that doesn't exist");
      return;
    }
    const e = t.responseStream;
    t = await z(t);
    const n = t.execution.workspace.getChatTools(), i = await te(t, e, n, E);
    return i.execution.state = i, i;
  })
);
o = o.addNode(
  "TURN_APPROVAL_CHECK",
  E.wrapTrace("TurnApprovalCheckNode", async (t) => {
    if (t.execution.autonomyMode !== Y.Supervised || (await le(t.execution.executionId)).length === 0)
      return t;
    const i = t.context.messages.findLast((c) => c.role === "bot")?.entries ?? [], { skip: r, currentFile: s } = pe(i, t.lastTurnToolFiles);
    if (r && s)
      return { ...t, lastTurnToolFiles: [s] };
    const { state: a } = await me(t);
    return { ...a, lastTurnToolFiles: s ? [s] : void 0 };
  })
);
o = o.addNode("FAILURE_DETECTION", E.wrapTrace("FailureDetectionNode", ge));
o = o.addNode("USER_INTERVENTION", E.wrapTrace("UserInterventionNode", he));
o = o.addEdge("PROCESS_MODEL_STREAM", "TURN_APPROVAL_CHECK");
o = o.addEdge("TURN_APPROVAL_CHECK", "SUMMARIZATION_DETECTION");
o = o.addConditionalEdges("FAILURE_DETECTION", Ee, ["USER_INTERVENTION", "MODEL_INVOKE"]);
o = o.addEdge("USER_INTERVENTION", "FAILURE_DETECTION");
o = o.addNode("SUMMARIZATION_DETECTION", fe);
o = o.addConditionalEdges("SUMMARIZATION_DETECTION", Ie, [
  "SUMMARIZATION_NODE",
  "FAILURE_DETECTION",
  "USER_HOOK_AGENT_STOP",
  "MODEL_INVOKE",
  f
]);
o = o.addNode("SUMMARIZATION_NODE", Te);
o = o.addConditionalEdges(
  "SUMMARIZATION_NODE",
  (t) => t.summarizationComplete ? (u.info("[ApprovalNode] Summarization complete - skipping hooks and ending"), f) : "USER_HOOK_AGENT_STOP",
  ["USER_HOOK_AGENT_STOP", f]
);
o = o.addNode("USER_HOOK_AGENT_STOP", async (t) => {
  if (t.execution.skipHooks)
    return t;
  if (t.onAgentStopHooksExecuted)
    return t.shouldRestartGraph = !1, t;
  {
    const e = await W(t, [q.AgentStop]), n = { ...t, ...e, onAgentStopHooksExecuted: !0 };
    return n.execution.state = n, n;
  }
});
o = o.addConditionalEdges(
  "USER_HOOK_AGENT_STOP",
  (t) => t.shouldRestartGraph ? "INTENT_OVERRIDE" : f,
  ["INTENT_OVERRIDE", f]
);
const Ue = o.compile();
var Le = Object.defineProperty, Qe = Object.getOwnPropertyDescriptor, He = (t, e, n, i) => {
  for (var r = Qe(e, n), s = t.length - 1, a; s >= 0; s--)
    (a = t[s]) && (r = a(e, n, r) || r);
  return r && Le(e, n, r), r;
};
const Ve = v(C.Agent, "ChatAgentGraph"), V = 300, Ke = 1e3;
function S(t) {
  return "messages" in t;
}
class Ge extends ne {
  constructor(e) {
    let n = "Chat Session";
    if (S(e.input)) {
      const i = [...e.input.messages].reverse().find((r) => r.role === "user");
      if (i)
        if (typeof i.content == "string")
          n = i.content;
        else {
          const { entireMessage: r } = L(i.content);
          n = r;
        }
    } else
      n = e.input.prompt;
    super({
      type: K.ChatAgent,
      ...e,
      titlePrompt: n
    });
  }
  /**
   * Builds the initial graph state based on the input type
   */
  async build(e) {
    return S(e.input) ? this.buildFromMessages(e) : this.buildFromPrompt(e);
  }
  async buildFromMessages(e) {
    if (e.input.messages.at(-1)?.role !== "user")
      throw new ye("Invalid Chat Agent invoke. Last message is not from role user");
    const n = e.input.messages.slice().reverse().find((d) => d.role === "user"), r = e.input.messagesFromExecutionId.some((d) => d.messageId === R), s = [
      ...await this.getSystemPromptMessages({
        includeFileTree: !r,
        workspace: e.workspace,
        machineId: e.workspace.machineId
      })
    ];
    if (e.input.messagesFromExecutionId.length > 0 && s.push(...e.input.messagesFromExecutionId), n) {
      let d = h.fromHuman();
      if (typeof n.content == "string")
        d = d.withText(n.content);
      else {
        const { entireMessage: m, imageBase64Urls: l, documentAttachments: N } = L(n.content);
        d = d.withText(m), l.length > 0 && (d = d.withImages(l.map((T) => ({ image: T })))), N.length > 0 && (d = d.withDocumentAttachments(
          N.map((T) => ({ data: T.data, name: T.name, mimeType: T.mimeType }))
        ));
      }
      s.push(d.withEnvironmentInfo());
    }
    s.at(-1)?.role === "bot" && s.push(h.fromHuman().withText("Now follow the instruction."));
    const a = F(), c = U() || "", p = e.getFastModelClient("intent-classification");
    return {
      agentIterationLimit: V,
      continuationId: this.preservedContinuationId ?? y(),
      context: s.reduce((d, m) => d.withNewMessage(m), _.empty()),
      chatSessionId: e.input.chatSessionId,
      intentDetectionService: new Q(
        p.modelId,
        p.modelClient
      ),
      openFiles: a,
      activeFile: c
    };
  }
  async buildFromPrompt(e) {
    const { prompt: n, previousMessages: i } = e.input, { inputDocuments: r, openedFiles: s, imageBase64Urls: a, documentAttachments: c, chatSessionId: p, workspace: d } = e, m = this.getSystemPromptMessagesWithImages(d, a, d.machineId), l = r.filter((g) => g.type === "file").map((g) => g.path);
    i?.some((g) => g.messageId === R) || m.push(...await D({ expandedPaths: l, openedFiles: s, workspace: d })), i?.some((g) => g.messageId === Ae) || m.push(...await xe(l, d)), i && (m.push(h.fromAI().withText("Understood.").withForcedRole()), m.push(...i));
    let O = h.fromHuman().withText(n).withEnvironmentInfo();
    c.length > 0 && (O = O.withDocumentAttachments(
      c.map((g) => ({ data: g.data, name: g.name, mimeType: g.mimeType }))
    )), m.push(O), m.at(-1)?.role === "bot" && m.push(h.fromHuman().withText("Now follow the instruction."));
    const Z = F(), $ = U() || "", M = e.getFastModelClient("intent-classification");
    return {
      agentIterationLimit: V,
      context: m.reduce((g, j) => g.withNewMessage(j), _.empty()),
      chatSessionId: p,
      continuationId: this.preservedContinuationId ?? y(),
      intentDetectionService: new Q(
        M.modelId,
        M.modelClient
      ),
      openFiles: Z,
      activeFile: $
    };
  }
  async getSystemPromptMessages(e) {
    const n = [
      h.fromHuman().withText(b(e.workspace).format({ machineId: e.machineId })).withForcedRole()
    ];
    return e.includeFileTree && n.push(...await D({ workspace: e.workspace })), n.push(h.fromAI().withText("I will follow these instructions.").withForcedRole()), n;
  }
  getSystemPromptMessagesWithImages(e, n, i) {
    return [
      h.fromHuman().withText(b(e).format({ machineId: i })).withImages(n.map((r) => ({ image: r }))).withForcedRole(),
      h.fromAI().withText("I will follow these instructions.").withForcedRole()
    ];
  }
  async invoke(e) {
    return await Ue.invoke(await e.getState(), {
      recursionLimit: Ke,
      signal: e.abortController.signal
    }), {
      status: B.Success,
      executionId: e.executionId,
      result: {}
    };
  }
}
He([
  Ve.Trace()
], Ge.prototype, "invoke");
export {
  Rt as A,
  Ge as C
};
//# sourceMappingURL=chat-agent-BAdndn_h.js.map
