import { defineCommand } from '@kb-labs/sdk';
import { loadTrace, formatTraceLoadError } from '@kb-labs/agent-tracing';

// src/cli/commands/trace-context.ts
var trace_context_default = defineCommand({
  id: "trace:context",
  description: "View what the LLM sees at each iteration \u2014 context window, truncations, and responses",
  handler: {
    async execute(ctx, input) {
      const flags = input.flags ?? input;
      const taskId = flags["task-id"] ?? flags.taskId;
      const filterIteration = typeof flags.iteration === "string" ? parseInt(flags.iteration, 10) : flags.iteration;
      try {
        const loaded = await loadTrace(taskId);
        if (!loaded.ok) {
          ctx.ui.write(JSON.stringify(error("INVALID_TASK_ID", formatTraceLoadError(loaded.error)), null, 2) + "\n");
          return { exitCode: 1 };
        }
        const events = loaded.events;
        const iterations = [];
        let currentSnapshot = null;
        for (const e of events) {
          if (e.type === "context:snapshot") {
            currentSnapshot = e.data ?? e;
          }
          if (e.type === "llm_response" && currentSnapshot) {
            const llmEnd = events.find(
              (ev) => ev.type === "llm:end" && Math.abs(new Date(ev.timestamp).getTime() - new Date(e.timestamp).getTime()) < 5e3
            );
            const responseData = e.data ?? e;
            const endData = llmEnd?.data ?? llmEnd ?? {};
            iterations.push({
              iteration: currentSnapshot.iteration,
              context: currentSnapshot,
              response: responseData,
              tokensUsed: endData.tokensUsed ?? 0,
              durationMs: endData.durationMs ?? 0
            });
            currentSnapshot = null;
          }
        }
        const filtered = filterIteration ? iterations.filter((it) => it.iteration === filterIteration) : iterations;
        if (filtered.length === 0) {
          ctx.ui.write("No context:snapshot events found. Make sure agent was run with latest build.\n");
          return { exitCode: 1 };
        }
        if (flags.json) {
          ctx.ui.write(JSON.stringify({ success: true, iterations: filtered }, null, 2) + "\n");
        } else {
          printTimeline(ctx, filtered);
        }
        return { exitCode: 0 };
      } catch (err) {
        ctx.ui.write(JSON.stringify(error("TRACE_NOT_FOUND", `Trace not found: ${taskId}`), null, 2) + "\n");
        return { exitCode: 1 };
      }
    }
  }
});
function printTimeline(ctx, iterations) {
  ctx.ui.write("\n\u{1F4CB} Context Timeline\n");
  ctx.ui.write("\u2550".repeat(60) + "\n");
  for (const it of iterations) {
    const sw = it.context.slidingWindow;
    ctx.ui.write(`
\u2500\u2500\u2500 Iteration ${it.iteration} \u2500\u2500\u2500
`);
    ctx.ui.write(`  \u{1F4CA} Context: ${it.context.messageCount} messages, ~${it.context.estimatedTokens} tokens (${it.context.totalChars} chars)
`);
    ctx.ui.write(`  \u{1F527} Tools available: ${it.context.toolCount}
`);
    if (sw && sw.droppedMessages > 0) {
      ctx.ui.write(`  \u26A0\uFE0F  Sliding window: ${sw.droppedMessages} messages DROPPED (${sw.fullHistorySize} total, window=${sw.windowedSize})
`);
    }
    ctx.ui.write(`
  Messages:
`);
    for (const msg of it.context.messages) {
      const role = msg.role.padEnd(10);
      const size = `${msg.chars}`.padStart(5) + " chars";
      let flags = "";
      if (msg.truncated) {
        flags += " [TRUNCATED]";
      }
      if (msg.toolCalls) {
        flags += ` \u2192 calls: ${msg.toolCalls.join(", ")}`;
      }
      if (msg.toolCallId) {
        flags += ` (result for ${msg.toolCallId.slice(0, 8)}...)`;
      }
      ctx.ui.write(`    [${msg.index}] ${role} ${size}${flags}
`);
      if (msg.preview && msg.role === "tool" && msg.chars < 200) {
        ctx.ui.write(`        "${msg.preview.slice(0, 80)}"
`);
      }
    }
    if (it.response) {
      ctx.ui.write(`
  \u{1F916} Response: ${it.tokensUsed} tokens, ${it.durationMs}ms
`);
      if (it.response.content && it.response.content.length > 0 && it.response.content !== "[Executing tools...]") {
        const preview = it.response.content.slice(0, 200).replace(/\n/g, " ");
        ctx.ui.write(`     Text: "${preview}"
`);
      }
      if (it.response.toolCalls && it.response.toolCalls.length > 0) {
        for (const tc of it.response.toolCalls) {
          ctx.ui.write(`     \u2192 ${tc.name}(${tc.args.slice(0, 100)})
`);
        }
      }
    }
  }
  ctx.ui.write("\n");
}
function error(code, message) {
  return {
    success: false,
    command: "trace:context",
    taskId: "",
    error: { code, message },
    summary: { message, severity: "error", actionable: true }
  };
}

export { trace_context_default as default };
//# sourceMappingURL=trace-context.js.map
//# sourceMappingURL=trace-context.js.map