import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
import {
  buildExecutionReminder,
  createExecutionStateFromPlan,
  createPlanCapability,
  extractPlanTodoItems,
  isPlanModeSafeCommand,
  markCompletedPlanSteps,
  restoreExecutionState
} from "../../../chunks/chunk-SW6G4XW2.js";
import "../../../chunks/chunk-D7NAXU7F.js";
import "../../../chunks/chunk-TG2EQLX2.js";

// builtin/extensions/plan-mode/index.ts
var SESSION_METADATA_KEY = "planModeEnabled";
var EXECUTION_METADATA_KEY = "executionState";
var planModeEnabled = false;
var executionMode = false;
function toPlanTodoItems(state) {
  return state.steps.map((step) => ({
    step: step.id,
    text: step.title,
    completed: step.status === "completed"
  }));
}
function planModeExtension(ctx) {
  const capability = createPlanCapability();
  function readPersistedPlanMode() {
    return ctx.getSessionMetadata()?.[SESSION_METADATA_KEY] === true;
  }
  function readExecutionState() {
    return restoreExecutionState(ctx.getSessionMetadata()?.[EXECUTION_METADATA_KEY] ?? ctx.getExecutionState());
  }
  function writeExecutionState(state) {
    const next = state ?? restoreExecutionState(null);
    ctx.setSessionMetadata(EXECUTION_METADATA_KEY, next);
    ctx.setExecutionState(next);
    ctx.setExecutionReminder(buildExecutionReminder(next) ?? void 0);
    return next;
  }
  function updateStatus() {
    const state = readExecutionState();
    if (executionMode && state.steps.length > 0) {
      const completed = state.steps.filter((step) => step.status === "completed").length;
      ctx.ui.notify(`\u{1F4CB} Plan: ${completed}/${state.steps.length} completed`, "info");
    } else if (planModeEnabled) {
      ctx.ui.notify("\u23F8\uFE0F Plan mode active (read-only)", "info");
    }
  }
  function applyPlanModeState(enabled, forcePromptInjection = false) {
    planModeEnabled = enabled;
    if (!enabled) {
      executionMode = false;
    }
    ctx.setPlanMode(enabled, { forcePromptInjection });
  }
  function togglePlanMode() {
    planModeEnabled = !planModeEnabled;
    executionMode = false;
    writeExecutionState(null);
    ctx.setSessionMetadata(SESSION_METADATA_KEY, planModeEnabled);
    applyPlanModeState(planModeEnabled, true);
    ctx.ui.notify(
      planModeEnabled ? `Plan mode enabled. Available tools: ${ctx.getActiveTools().join(", ")}` : "Plan mode disabled. Full access restored."
    );
    updateStatus();
  }
  ctx.registerCommand({
    path: capability.commands?.[0]?.path ?? ["tools", "plan"],
    description: capability.commands?.[0]?.description ?? "Toggle plan mode (read-only exploration)",
    handler: async () => {
      togglePlanMode();
    }
  });
  ctx.registerShortcut("ctrl+alt+p", {
    description: "Toggle plan mode",
    handler: async () => {
      togglePlanMode();
    }
  });
  ctx.on("tool:call", async (event) => {
    if (!planModeEnabled || event.toolName !== "bash") return;
    const command = event.args?.command;
    if (command && !isPlanModeSafeCommand(command)) {
      ctx.ui.notify(
        `Plan mode: Command blocked (not allowlisted). Use /plan to disable plan mode first.
Command: ${command}`,
        "error"
      );
      return { block: true, reason: `Plan mode: command "${command}" is not in the allowlist. Disable plan mode with /plan to run this command.` };
    }
  });
  ctx.on("agent:start", async () => {
    const persisted = readPersistedPlanMode();
    applyPlanModeState(persisted);
    writeExecutionState(readExecutionState());
  });
  ctx.on("session:changed", async () => {
    const enabled = readPersistedPlanMode();
    applyPlanModeState(enabled, enabled);
    writeExecutionState(readExecutionState());
  });
  ctx.on("turn:end", async (event) => {
    const state = readExecutionState();
    if (!executionMode || state.steps.length === 0) return;
    const message = event.message;
    if (message?.role !== "assistant" || !Array.isArray(message.content)) return;
    const text = message.content.filter((item) => item.type === "text").map((item) => item.text).join("\n");
    const todoItems = toPlanTodoItems(state);
    if (markCompletedPlanSteps(text, todoItems) <= 0) return;
    const nextState = createExecutionStateFromPlan(todoItems);
    writeExecutionState(nextState);
    updateStatus();
  });
  ctx.on("agent:end", async (event) => {
    const state = readExecutionState();
    if (executionMode && state.steps.length > 0) {
      if (state.steps.every((step) => step.status === "completed")) {
        const completedList = state.steps.map((step) => `\u2713 ${step.title}`).join("\n");
        ctx.ui.notify(`**Plan Complete!** \u2713

${completedList}`, "info");
        executionMode = false;
        writeExecutionState(null);
      }
      return;
    }
    if (!planModeEnabled || !ctx.hasUI) return;
    const messages = event.messages || [];
    const lastAssistant = [...messages].reverse().find(
      (message) => message.role === "assistant" && Array.isArray(message.content)
    );
    if (!lastAssistant) return;
    const text = lastAssistant.content.filter((item) => item.type === "text").map((item) => item.text).join("\n");
    const extracted = extractPlanTodoItems(text);
    if (extracted.length === 0) return;
    const extractedState = writeExecutionState(createExecutionStateFromPlan(extracted));
    const todoListText = extractedState.steps.map((step) => `${step.id}. \u2610 ${step.title}`).join("\n");
    ctx.ui.notify(`**Plan Steps (${extractedState.steps.length}):**
${todoListText}`, "info");
    const choice = await ctx.ui.select("Plan mode - what next?", [
      "Execute the plan (track progress)",
      "Stay in plan mode",
      "Refine the plan"
    ]);
    if (choice?.startsWith("Execute")) {
      planModeEnabled = false;
      executionMode = extractedState.steps.length > 0;
      ctx.setSessionMetadata(SESSION_METADATA_KEY, false);
      ctx.setPlanMode(false);
      updateStatus();
      const execMessage = extractedState.steps.length > 0 ? `Execute the plan. Start with: ${extractedState.steps[0].title}. Mark completed steps with [DONE:n] in your response.` : "Execute the plan you just created.";
      ctx.sendUserMessage(execMessage);
      return;
    }
    if (choice === "Refine the plan") {
      const refinement = await ctx.ui.editor("Refine the plan:", "");
      if (refinement?.trim()) {
        ctx.sendUserMessage(refinement.trim());
      }
    }
  });
  ctx.log("Plan mode extension loaded");
}
export {
  planModeExtension as default
};
