import { defineCommand, useCache, useConfig, useAnalytics } from '@kb-labs/sdk';
import { bootstrapAgentSDK, SessionManager, PlanDocumentService, createSessionMemoryBridge, SpecModeHandler, createCoreToolPack } from '@kb-labs/agent-core';
import { AgentSDK } from '@kb-labs/agent-sdk';
import { createDefaultResponseRequirementsSelector } from '@kb-labs/agent-runtime';
import { IncrementalTraceWriter } from '@kb-labs/agent-tracing';
import { createToolRegistry } from '@kb-labs/agent-tools';
import { promises } from 'fs';

// src/cli/commands/run.ts

// src/cli/ui/event-renderer.ts
var CSI = "\x1B[";
var RESET = "\x1B[0m";
var color = {
  // Status colors
  success: (t) => `${CSI}32m${t}${RESET}`,
  error: (t) => `${CSI}31m${t}${RESET}`,
  warning: (t) => `${CSI}33m${t}${RESET}`,
  info: (t) => `${CSI}36m${t}${RESET}`,
  // UI colors
  dim: (t) => `${CSI}90m${t}${RESET}`,
  bold: (t) => `${CSI}1m${t}${RESET}`,
  accent: (t) => `${CSI}38;5;99m${t}${RESET}`,
  // Purple - orchestrator
  primary: (t) => `${CSI}38;5;39m${t}${RESET}`,
  // Blue - agent
  highlight: (t) => `${CSI}38;5;51m${t}${RESET}`,
  // Cyan - tools
  secondary: (t) => `${CSI}38;5;208m${t}${RESET}`
  // Orange - subtask
};
var box = {
  topLeft: "\u250C",
  topRight: "\u2510",
  bottomLeft: "\u2514",
  bottomRight: "\u2518",
  horizontal: "\u2500",
  vertical: "\u2502",
  leftT: "\u251C"};
var symbols = {
  success: color.success("\u2713"),
  error: color.error("\u2717"),
  thinking: "\u25C6",
  tool: "\u2699",
  memory: "\u{1F4BE}",
  subtask: "\u25C8",
  agent: "\u25CF"
};
function formatDuration(ms) {
  if (ms < 1e3) {
    return `${ms}ms`;
  }
  if (ms < 6e4) {
    return `${(ms / 1e3).toFixed(1)}s`;
  }
  return `${Math.floor(ms / 6e4)}m ${Math.floor(ms % 6e4 / 1e3)}s`;
}
function formatPath(path, maxLen = 40) {
  if (path.length <= maxLen) {
    return path;
  }
  const parts = path.split("/");
  if (parts.length <= 2) {
    return "..." + path.slice(-maxLen + 3);
  }
  return `.../${parts.slice(-2).join("/")}`;
}
function formatBudget(event) {
  const data = event.data;
  const used = typeof data.budgetUsedTokens === "number" ? data.budgetUsedTokens : null;
  const remaining = typeof data.budgetRemainingTokens === "number" ? data.budgetRemainingTokens : null;
  const total = typeof data.budgetTotalTokens === "number" ? data.budgetTotalTokens : null;
  if (used === null && remaining === null && total === null) {
    return null;
  }
  const fmt = (value) => value === null ? "?" : value.toLocaleString("en-US");
  return `Budget ${fmt(used)} used / ${fmt(total)} total (${fmt(remaining)} left)`;
}
function renderBoxTop(title, colorFn, width = 60) {
  const titleLen = title.length + 2;
  const leftPad = 2;
  const rightPad = width - leftPad - titleLen - 2;
  return colorFn(
    `${box.topLeft}${box.horizontal.repeat(leftPad)} ${title} ${box.horizontal.repeat(Math.max(0, rightPad))}${box.topRight}`
  );
}
function renderBoxBottom(colorFn, width = 60) {
  return colorFn(`${box.bottomLeft}${box.horizontal.repeat(width - 2)}${box.bottomRight}`);
}
function renderBoxLine(content, colorFn) {
  return `${colorFn(box.vertical)} ${content}`;
}
function createEventRenderer(options) {
  const { verbose = true, showToolOutput = true, showLLMContent = false, showDebug = false } = options;
  const state = {
    currentSubtask: null,
    agentActive: false,
    indentLevel: 0
  };
  return (event) => {
    switch (event.type) {
      // ═══════════════════════════════════════════════════════════════════
      // SUBTASK LEVEL
      // ═══════════════════════════════════════════════════════════════════
      case "subtask:start": {
        state.currentSubtask = {
          id: event.data.subtaskId,
          index: event.data.index,
          total: event.data.total
        };
        state.indentLevel = 1;
        const subtaskNum = `${event.data.index + 1}/${event.data.total}`;
        console.log(color.accent(box.vertical));
        console.log(
          color.accent(`${box.leftT}${box.horizontal}`) + renderBoxTop(`SUBTASK ${subtaskNum}`, color.secondary, 50)
        );
        console.log(
          color.accent(box.vertical) + " " + renderBoxLine(
            `${symbols.subtask} ${event.data.description.slice(0, 45)}${event.data.description.length > 45 ? "..." : ""}`,
            color.secondary
          )
        );
        console.log(color.accent(box.vertical) + " " + color.secondary(box.vertical));
        break;
      }
      case "subtask:end": {
        const status = event.data.success ? color.success(`${symbols.success} Done`) : color.error(`${symbols.error} Failed`);
        console.log(color.accent(box.vertical) + " " + color.secondary(box.vertical));
        console.log(
          color.accent(box.vertical) + " " + renderBoxLine(status, color.secondary)
        );
        console.log(
          color.accent(box.vertical) + " " + renderBoxBottom(color.secondary, 50)
        );
        state.currentSubtask = null;
        state.indentLevel = 0;
        break;
      }
      // ═══════════════════════════════════════════════════════════════════
      // AGENT LEVEL (nested under subtask or standalone)
      // ═══════════════════════════════════════════════════════════════════
      case "agent:start": {
        state.agentActive = true;
        const linePrefix = state.currentSubtask ? color.accent(box.vertical) + " " + color.secondary(box.vertical) + " " : "";
        console.log(linePrefix);
        console.log(linePrefix + renderBoxTop(`AGENT [${event.data.tier}]`, color.primary, 45));
        console.log(linePrefix + renderBoxLine(
          `${symbols.agent} ${event.data.task.slice(0, 40)}${event.data.task.length > 40 ? "..." : ""}`,
          color.primary
        ));
        console.log(linePrefix + renderBoxLine(
          color.dim(`Tools: ${event.data.toolCount} | Max iterations: ${event.data.maxIterations}`),
          color.primary
        ));
        state.indentLevel = state.currentSubtask ? 3 : 1;
        break;
      }
      case "agent:end": {
        const linePrefix = state.currentSubtask ? color.accent(box.vertical) + " " + color.secondary(box.vertical) + " " : "";
        const status = event.data.success ? color.success(`${symbols.success} Success`) : color.error(`${symbols.error} Failed`);
        console.log(linePrefix + color.primary(box.vertical));
        console.log(linePrefix + renderBoxLine(
          `${status} ${color.dim(`(${formatDuration(event.data.durationMs)}, ${event.data.tokensUsed} tokens)`)}`,
          color.primary
        ));
        if (event.data.summary) {
          console.log(linePrefix + color.primary(box.vertical));
          console.log(linePrefix + renderBoxLine(
            color.bold("\u{1F4CB} Result:"),
            color.primary
          ));
          const summaryLines = event.data.summary.split("\n");
          for (const line of summaryLines) {
            if (line.trim()) {
              const words = line.split(" ");
              let currentLine = "";
              for (const word of words) {
                if (currentLine.length + word.length > 75) {
                  if (currentLine) {
                    console.log(linePrefix + renderBoxLine(`   ${currentLine}`, color.primary));
                  }
                  currentLine = word;
                } else {
                  currentLine = currentLine ? `${currentLine} ${word}` : word;
                }
              }
              if (currentLine) {
                console.log(linePrefix + renderBoxLine(`   ${currentLine}`, color.primary));
              }
            }
          }
        }
        if (event.data.filesModified.length > 0 || event.data.filesCreated.length > 0) {
          const files = [...event.data.filesCreated, ...event.data.filesModified];
          console.log(linePrefix + renderBoxLine(
            color.dim(`Files: ${files.slice(0, 3).map((f) => formatPath(f, 20)).join(", ")}${files.length > 3 ? ` +${files.length - 3}` : ""}`),
            color.primary
          ));
        }
        console.log(linePrefix + renderBoxBottom(color.primary, 45));
        state.agentActive = false;
        state.indentLevel = state.currentSubtask ? 1 : 0;
        break;
      }
      case "agent:error": {
        const linePrefix = getLinePrefix(state);
        console.log(linePrefix + renderBoxLine(
          `${symbols.error} ${color.error("Error:")} ${event.data.error.slice(0, 50)}`,
          color.primary
        ));
        break;
      }
      // ═══════════════════════════════════════════════════════════════════
      // ITERATION & LLM (inside agent box)
      // ═══════════════════════════════════════════════════════════════════
      case "iteration:start": {
        const linePrefix = getLinePrefix(state);
        if (verbose) {
          console.log(linePrefix + color.primary(box.vertical));
          console.log(linePrefix + renderBoxLine(
            color.dim(`\u2500\u2500\u2500 Iteration ${event.data.iteration}/${event.data.maxIterations} \u2500\u2500\u2500`),
            color.primary
          ));
        }
        break;
      }
      case "llm:start": {
        const linePrefix = getLinePrefix(state);
        if (verbose) {
          const iterLabel = event.data.iteration !== void 0 ? color.dim(` #${event.data.iteration}`) : "";
          const msgLabel = showDebug ? color.dim(` [${event.data.messageCount} msgs, ${event.data.toolCount ?? 0} tools, ${event.data.systemPromptChars ?? 0} sys chars]`) : "";
          process.stdout.write(linePrefix + renderBoxLine(
            `${color.accent(symbols.thinking)} ${color.dim("Thinking...")}${iterLabel}${msgLabel}`,
            color.primary
          ));
        }
        break;
      }
      case "llm:end": {
        if (verbose) {
          process.stdout.write(`\r`);
          const linePrefix = getLinePrefix(state);
          const stopLabel = event.data.stopReason ? `, stop=${event.data.stopReason}` : "";
          console.log(linePrefix + renderBoxLine(
            `${color.accent(symbols.thinking)} Thought ${color.dim(`(${formatDuration(event.data.durationMs)}, ${event.data.tokensUsed} tok${stopLabel})`)}`,
            color.primary
          ));
          if (event.data.content) {
            const maxLen = showDebug ? 2e3 : showLLMContent ? 500 : 150;
            const content = event.data.content.slice(0, maxLen).replace(/\n/g, " ").trim();
            if (content) {
              console.log(linePrefix + renderBoxLine(
                color.dim(`  \u{1F4AD} "${content}${event.data.content.length > maxLen ? "..." : ""}"`),
                color.primary
              ));
            }
          }
        }
        break;
      }
      // ═══════════════════════════════════════════════════════════════════
      // TOOL EXECUTION (inside agent, compact format)
      // ═══════════════════════════════════════════════════════════════════
      case "tool:start": {
        const linePrefix = getLinePrefix(state);
        const toolName = event.data.toolName;
        const meta = event.data.metadata;
        let details = "";
        if (showDebug) {
          const inputObj = event.data.input;
          if (inputObj && Object.keys(inputObj).length > 0) {
            const raw = JSON.stringify(inputObj);
            const maxLen = 200;
            details = ` ${color.dim(raw.slice(0, maxLen) + (raw.length > maxLen ? "..." : ""))}`;
          }
        } else if (meta?.filePath) {
          details = ` ${color.dim(formatPath(meta.filePath, 30))}`;
        } else if (meta?.query) {
          details = ` ${color.dim(`"${meta.query.slice(0, 25)}${meta.query.length > 25 ? "..." : ""}"`)}`;
        } else if (meta?.command) {
          details = ` ${color.dim(`$ ${meta.command.slice(0, 25)}`)}`;
        }
        process.stdout.write(linePrefix + renderBoxLine(
          `${color.highlight(symbols.tool)} ${color.highlight(toolName)}${details}`,
          color.primary
        ));
        break;
      }
      case "tool:end": {
        const status = event.data.success ? ` ${symbols.success}` : ` ${symbols.error}`;
        process.stdout.write(`${status} ${color.dim(formatDuration(event.data.durationMs))}
`);
        if (showToolOutput) {
          const linePrefix = getLinePrefix(state);
          const meta = event.data.metadata;
          const output = event.data.output;
          if (output && verbose) {
            const maxOutputLen = showDebug ? 1e3 : 200;
            if (showDebug) {
              const truncated = output.slice(0, maxOutputLen);
              const lines = truncated.split("\n");
              for (const line of lines) {
                if (line.trim()) {
                  console.log(linePrefix + renderBoxLine(
                    color.dim(`    \u{1F4C4} ${line}`),
                    color.primary
                  ));
                }
              }
              if (output.length > maxOutputLen) {
                console.log(linePrefix + renderBoxLine(
                  color.dim(`    \u{1F4C4} ... (${output.length - maxOutputLen} more chars)`),
                  color.primary
                ));
              }
            } else {
              const cleanOutput = output.slice(0, maxOutputLen).replace(/\n/g, " ").replace(/\s+/g, " ").trim();
              if (cleanOutput && cleanOutput.length > 10) {
                console.log(linePrefix + renderBoxLine(
                  color.dim(`    \u{1F4C4} ${cleanOutput}${output.length > maxOutputLen ? "..." : ""}`),
                  color.primary
                ));
              }
            }
          }
          if (meta?.summary && !output) {
            console.log(linePrefix + renderBoxLine(
              color.dim(`    \u2514\u2500 ${meta.summary.slice(0, 80)}`),
              color.primary
            ));
          }
        }
        break;
      }
      case "tool:error": {
        process.stdout.write(` ${symbols.error}
`);
        const linePrefix = getLinePrefix(state);
        console.log(linePrefix + renderBoxLine(
          color.error(`    \u2514\u2500 ${event.data.error.slice(0, 50)}`),
          color.primary
        ));
        break;
      }
      // ═══════════════════════════════════════════════════════════════════
      // MEMORY & PROGRESS (compact notifications)
      // ═══════════════════════════════════════════════════════════════════
      case "memory:write": {
        if (verbose) {
          const linePrefix = getLinePrefix(state);
          console.log(linePrefix + renderBoxLine(
            color.dim(`${symbols.memory} Saved ${event.data.entryType} to ${event.data.target}`),
            color.primary
          ));
        }
        break;
      }
      case "progress:update": {
        const budgetLine = formatBudget(event);
        const phase = event.data.phase || "progress";
        const progress = Math.max(0, Math.min(100, Math.round(event.data.progress || 0)));
        const message = event.data.message || "";
        if (verbose) {
          const linePrefix = getLinePrefix(state);
          const main = `[${phase}] ${progress}%${message ? ` - ${message}` : ""}`;
          console.log(linePrefix + renderBoxLine(color.info(main), color.primary));
          if (budgetLine) {
            console.log(linePrefix + renderBoxLine(color.dim(`    ${budgetLine}`), color.primary));
          }
        } else if (message && (phase === "plan" || phase === "spec") && (progress === 100 || progress === 5)) {
          const budgetSuffix = budgetLine ? ` | ${budgetLine}` : "";
          console.log(`${color.info(`[${phase}]`)} ${message}${budgetSuffix}`);
        }
        break;
      }
      case "status:change": {
        const budgetLine = formatBudget(event);
        if (verbose && event.data.message) {
          const linePrefix = getLinePrefix(state);
          console.log(linePrefix + renderBoxLine(
            color.info(`Status: ${event.data.status}${event.data.message ? ` - ${event.data.message}` : ""}`),
            color.primary
          ));
          if (budgetLine) {
            console.log(linePrefix + renderBoxLine(color.dim(`    ${budgetLine}`), color.primary));
          }
          if (event.data.status === "waiting" && event.sessionId) {
            const sid = event.sessionId;
            console.log(linePrefix + renderBoxLine(color.dim(`  To approve:  kb agent run --session-id=${sid} --approve`), color.primary));
            console.log(linePrefix + renderBoxLine(color.dim(`  To execute:  kb agent run --session-id=${sid}`), color.primary));
          }
        }
        if (!verbose && (event.data.status === "done" || event.data.status === "error")) {
          const budgetSuffix = budgetLine ? ` (${budgetLine})` : "";
          console.log(
            event.data.status === "done" ? `${symbols.success} ${event.data.message}${budgetSuffix}` : `${symbols.error} ${event.data.message}${budgetSuffix}`
          );
        }
        break;
      }
      case "middleware:decision": {
        if (verbose) {
          const linePrefix = getLinePrefix(state);
          const decisionIcons = {
            soft_warning: "\u26A0",
            hard_stop: "\u{1F6D1}",
            trimmed: "\u2702",
            loop_detected: "\u{1F501}",
            stuck: "\u23F8",
            summarized: "\u{1F4DD}"
          };
          const icon = decisionIcons[event.data.decision] ?? "\xB7";
          console.log(linePrefix + renderBoxLine(
            color.dim(`  ${icon} [${event.data.middleware}] ${event.data.decision}`),
            color.primary
          ));
        }
        break;
      }
      case "llm:debug": {
        if (!showDebug) {
          break;
        }
        const linePrefix = getLinePrefix(state);
        const iterLabel = event.data.iteration !== void 0 ? ` (iter #${event.data.iteration})` : "";
        console.log(linePrefix + renderBoxLine(
          color.dim(`  \u2500\u2500\u2500 System Prompt${iterLabel} \u2500\u2500\u2500`),
          color.primary
        ));
        for (const line of event.data.systemPrompt.split("\n")) {
          console.log(linePrefix + renderBoxLine(color.dim(`  ${line}`), color.primary));
        }
        console.log(linePrefix + renderBoxLine(color.dim("  \u2500\u2500\u2500 Messages \u2500\u2500\u2500"), color.primary));
        for (const m of event.data.messages) {
          const roleLabel = `[${m.role}]`;
          const content = m.content;
          const lines = content.split("\n");
          const firstLine = `${roleLabel} ${lines[0] ?? ""}`;
          console.log(linePrefix + renderBoxLine(color.dim(`  ${firstLine}`), color.primary));
          for (const line of lines.slice(1)) {
            console.log(linePrefix + renderBoxLine(color.dim(`      ${line}`), color.primary));
          }
        }
        console.log(linePrefix + renderBoxLine(color.dim("  \u2500\u2500\u2500 End Prompt \u2500\u2500\u2500"), color.primary));
        break;
      }
    }
  };
  function getLinePrefix(state2) {
    if (state2.currentSubtask && state2.agentActive) {
      return color.accent(box.vertical) + " " + color.secondary(box.vertical) + " ";
    }
    if (state2.currentSubtask) {
      return color.accent(box.vertical) + " " + color.secondary(box.vertical) + " ";
    }
    if (state2.agentActive) {
      return "";
    }
    return "";
  }
}
function createMinimalRenderer() {
  return createEventRenderer({
    verbose: false,
    showToolOutput: false,
    showLLMContent: false
  });
}
function createDetailedRenderer() {
  return createEventRenderer({
    verbose: true,
    showToolOutput: true,
    showLLMContent: true
  });
}
function createDebugRenderer() {
  return createEventRenderer({
    verbose: true,
    showToolOutput: true,
    showLLMContent: true,
    showDebug: true
  });
}

// src/cli/commands/run.ts
bootstrapAgentSDK();
function parseBooleanFlag(value, defaultValue) {
  if (typeof value === "boolean") {
    return value;
  }
  if (typeof value === "string") {
    const normalized = value.trim().toLowerCase();
    if (["true", "1", "yes", "y", "on"].includes(normalized)) {
      return true;
    }
    if (["false", "0", "no", "n", "off"].includes(normalized)) {
      return false;
    }
  }
  if (typeof value === "number") {
    return value !== 0;
  }
  return defaultValue;
}
var run_default = defineCommand({
  id: "agent:run",
  description: "Execute a task with autonomous agent (orchestrator + child agents)",
  handler: {
    async execute(ctx, input) {
      const flags = "flags" in input && typeof input.flags === "object" && input.flags !== null ? input.flags : input;
      const {
        task,
        workingDir = ctx.cwd || process.cwd(),
        maxIterations = 200,
        temperature = 0.1,
        verbose: verboseRaw = true,
        quiet: quietRaw = false,
        detailed: detailedRaw = false,
        sessionId,
        tier = "medium",
        mode = "execute",
        complexity,
        files,
        trace,
        approve: approveRaw = false,
        execute: executeRaw = false,
        spec: specRaw = false,
        "dry-run": dryRunRaw = false,
        debug: debugRaw = false,
        timeout: timeoutSeconds,
        budget: budgetOverride,
        json: jsonOutput = false
      } = flags;
      const verbose = parseBooleanFlag(verboseRaw, true);
      const quiet = parseBooleanFlag(quietRaw, false);
      const detailed = parseBooleanFlag(detailedRaw, false);
      const approve = parseBooleanFlag(approveRaw, false);
      const executeAfterPlan = parseBooleanFlag(executeRaw, false);
      const spec = parseBooleanFlag(specRaw, false);
      const dryRun = parseBooleanFlag(dryRunRaw, false);
      const debug = parseBooleanFlag(debugRaw, false);
      const timeoutSecs = typeof timeoutSeconds === "number" && timeoutSeconds > 0 ? timeoutSeconds : void 0;
      const abortController = timeoutSecs !== void 0 ? new AbortController() : void 0;
      let timeoutHandle;
      if (abortController && timeoutSecs !== void 0) {
        timeoutHandle = setTimeout(() => {
          abortController.abort(
            new Error(`Agent execution timed out after ${timeoutSecs}s (--timeout=${timeoutSecs})`)
          );
        }, timeoutSecs * 1e3);
        timeoutHandle.unref?.();
      }
      const clearTimeout_ = () => {
        if (timeoutHandle !== void 0) {
          clearTimeout(timeoutHandle);
          timeoutHandle = void 0;
        }
      };
      if (!task) {
        if (approve && sessionId) {
          const sessionManager = new SessionManager(workingDir || ctx.cwd || process.cwd());
          const planPath = sessionManager.getSessionPlanPath(sessionId);
          try {
            const raw = await promises.readFile(planPath, "utf-8");
            const plan = JSON.parse(raw);
            if (plan.status !== "draft") {
              ctx.ui?.warn?.(`Plan is not in draft state (current: ${plan.status}). Nothing to approve.`);
              clearTimeout_();
              return { exitCode: 1 };
            }
            const approvedAt = (/* @__PURE__ */ new Date()).toISOString();
            const approvedPlan = { ...plan, status: "approved", approvedAt, approvalComment: "Approved via CLI --approve", updatedAt: approvedAt };
            await promises.writeFile(planPath, JSON.stringify(approvedPlan, null, 2), "utf-8");
            const planDocumentService = new PlanDocumentService(workingDir || ctx.cwd || process.cwd());
            const planDocPath = planDocumentService.getPlanPath(plan);
            await planDocumentService.appendExecutionLog(planDocPath, `- ${approvedAt}: Plan approved via CLI (--approve).`).catch(() => {
            });
            ctx.ui?.success?.(`Plan approved: ${approvedPlan.id} (session: ${sessionId})`);
            ctx.ui?.info?.(`Ready to execute: kb agent run --session-id=${sessionId}`);
            clearTimeout_();
            return { exitCode: 0, sessionId };
          } catch {
            ctx.ui?.error?.(`No plan found for session: ${sessionId}`);
            clearTimeout_();
            return { exitCode: 1 };
          }
        }
        ctx.ui?.error?.("Error: --task is required");
        clearTimeout_();
        return { exitCode: 1 };
      }
      let modeConfig;
      if (mode !== "execute") {
        modeConfig = { mode };
        if (mode === "plan") {
          modeConfig.context = { mode: "plan", task, complexity };
        } else if (mode === "edit") {
          modeConfig.context = { mode: "edit", task, targetFiles: files || [], dryRun };
        } else if (mode === "debug") {
          modeConfig.context = { mode: "debug", task, traceFile: trace, relevantFiles: files || [] };
        }
      }
      let eventRenderer;
      if (jsonOutput) {
        eventRenderer = () => {
        };
      } else if (quiet) {
        eventRenderer = createMinimalRenderer();
      } else if (debug) {
        eventRenderer = createDebugRenderer();
      } else if (detailed) {
        eventRenderer = createDetailedRenderer();
      } else {
        eventRenderer = createEventRenderer({
          verbose,
          showToolOutput: true,
          showLLMContent: false
        });
      }
      try {
        const runId = `run-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
        const sessionManager = new SessionManager(workingDir);
        let effectiveSessionId = sessionId;
        if (!effectiveSessionId) {
          const createdSession = await sessionManager.createSession({
            mode,
            task,
            agentId: "cli-agent"
          });
          effectiveSessionId = createdSession.id;
        } else {
          const existing = await sessionManager.loadSession(effectiveSessionId);
          if (!existing) {
            const createdSession = await sessionManager.createSession({
              mode,
              task,
              agentId: "cli-agent",
              sessionId: effectiveSessionId
            });
            effectiveSessionId = createdSession.id;
          }
        }
        await sessionManager.createUserTurn(effectiveSessionId, task, runId);
        const filesRead = /* @__PURE__ */ new Set();
        const filesReadHash = /* @__PURE__ */ new Map();
        const sessionMemory = createSessionMemoryBridge(workingDir, effectiveSessionId);
        const responseRequirementsSelector = createDefaultResponseRequirementsSelector();
        const toolRegistry = createToolRegistry({
          workingDir,
          currentTask: task,
          sessionId: effectiveSessionId,
          verbose: false,
          // Disable tool registry verbose - we have event renderer
          cache: useCache(),
          filesRead,
          filesReadHash,
          sessionMemory,
          responseRequirementsResolver: async ({ task: activeTask, kernel }) => responseRequirementsSelector.select({
            state: kernel,
            messages: [],
            task: activeTask ?? task
          })
        });
        const agentsConfig = await useConfig();
        const effectiveBudget = typeof budgetOverride === "number" && budgetOverride > 0 ? { ...agentsConfig?.tokenBudget ?? {}, enabled: true, maxTokens: budgetOverride } : agentsConfig?.tokenBudget;
        const analytics = useAnalytics() ?? null;
        const taskId = `task-${Date.now()}`;
        const tracer = new IncrementalTraceWriter(taskId);
        if (spec && effectiveSessionId && sessionId) {
          const planPath = sessionManager.getSessionPlanPath(effectiveSessionId);
          try {
            const planData = JSON.parse(await promises.readFile(planPath, "utf-8"));
            if (planData.status === "approved" || planData.status === "spec_ready") {
              ctx.ui?.info?.(`Found approved plan: ${planData.id} (${planData.phases.length} phases). Generating spec directly...`);
              let pendingSessionWrite2 = Promise.resolve();
              const specEventCallback = (event) => {
                tracer.trace(event);
                eventRenderer(event);
                pendingSessionWrite2 = pendingSessionWrite2.then(async () => {
                  await sessionManager.addEvent(effectiveSessionId, {
                    ...event,
                    sessionId: effectiveSessionId,
                    runId,
                    metadata: {
                      ...event["metadata"],
                      sessionId: effectiveSessionId,
                      runId,
                      workingDir
                    }
                  });
                }).catch((error) => {
                  const message = error instanceof Error ? error.message : String(error);
                  console.warn(`[agent:run] Failed to persist spec event: ${message}`);
                });
              };
              const specConfig = {
                workingDir,
                maxIterations: 40,
                temperature: 0.1,
                sessionId: effectiveSessionId,
                tier,
                analytics,
                tokenBudget: effectiveBudget,
                onEvent: specEventCallback,
                abortSignal: abortController?.signal
              };
              const specHandler = new SpecModeHandler();
              const specResult = await specHandler.execute(planData, specConfig, toolRegistry);
              await pendingSessionWrite2;
              await tracer.finalize();
              const detailedTrace2 = tracer.getEntries();
              if (detailedTrace2.length > 0) {
                await sessionManager.storeTraceArtifacts(effectiveSessionId, runId, detailedTrace2);
              }
              if (specResult.success) {
                ctx.ui?.success?.(`Spec generated: ${specResult.spec?.id} (${specResult.spec?.sections.length || 0} sections, ${specResult.spec?.sections.reduce((s, sec) => s + sec.changes.length, 0) || 0} changes)`);
              } else {
                ctx.ui?.warn?.(`Spec generation failed: ${specResult.summary}`);
              }
              const specSucceeded = specResult.success;
              clearTimeout_();
              return {
                exitCode: specSucceeded ? 0 : 1,
                sessionId: effectiveSessionId,
                result: {
                  success: specSucceeded,
                  summary: specResult.summary,
                  filesCreated: specResult.filesCreated,
                  filesModified: specResult.filesModified,
                  filesRead: specResult.filesRead,
                  iterations: specResult.iterations,
                  tokensUsed: specResult.tokensUsed
                }
              };
            }
          } catch {
          }
        }
        let pendingSessionWrite = Promise.resolve();
        let persistedEventCount = 0;
        const compositeEventCallback = (event) => {
          tracer.trace(event);
          eventRenderer(event);
          pendingSessionWrite = pendingSessionWrite.then(async () => {
            await sessionManager.addEvent(effectiveSessionId, {
              ...event,
              sessionId: effectiveSessionId,
              runId
            });
            persistedEventCount += 1;
          }).catch((error) => {
            const message = error instanceof Error ? error.message : String(error);
            console.warn(`[agent:run] Failed to persist event: ${message}`);
          });
        };
        const config = {
          workingDir,
          maxIterations,
          temperature,
          sessionId: effectiveSessionId,
          tier,
          analytics,
          tokenBudget: agentsConfig?.tokenBudget,
          mode: modeConfig,
          onEvent: compositeEventCallback,
          debug,
          abortSignal: abortController?.signal
        };
        if (timeoutSecs !== void 0 && !quiet) {
          ctx.ui?.info?.(`\u23F1  Timeout active: agent will abort after ${timeoutSecs}s (--timeout=${timeoutSecs})`);
        }
        const sdk = new AgentSDK();
        sdk.register(createCoreToolPack(toolRegistry));
        const runner = sdk.createRunner(config);
        let result = await runner.execute(task);
        clearTimeout_();
        await pendingSessionWrite;
        if (persistedEventCount === 0 && result.summary?.trim()) {
          const now = (/* @__PURE__ */ new Date()).toISOString();
          const agentId = `agent-${runId}`;
          const baseMetadata = { sessionId: effectiveSessionId, runId, workingDir };
          await sessionManager.addEvent(effectiveSessionId, {
            type: "agent:start",
            timestamp: now,
            sessionId: effectiveSessionId,
            agentId,
            runId,
            data: { task, tier, maxIterations, toolCount: 0 },
            metadata: baseMetadata
          });
          await sessionManager.addEvent(effectiveSessionId, {
            type: "llm:end",
            timestamp: now,
            sessionId: effectiveSessionId,
            agentId,
            runId,
            data: {
              content: result.summary,
              hasToolCalls: false,
              tokensUsed: 0,
              durationMs: 0,
              stopReason: "no_tool_calls"
            },
            metadata: baseMetadata
          });
          await sessionManager.addEvent(effectiveSessionId, {
            type: "agent:end",
            timestamp: now,
            sessionId: effectiveSessionId,
            agentId,
            runId,
            data: {
              success: result.success,
              summary: result.summary,
              iterations: result.iterations,
              tokensUsed: result.tokensUsed,
              durationMs: 0,
              filesCreated: result.filesCreated,
              filesModified: result.filesModified,
              stopReason: result.success ? "report_complete" : "unknown"
            },
            metadata: baseMetadata
          });
        }
        const detailedTrace = tracer.getEntries();
        if (detailedTrace.length > 0) {
          await sessionManager.storeTraceArtifacts(effectiveSessionId, runId, detailedTrace);
        }
        if (result.fileChanges && result.fileChanges.length > 0) {
          await sessionManager.attachFileChangesToTurn(effectiveSessionId, runId, result.fileChanges);
        }
        if (approve) {
          if (mode !== "plan") {
            ctx.ui?.warn?.("--approve is currently supported only with --mode=plan");
          } else if (!result.plan) {
            ctx.ui?.warn?.("No plan produced by plan mode, nothing to approve");
          } else {
            const approvedAt = (/* @__PURE__ */ new Date()).toISOString();
            const approvedPlan = {
              ...result.plan,
              status: "approved",
              approvedAt,
              approvalComment: "Approved via CLI --approve",
              updatedAt: approvedAt
            };
            const sessionPlanPath = sessionManager.getSessionPlanPath(effectiveSessionId);
            await promises.writeFile(sessionPlanPath, JSON.stringify(approvedPlan, null, 2), "utf-8");
            const planDocumentService = new PlanDocumentService(workingDir);
            const planDocPath = planDocumentService.getPlanPath(result.plan);
            await planDocumentService.appendExecutionLog(
              planDocPath,
              `- ${approvedAt}: Plan approved via CLI (--approve).`
            );
            ctx.ui?.success?.(`Plan approved: ${approvedPlan.id}`);
            if (executeAfterPlan) {
              ctx.ui?.info?.("Executing approved plan...");
              const executeConfig = {
                ...config,
                mode: { mode: "execute" }
              };
              const executeSdk = new AgentSDK();
              executeSdk.register(createCoreToolPack(toolRegistry));
              const executeRunner = executeSdk.createRunner(executeConfig);
              result = await executeRunner.execute(task);
            } else {
              ctx.ui?.info?.(`Execute: kb agent run --session-id=${effectiveSessionId}`);
            }
            if (spec && approvedPlan) {
              ctx.ui?.info?.("Generating detailed specification from approved plan...");
              const specHandler = new SpecModeHandler();
              const specResult = await specHandler.execute(approvedPlan, config, toolRegistry);
              if (specResult.success) {
                ctx.ui?.success?.(`Spec generated: ${specResult.spec?.id} (${specResult.spec?.sections.length || 0} sections)`);
              } else {
                ctx.ui?.warn?.(`Spec generation failed: ${specResult.summary}`);
              }
            }
          }
        }
        await tracer.finalize();
        const runSucceeded = result.success;
        const structuredResult = {
          exitCode: runSucceeded ? 0 : 1,
          sessionId: effectiveSessionId,
          summary: result.summary,
          data: {
            sessionId: effectiveSessionId,
            success: runSucceeded,
            summary: result.summary,
            filesCreated: result.filesCreated,
            filesModified: result.filesModified,
            filesRead: result.filesRead,
            iterations: result.iterations,
            tokensUsed: result.tokensUsed,
            hasPlan: mode === "plan" && !!result.plan
          }
        };
        if (jsonOutput) {
          ctx.ui?.json?.(structuredResult);
        }
        return structuredResult;
      } catch (error) {
        clearTimeout_();
        if (abortController?.signal.aborted) {
          const reason = abortController.signal.reason instanceof Error ? abortController.signal.reason.message : `Agent execution timed out after ${timeoutSecs}s`;
          console.error(`
\u23F1  ${reason}
`);
          return { exitCode: 124 };
        }
        const errorMessage = error instanceof Error ? error.message : String(error);
        console.error(`
\u274C Agent execution failed: ${errorMessage}
`);
        return { exitCode: 1 };
      }
    }
  }
});

export { run_default as default };
//# sourceMappingURL=run.js.map
//# sourceMappingURL=run.js.map