import { b } from "./telemetry-Bf0GI6nJ.js";
import { d as k, O as E } from "./shared-types-CIxCt9tj.js";
import { M as O, b as W } from "./token-monitor-QTYxqQ8j.js";
import { C as f, g as P } from "./context-chat-message-DzjJbTBD.js";
import { i as U } from "./stream-CtDBTPgX.js";
import "./base-BCJFoMV_.js";
import "uuid";
import "./string-BZO3_EzG.js";
import * as z from "crypto";
import { s as H } from "./prompt-DuC9mWRH.js";
import "os";
import "dedent";
import "vscode-uri";
import "path";
import "zod";
import { Annotation as a, StateGraph as V, START as j, END as N } from "@langchain/langgraph";
import { a as l } from "./logger-CTb8_yz9.js";
import { a as K } from "./token-estimator-B45EKs9J.js";
import { i as Y } from "./model-config-BdfVU6dY.js";
import { AsyncStream as Q } from "./async-stream/index.js";
import { U as q } from "./unknown-error-7JAvTvbU.js";
import { a as J } from "./message-analyzer-BAqw8PNp.js";
import { A as X, g as Z, a as ee } from "./autonomy-mode-CooE4oAK.js";
import { i as te } from "./prompts-DfcXHzAI.js";
const F = {
  // The agent execution is a object representing the current state of this execution
  // This is connected to the execution log
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  execution: a(),
  // Input that the graph was invoked with
  inputParams: a(),
  // Current execution context for the agent
  context: a(),
  // Open and active files for intent detection weighting
  openFiles: a(),
  activeFile: a(),
  // Output that can be stored by nodes in the graph
  output: a(),
  // Iteration tracking for multi-turn flows
  agentIterationLimit: a(),
  agentIterationNumber: a(),
  agentPerIterationFilesModifiedMap: a(),
  // If there is an active stream going on, these types are used to handle it and route actions
  agentRawResponseMessageId: a(),
  agentRawResponse: a(),
  agentActionStream: a(),
  agentActionRoutingToolIndex: a(),
  agentActionRoutingToolNextIndex: a(),
  agentActionRoutingActionId: a(),
  agentStreamAbortCallback: a(),
  chatSessionId: a(),
  // Intent detection - stores message classifications and current intent
  intentDetectionService: a(),
  responseStream: a(),
  responseStreamAbortController: a(),
  intentClassificationOverride: a(),
  // Metering
  continuationId: a(),
  specTaskId: a(),
  // Failure intervention
  skipFailureIntervention: a(),
  interventionResult: a(),
  // Hook restart flag
  shouldRestartGraph: a(),
  onAgentStopHooksExecuted: a(),
  // Array of tool names that should skip pre-tool-use hooks on their next invocation
  // Used to allow tool execution after hook interception (prevents infinite hook loops)
  skipHooksForNextToolCall: a(),
  // Tracks the file targeted by the previous turn's edits for skipping yield on consecutive same-file edits
  lastTurnToolFiles: a(),
  // Auto-summarization state
  contextUsagePercentage: a(),
  needsSummarization: a(),
  summarizationComplete: a(),
  summarizationActionId: a(),
  summarizationResult: a()
};
function je(e) {
  return {
    inputParams: e.inputParams,
    context: e.context,
    output: e.output,
    agentIterationLimit: e.agentIterationLimit,
    agentIterationNumber: e.agentIterationNumber
  };
}
const Ke = a.Root(F);
var $ = /* @__PURE__ */ ((e) => (e.Success = "success", e.Fault = "fault", e.UserAborted = "user-aborted", e))($ || {});
function G() {
  return l.debug("[createContinuationId] Starting new vibe session."), z.randomUUID();
}
class ne {
  type;
  executionId;
  // Input to this definition, if there is any
  input;
  // Graph state to build on top of
  state;
  // Starting execution status, this defaults to "queued" but can be another status if requested
  status;
  // Initially provided documents for context
  inputDocuments;
  // Initially provided images
  imageBase64Urls;
  // Initially provided document attachments (PDF, DOCX, etc.)
  documentAttachments;
  autonomyMode;
  agentModeOverride;
  skipHooks;
  agentMode;
  hookId;
  chatSessionId;
  isNewSession;
  preservedContinuationId;
  nested;
  simulatedTurnMessage;
  hideSimulatedTurnMessage;
  titlePrompt;
  title;
  constructor({
    type: t,
    input: i,
    state: s,
    status: n,
    inputDocuments: r,
    imageBase64Urls: o,
    documentAttachments: c,
    autonomyMode: p,
    agentModeOverride: w,
    skipHooks: y,
    agentMode: d,
    hookId: A,
    executionId: x,
    chatSessionId: S,
    preservedContinuationId: R,
    nested: g,
    simulatedTurnMessage: C,
    titlePrompt: u,
    title: m,
    isNewSession: h,
    hideSimulatedTurnMessage: I
  }) {
    this.type = t, this.input = i, this.state = s, this.inputDocuments = r || [], this.imageBase64Urls = o || [], this.documentAttachments = c || [], this.status = n || X.Queued, this.autonomyMode = p || Z(), this.agentModeOverride = w, this.skipHooks = y, this.agentMode = d, this.hookId = A, this.executionId = x, this.chatSessionId = S, this.preservedContinuationId = R, this.nested = g, this.simulatedTurnMessage = C, this.titlePrompt = u, this.title = m, this.isNewSession = h, this.hideSimulatedTurnMessage = I;
  }
  /**
   * Builds a graph state for a given execution if we are running it for the first time
   * Override this to provide custom build of agent context
   */
  build(t) {
    return {
      context: O.empty(),
      continuationId: this.preservedContinuationId ?? G()
    };
  }
}
const M = b(k.Agent, "Steering"), oe = 10, ie = 1e4;
function se(e) {
  const t = e.filter((i) => i.role === "bot").length;
  return t > 0 && t % oe === 0;
}
function re(e, t) {
  try {
    const i = e.execution.getModelId(), s = W(i), r = new K().estimateContextTokens(e.context, i), o = Math.ceil(t.length / 4), c = s * 0.9, p = r + o > c;
    return p && l.warn(
      `[Steering] Adding steering would exceed context window: ${r} + ${o} > ${c} (90% of ${s})`
    ), p;
  } catch (i) {
    return l.error("[Steering] Error checking context window limit:", i), !1;
  }
}
function ae(e, t) {
  const i = [];
  let s = 39;
  for (const r of e) {
    const o = r.displayName.length + r.content.length + 4, c = s + o;
    if (c <= t)
      i.push(r), s = c;
    else
      break;
  }
  const n = e.length - i.length;
  return n > 0 && l.info(`[Steering] Excluded ${n} documents to stay within ${t} char budget`), { included: i, excluded: n };
}
async function ce(e) {
  try {
    const t = await e.execution.workspace.getSteeringDocuments();
    if (t.documents.length === 0)
      return e;
    const { included: i, excluded: s } = ae(t.documents, ie);
    if (i.length === 0)
      return l.warn("[Steering] No documents fit within budget, skipping refresh"), e;
    const n = `<steering-reminder>${i.map((o) => `

${o.displayName}:
${o.content}`).join(`

`)}</steering-reminder>`;
    if (re(e, n))
      return l.warn("[Steering] Skipping refresh to avoid exceeding context window"), M.reportCountMetrics({
        SteeringSkippedContextWindow: 1
      }), e;
    l.info(
      `[Steering] Refreshing ${i.length}/${t.documents.length} steering documents, (${n.length} characters)${s > 0 ? `, ${s} excluded` : ""}`
    ), M.reportCountMetrics({
      SteeringRefreshedDocuments: i.length,
      SteeringRefreshedCharacters: n.length,
      SteeringRefreshCount: 1,
      SteeringExcludedDocuments: s
    });
    const r = {
      ...e,
      context: e.context.withExtendedMessage(
        new f("human", [
          {
            type: "text",
            text: n
          }
        ])
      )
    };
    return r.execution.state = r, r.execution.saveState(r), r;
  } catch (t) {
    return l.error("[Steering] Error during steering refresh", t), M.reportCountMetrics({
      SteeringRefreshError: 1
    }), l.debug("[Steering] Refresh error details", {
      executionId: e.execution.executionId,
      error: t instanceof Error ? t.message : String(t)
    }), e;
  }
}
const ue = M.wrapTrace("PopulateSteeringNode", de);
async function de(e) {
  l.info(`[Steering] Populating steering for execution ${e.execution.executionId}`);
  const t = (await Promise.all(
    e.context.getWorkspaceFiles().map((o) => e.execution.workspace.resolveRelativePath(o.path))
  )).filter((o) => o !== void 0);
  l.info(`[Steering] ExistingFiles: ${t.map((o) => o.path).join(", ")} in ${e.execution.executionId}`);
  const i = e.context.getWorkspaceSteering().map((o) => o.id), { documents: s } = await e.execution.workspace.getSteeringDocuments({
    files: t.length > 0 ? t : void 0
  });
  l.debug("[Steering] Found documents: ", { ids: s.map((o) => o.id) });
  const n = s.filter((o) => !i.includes(o.id));
  l.debug("[Steering] Net new documents: ", { default: n.map((o) => o.id) }), n.length > 0 && M.reportCountMetrics({
    SteeringAdded: n.length,
    SteeringAlreadyInContext: s.length - n.length
  });
  const r = n.map((o) => ({
    type: "document",
    document: {
      type: "steering",
      id: o.id,
      displayName: o.displayName,
      content: o.content,
      scope: o.scope
    }
  }));
  if (n.length > 0) {
    e.execution.emit({
      type: "AgentExecutionAction",
      executionId: e.execution.executionId,
      actionId: n.map(({ id: c }) => c).join(","),
      actionType: "steering",
      actionState: E.Success,
      endTime: Date.now(),
      input: {
        documents: n.map((c) => c.id)
      }
    });
    const o = {
      ...e,
      context: e.context.withExtendedMessage(new f("human", r))
    };
    o.execution.state = o, o.execution.saveState(o), e = o;
  }
  if (Y("steeringReminders") && se(e.context.messages))
    try {
      return await ce(e);
    } catch (o) {
      l.error("[Steering] Failed to refresh steering documents", o), M.reportCountMetrics({
        SteeringRefreshError: 1
      });
    }
  return e;
}
async function le(e, t, i, s) {
  let n, r, o, c = 0, p = "", w, y, d = "", A, x;
  const S = P();
  e = { ...e, context: e.context.withNewMessage(f.fromAI(S)) };
  const R = [];
  try {
    for await (const u of t)
      if (n ? n = n.concat(u) : n = u, typeof n.content == "string" && p !== n.content && (x && d && (e.execution.emit({
        type: "AgentExecutionAction",
        executionId: e.execution.executionId,
        actionId: x,
        actionState: E.Success,
        actionType: "reasoning",
        output: { message: d }
      }), x = void 0), e.execution.emit({
        type: "AgentExecutionAction",
        executionId: e.execution.executionId,
        actionId: S,
        actionState: E.Running,
        actionType: "say",
        output: { message: n.content }
      }), p = n.content), U(u)) {
        const m = u.tool_call_chunks;
        if (m && m.length === 1 && m[0] && m[0].id && m[0].name) {
          x && d && (e.execution.emit({
            type: "AgentExecutionAction",
            executionId: e.execution.executionId,
            actionId: x,
            actionState: E.Success,
            actionType: "reasoning",
            output: { message: d }
          }), x = void 0);
          const I = i.find((B) => B.id === m[0].name);
          if (!I || !("call" in I))
            continue;
          e.execution.shouldBlockToolInvocation() && await e.execution.waitForYieldRelease(), c = m[0].index ?? c;
          const D = new Q();
          r = D;
          const L = m[0].id;
          o = s.callWithTrace(
            "AsyncToolCallStart",
            () => I.call(e, L, S, D)
          ), R.push(o);
        }
        for (const I of u.tool_call_chunks ?? [])
          r?.send(I);
        const { additional_kwargs: h } = u;
        h.stop && (c++, r?.close()), h.usageSummaryEntry && (w = u.additional_kwargs.usageSummaryEntry), h.contextUsagePercentage && (y = h.contextUsagePercentage), h.reasoningContent && (x || (x = P()), d += h.reasoningContent, e.execution.emit({
          type: "AgentExecutionAction",
          executionId: e.execution.executionId,
          actionId: x,
          actionState: E.Running,
          actionType: "reasoning",
          output: { message: d }
        })), h.reasoningSignature && (A = h.reasoningSignature);
      }
    r?.tryClose();
  } catch (u) {
    r?.error(u instanceof Error ? u : new q(String(u)));
  }
  p !== "" && e.execution.emit({
    type: "AgentExecutionAction",
    executionId: e.execution.executionId,
    actionId: S,
    actionState: E.Success,
    actionType: "say",
    output: { message: p }
  }), x && d && e.execution.emit({
    type: "AgentExecutionAction",
    executionId: e.execution.executionId,
    actionId: x,
    actionState: E.Success,
    actionType: "reasoning",
    output: { message: d }
  }), w && e.execution.emit({
    type: "AgentExecutionSummarizeUsage",
    executionId: e.execution.executionId,
    usageSummaryEntry: w
  }), y !== void 0 && e.execution.emit({
    type: "AgentExecutionContextUsageUpdate",
    executionId: e.execution.executionId,
    contextUsagePercentage: y,
    chatSessionId: e.execution.chatSessionId
  });
  let g = f.fromAI(S);
  if (n && typeof n.content == "string" && (g = g.withText(n.content)), d && (g = g.withReasoningContent(d, A, e.execution.getModelId())), n && U(n)) {
    for (const u of n.tool_calls ?? [])
      g = g.withToolUse({
        id: u.id ?? "",
        args: u.args,
        name: u.name
      });
    for (const u of n.invalid_tool_calls ?? [])
      u.name && u.id && (g = g.withToolUse({
        id: u.id,
        args: { invalidArgs: u.args },
        name: u.name
      }));
  }
  const C = f.generateResponseMessageId(S);
  for (const u of R) {
    const m = await u;
    e = {
      ...e,
      ...m,
      context: e.context
    };
    const h = m.context.getMessageById(C);
    h && (e.context = e.context.withMergedMessage(h));
    const I = m.context.getMessageById(S);
    I && (g = g.mergedWith(I));
  }
  return J(g), {
    ...e,
    contextUsagePercentage: y,
    // Store for graph to use in CHECK_SUMMARIZATION node
    context: e.context.withReplacedMessageById(S, g)
  };
}
const v = b(k.Agent, "SubAgentGraph");
function ge(e) {
  l.info("[SubAgentGraph] Reminding agent to use subagentResponse tool");
  const t = f.fromHuman().withText(
    "You must use the subagentResponse tool to provide your final response. Please call subagentResponse with your response text and files (or parts of files) you think are important for the parent context."
  );
  return {
    ...e,
    context: e.context.withNewMessage(t)
  };
}
let T = new V(F);
T = T.addNode(
  "MODEL_INVOKE",
  v.wrapTrace("ModelInvokeNode", async (e) => {
    e = await ue(e), e.execution.state = e;
    const t = e.context, i = [...e.execution.workspace.getSpecAgentTools(), ...e.execution.workspace.getSubAgentTools()], { responseStream: s } = await e.execution.modelStream2(t, i), n = await le(e, s, i, v);
    return n.execution.state = n, n;
  })
).addNode("REMIND_RESPONSE", v.wrapTrace("RemindResponseNode", ge)).addEdge(j, "MODEL_INVOKE").addEdge("REMIND_RESPONSE", "MODEL_INVOKE");
T = T.addConditionalEdges(
  "MODEL_INVOKE",
  (e) => {
    const t = e.context.messages.at(-1);
    return t?.role === "tool" ? t.entries.some(
      (s) => s.type === "toolUseResponse" && s.name === "subagentResponse"
    ) ? N : "MODEL_INVOKE" : t?.role === "bot" && !t.entries.some((s) => s.type === "toolUse") ? "REMIND_RESPONSE" : N;
  },
  [N, "MODEL_INVOKE", "REMIND_RESPONSE"]
);
const me = T.compile(), _ = "tooluse_fileTree";
async function pe(e) {
  if (te(e.workspace))
    return [];
  const t = {
    id: _,
    args: { path: "." },
    name: "listDirectory"
  };
  return [
    // We can't have the same message id. The restore from execution logic dedupes based on message id.
    f.fromAI(_ + "__toolUse").withToolUse(t),
    f.fromTool(_).withDocument(await xe(e)).withToolUseResponse({
      ...t,
      message: "I will list the files in current directory.",
      success: !0
    })
  ];
}
async function xe({
  expandedPaths: e,
  openedFiles: t,
  target: i,
  workspace: s,
  disableDirectorySummaries: n
}) {
  const r = e ?? [], o = t ?? [], c = i ?? 500, p = (await Promise.all(r.map((d) => s.resolveRelativePath(d)))).filter((d) => d !== void 0), w = (await Promise.all(o.map((d) => s.resolveRelativePath(d.path)))).filter((d) => d !== void 0), y = await H({
    paths: [...p, ...w],
    workspace: s,
    target: c,
    disableDirectorySummaries: n
  });
  return {
    document: {
      type: "fileTree",
      target: c,
      expandedPaths: r,
      openedFiles: o,
      staticDirectoryView: y
    }
  };
}
var he = Object.defineProperty, fe = Object.getOwnPropertyDescriptor, Se = (e, t, i, s) => {
  for (var n = fe(t, i), r = e.length - 1, o; r >= 0; r--)
    (o = e[r]) && (n = o(t, i, n) || n);
  return n && he(t, i, n), n;
};
const Ie = b(k.Agent, "SubAgentGraph"), we = 300, ye = 1e3;
class Ee extends ne {
  /**
   * Creates a new instance of SubAgentDefinition
   */
  constructor(t) {
    super({
      type: ee.SubAgent,
      ...t,
      titlePrompt: t.input.prompt
    });
  }
  /**
   * Returns initial state for storing intermediate graph state
   */
  async build({
    input: { prompt: t, systemPrompt: i, contextMessages: s },
    imageBase64Urls: n,
    chatSessionId: r,
    workspace: o
  }) {
    const c = this.getSystemPromptMessages(n, i, o.machineId);
    return c.push(f.fromHuman().withText(t).withEnvironmentInfo()), c.push(...await pe({ workspace: o })), s && s.length > 0 && c.push(...s), {
      agentIterationLimit: we,
      context: c.reduce((p, w) => p.withNewMessage(w), O.empty()),
      chatSessionId: r,
      continuationId: this.preservedContinuationId ?? G()
    };
  }
  /**
   * Builds system prompt messages for the sub-agent
   */
  getSystemPromptMessages(t, i, s) {
    const n = `${i}
<current_context>Machine ID: ${s}</current_context>`;
    return [
      f.fromHuman().withText(n).withImages(t.map((r) => ({ image: r }))).withForcedRole(),
      f.fromAI().withText("I will follow these instructions.").withForcedRole()
    ];
  }
  async invoke(t) {
    await me.invoke(await t.getState(), {
      recursionLimit: ye,
      signal: t.abortController.signal
    });
    const { response: i, files: s } = this.extractSubagentResponse(t);
    return {
      status: $.Success,
      executionId: t.executionId,
      result: {
        response: i,
        files: s
      }
    };
  }
  /**
   * Extracts the final assistant message from the execution context
   * @deprecated Use extractSubagentResponse instead
   */
  extractAssistantMessage(t) {
    const i = t.state?.context;
    if (!i)
      return "";
    const s = i.messages;
    if (s.length === 0)
      return "";
    const n = [...s].reverse().find((c) => c.role === "bot");
    return n ? n.entries.filter((c) => c.type === "text").map((c) => c.text).join("") : "";
  }
  /**
   * Extracts the response from the subagentResponse tool in the execution context.
   * Falls back to empty response if the tool was not called.
   */
  extractSubagentResponse(t) {
    const i = t.state?.context;
    if (!i)
      return { response: "", files: [] };
    const s = [...i.messages].reverse().find((o) => o.role === "bot");
    if (!s)
      return { response: "", files: [] };
    const n = s.entries.find(
      (o) => o.type === "toolUse" && o.name === "subagentResponse"
    );
    if (!n || n.type !== "toolUse")
      return { response: this.extractAssistantMessage(t), files: [] };
    const r = n.args;
    return {
      response: r.response,
      files: r.files ?? []
    };
  }
}
Se([
  Ie.Trace()
], Ee.prototype, "invoke");
export {
  $ as A,
  ne as E,
  _ as F,
  Ee as S,
  F as a,
  Ke as b,
  G as c,
  le as d,
  je as e,
  pe as g,
  ue as p
};
//# sourceMappingURL=sub-agent-BpZpYDp-.js.map
