// Force strict mode and setup for ESM
"use strict";
import "./chunk-2MWHVNSM.js";
import "./chunk-T4TZQJ7W.js";
import "./chunk-H6XPXXMH.js";
import "./chunk-5M6IDOMF.js";
import "./chunk-T2L47JJK.js";
import "./chunk-GPSKDNEE.js";
import "./chunk-X6N25LXS.js";
import "./chunk-E2UVIFI2.js";
import "./chunk-Q2YKNMLS.js";
import "./chunk-XU457J4V.js";
import "./chunk-VDDGDZMA.js";
import "./chunk-KHOVYUHX.js";
import "./chunk-SZRN75WQ.js";
import "./chunk-6PVPNMXU.js";
import "./chunk-VWYINXDB.js";
import "./chunk-CPBF7KYF.js";
import "./chunk-NABLFI57.js";
import "./chunk-QBUDF33N.js";
import "./chunk-LIZRAKPB.js";
import {
  buildSubagentPlanToolBlockedResult,
  isPlanLifecycleToolUnavailableInSubagent,
  isPlanRequiredTeammateContext
} from "./chunk-WHGVTP7Q.js";
import {
  getTeammateContext
} from "./chunk-6AM5D4ME.js";
import "./chunk-JCW2R7WC.js";
import "./chunk-57FIIFJN.js";
import "./chunk-HTO4JFDZ.js";
import "./chunk-XVNQMZ2I.js";
import "./chunk-FODK6UMO.js";
import "./chunk-GLNBDYUX.js";
import "./chunk-5YMPVE5X.js";
import "./chunk-JESCGQM3.js";
import "./chunk-TULTPXPE.js";
import "./chunk-EHPOFGVJ.js";
import "./chunk-DJ2GSRLV.js";
import "./chunk-5I5BM454.js";
import "./chunk-TMSMMRTT.js";
import "./chunk-VGC4I5JJ.js";
import "./chunk-4K56OJFJ.js";
import "./chunk-JYS55H6Z.js";
import "./chunk-A4UCTEB5.js";
import "./chunk-XWRJCPHC.js";
import "./chunk-QNLNLENL.js";
import "./chunk-6X4GWOPW.js";
import "./chunk-TYQMGACW.js";
import "./chunk-TYAMGABM.js";
import "./chunk-FCMNKVXT.js";
import "./chunk-IS2SBY6T.js";
import "./chunk-HTR4WV6U.js";
import "./chunk-M7WBGLYP.js";
import "./chunk-U7ZFW55U.js";
import "./chunk-NPQDJGKU.js";
import {
  BaseDeclarativeTool,
  BaseToolInvocation,
  ToolDisplayNames,
  ToolNames
} from "./chunk-YM3SZTH4.js";
import {
  createDebugLogger
} from "./chunk-OQB4EXO4.js";
import "./chunk-75DOP5OR.js";
import "./chunk-DMTGGOSA.js";
import "./chunk-YQ3U5MUC.js";
import "./chunk-THJNPLI4.js";
import {
  init_esbuild_shims
} from "./chunk-5O2XNYP6.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/core/src/tools/exitPlanMode.ts
init_esbuild_shims();
var debugLogger = createDebugLogger("EXIT_PLAN_MODE");
var exitPlanModeToolDescription = `Use this tool when you are in plan mode and have finished presenting your plan and are ready to code. This will prompt the user to exit plan mode.

## When to Use This Tool
IMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase - do NOT use this tool.

## Before Using This Tool
Ensure your plan is complete and unambiguous:
- If you have unresolved questions about requirements or approach, use AskUserQuestion first (in earlier phases)
- The plan parameter MUST contain your actual plan content \u2014 empty strings will be rejected
- Once your plan is finalized, use THIS tool to request approval

**Important:** Do NOT use AskUserQuestion to ask "Is this plan okay?" or "Should I proceed?" - that's exactly what THIS tool does. ExitPlanMode inherently requests user approval of your plan.

## Examples
1. Initial task: "Search for and understand the implementation of vim mode in the codebase" - Do not use the exit plan mode tool because you are not planning the implementation steps of a task.
2. Initial task: "Help me implement yank mode for vim" - Use the exit plan mode tool after you have finished planning the implementation steps of the task.
3. Initial task: "Add a new feature to handle user authentication" - If unsure about auth method (OAuth, JWT, etc.), use AskUserQuestion first, then use exit plan mode tool after clarifying the approach.
`;
var exitPlanModeToolSchemaData = {
  name: "exit_plan_mode",
  description: exitPlanModeToolDescription,
  parametersJsonSchema: {
    type: "object",
    properties: {
      plan: {
        type: "string",
        description: "The plan you came up with, that you want to run by the user for approval. Supports markdown. The plan should be pretty concise. Must contain your actual plan content \u2014 empty strings will be rejected."
      },
      originalRequest: {
        type: "string",
        description: "The original user request that prompted this plan. Restate it faithfully for a plan-required teammate leader."
      },
      researchSummary: {
        type: "string",
        description: "A brief summary of the investigation and key findings gathered during plan mode for a plan-required teammate leader."
      }
    },
    required: ["plan"],
    additionalProperties: false,
    $schema: "http://json-schema.org/draft-07/schema#"
  }
};
var ExitPlanModeToolInvocation = class extends BaseToolInvocation {
  constructor(config, params) {
    super(params);
    this.config = config;
  }
  static {
    __name(this, "ExitPlanModeToolInvocation");
  }
  approval;
  getDescription() {
    return "Plan:";
  }
  requiresUserInteraction() {
    return !isPlanRequiredTeammateContext() && !isPlanLifecycleToolUnavailableInSubagent(ToolNames.EXIT_PLAN_MODE);
  }
  async getDefaultPermission() {
    if (isPlanRequiredTeammateContext() || isPlanLifecycleToolUnavailableInSubagent(ToolNames.EXIT_PLAN_MODE)) {
      return "allow";
    }
    return this.config.getApprovalMode() === "plan" /* PLAN */ ? "ask" : "deny";
  }
  async getConfirmationDetails(abortSignal) {
    if (isPlanRequiredTeammateContext()) {
      return super.getConfirmationDetails(abortSignal);
    }
    if (isPlanLifecycleToolUnavailableInSubagent(ToolNames.EXIT_PLAN_MODE)) {
      return super.getConfirmationDetails(abortSignal);
    }
    if (this.config.getApprovalMode() !== "plan" /* PLAN */) {
      throw new Error("Cannot request plan approval outside plan mode.");
    }
    const snapshot = {
      plan: this.params.plan,
      approvalModeRevision: this.config.getApprovalModeRevision(),
      prePlanMode: this.config.getPrePlanMode()
    };
    this.approval = void 0;
    const details = {
      type: "plan",
      title: "Would you like to proceed?",
      hideAlwaysAllow: true,
      plan: snapshot.plan,
      prePlanMode: snapshot.prePlanMode,
      onConfirm: /* @__PURE__ */ __name(async (outcome) => {
        switch (outcome) {
          case "restore_previous" /* RestorePrevious */:
            this.approval = {
              snapshot,
              targetMode: snapshot.prePlanMode
            };
            break;
          case "proceed_always" /* ProceedAlways */:
            this.approval = {
              snapshot,
              targetMode: "auto-edit" /* AUTO_EDIT */
            };
            break;
          case "proceed_once" /* ProceedOnce */:
            this.approval = {
              snapshot,
              targetMode: "default" /* DEFAULT */
            };
            break;
          case "cancel" /* Cancel */:
            this.approval = void 0;
            break;
          default:
            this.approval = void 0;
            throw new Error(
              `Invalid plan approval outcome: ${String(outcome)}`
            );
        }
      }, "onConfirm")
    };
    return details;
  }
  async execute(signal) {
    if (isPlanLifecycleToolUnavailableInSubagent(ToolNames.EXIT_PLAN_MODE)) {
      return buildSubagentPlanToolBlockedResult(
        ToolNames.EXIT_PLAN_MODE,
        "ExitPlanModeTool",
        debugLogger
      );
    }
    const { plan, originalRequest, researchSummary } = this.params;
    if (isPlanRequiredTeammateContext()) {
      return this.executePlanRequiredTeammate(
        plan,
        originalRequest,
        researchSummary,
        signal
      );
    }
    const approval = this.approval;
    if (!approval) {
      return this.noActionResult(
        "Plan execution was not approved. Remaining in plan mode."
      );
    }
    const { snapshot, targetMode } = approval;
    if (signal.aborted) {
      return this.noActionResult(
        "Plan exit was cancelled. Remaining in plan mode."
      );
    }
    if (this.config.getApprovalMode() !== "plan" /* PLAN */ || this.config.getApprovalModeRevision() !== snapshot.approvalModeRevision) {
      return this.noActionResult(
        "Plan approval is stale because the approval mode changed. No action was taken."
      );
    }
    this.savePlanBestEffort(snapshot.plan);
    try {
      this.config.setApprovalMode(targetMode);
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      debugLogger.error(
        `[ExitPlanModeTool] Failed to set approval mode to "${targetMode}": ${message}`
      );
      return this.errorResult(
        `Failed to exit plan mode: ${message}. Remaining in plan mode.`
      );
    }
    return {
      llmContent: "User approved. You can now start coding. Start with updating your todo list if applicable.",
      returnDisplay: {
        type: "plan_summary",
        message: "User approved.",
        plan: snapshot.plan
      }
    };
  }
  async executePlanRequiredTeammate(plan, originalRequest, researchSummary, signal) {
    if (this.config.getApprovalMode() !== "plan" /* PLAN */) {
      return this.errorResult("Not in plan mode \u2014 no action taken.");
    }
    const approvalModeRevision = this.config.getApprovalModeRevision();
    const teammate = getTeammateContext();
    const manager = this.config.getTeamManager();
    if (!teammate || !manager) {
      return this.errorResult(
        "Plan-required teammate approval is unavailable in this context."
      );
    }
    let decision;
    try {
      decision = await manager.requestPlanApproval({
        teammateName: teammate.agentName,
        plan,
        originalRequest,
        researchSummary,
        signal
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      return this.errorResult(
        `Failed to request leader plan approval: ${message}`
      );
    }
    if (signal.aborted) {
      return this.noActionResult(
        "Leader plan approval was cancelled. Remaining in plan mode."
      );
    }
    if (this.config.getApprovalMode() !== "plan" /* PLAN */ || this.config.getApprovalModeRevision() !== approvalModeRevision) {
      return this.noActionResult(
        "Leader plan approval is stale because the approval mode changed. No action was taken."
      );
    }
    if (decision.action === "reject") {
      const feedback2 = decision.message ? `

Leader feedback:
${decision.message}` : "";
      const llmContent = "Leader rejected the plan. Revise the plan based on the feedback and call exit_plan_mode again." + feedback2;
      return {
        llmContent,
        returnDisplay: {
          type: "plan_summary",
          message: "Leader rejected the plan.",
          plan: `${plan.trimEnd()}

---

${llmContent}`,
          rejected: true
        }
      };
    }
    if (decision.targetMode === "plan" /* PLAN */) {
      return this.errorResult(
        "Leader approval did not select an execution mode. Remaining in plan mode."
      );
    }
    this.savePlanBestEffort(plan);
    try {
      this.config.setApprovalMode(decision.targetMode);
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      return this.errorResult(
        `Leader approved the plan, but failed to exit plan mode: ${message}.`
      );
    }
    const feedback = decision.message ? ` Leader note: ${decision.message}` : "";
    return {
      llmContent: `Leader approved.${feedback} You can now start coding. Start with updating your todo list if applicable.`,
      returnDisplay: {
        type: "plan_summary",
        message: "Leader approved.",
        plan
      }
    };
  }
  savePlanBestEffort(plan) {
    try {
      this.config.savePlan(plan);
    } catch (error) {
      debugLogger.warn(
        `[ExitPlanModeTool] Failed to save plan to disk: ${error instanceof Error ? error.message : String(error)}`
      );
    }
  }
  errorResult(message) {
    return {
      llmContent: message,
      returnDisplay: message,
      error: { message }
    };
  }
  noActionResult(message) {
    return {
      llmContent: message,
      returnDisplay: message
    };
  }
};
var ExitPlanModeTool = class _ExitPlanModeTool extends BaseDeclarativeTool {
  constructor(config) {
    super(
      _ExitPlanModeTool.Name,
      ToolDisplayNames.EXIT_PLAN_MODE,
      exitPlanModeToolDescription,
      "think" /* Think */,
      exitPlanModeToolSchemaData.parametersJsonSchema,
      true,
      false,
      true,
      // Plan mode tells the model to call exit_plan_mode directly, so its schema
      // must always be declared instead of deferred (issue #5210).
      true
    );
    this.config = config;
  }
  static {
    __name(this, "ExitPlanModeTool");
  }
  static Name = ToolNames.EXIT_PLAN_MODE;
  validateToolParams(params) {
    if (!params.plan || typeof params.plan !== "string" || params.plan.trim() === "") {
      return 'Parameter "plan" must be a non-empty string.';
    }
    return null;
  }
  createInvocation(params) {
    return new ExitPlanModeToolInvocation(this.config, params);
  }
};
export {
  ExitPlanModeTool
};
/**
 * @license
 * Copyright 2025 Qwen
 * SPDX-License-Identifier: Apache-2.0
 */
