import * as vscode from "vscode";
import { propagation, metrics } from "@opentelemetry/api";
import * as semver from "semver";
import { machineIdSync } from "node-machine-id";
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { AWSXRayIdGenerator } from "@opentelemetry/id-generator-aws-xray";
import { AWSXRayPropagator } from "@opentelemetry/propagator-aws-xray";
import { Resource } from "@opentelemetry/resources";
import { AggregationTemporality, PeriodicExportingMetricReader, MeterProvider, View, ExponentialHistogramAggregation, InstrumentType } from "@opentelemetry/sdk-metrics";
import { NodeSDK } from "@opentelemetry/sdk-node";
import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
import { ATTR_SERVICE_VERSION, ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
import "path";
import "os";
import "fs";
import { exec } from "child_process";
import { promisify } from "util";
import { initializeToolCounters } from "@kiro/agent";
const channel = vscode.window.createOutputChannel("Kiro Logs", { log: true });
const logs = [];
function logLocalLevel(level, message, ...arguments_) {
  const argumentsJoined = arguments_.map((a) => typeof a === "object" ? JSON.stringify(a) : a).join(" ");
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
  const logMessage = `[${timestamp}] [${level}] ${message} ${argumentsJoined}`;
  logs.push(logMessage);
}
const logger = {
  trace(message, ...arguments_) {
    channel.trace(message, ...arguments_);
    logLocalLevel("trace", message, ...arguments_);
  },
  debug(message, ...arguments_) {
    channel.debug(message, ...arguments_);
    logLocalLevel("debug", message, ...arguments_);
  },
  info(message, ...arguments_) {
    channel.info(message, ...arguments_);
    logLocalLevel("info", message, ...arguments_);
  },
  warn(message, ...arguments_) {
    channel.warn(message, ...arguments_);
    logLocalLevel("warn", message, ...arguments_);
  },
  error(error, ...arguments_) {
    channel.error(error, ...arguments_);
    logLocalLevel("error", `${error}`, ...arguments_);
  },
  capture() {
    const logsString = logs.join("\n");
    logs.length = 0;
    channel.clear();
    return logsString;
  }
};
const mcpLogsPerServer = /* @__PURE__ */ new Map();
const mcpLogChannel = vscode.window.createOutputChannel("Kiro - MCP Logs", { log: true });
function storeMCPLogMessage(message, level, serverName, ...arguments_) {
  const argumentsJoined = arguments_.map((a) => typeof a === "object" ? JSON.stringify(a) : a).join(" ");
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
  const logServerName = serverName || "KIRO_MCP_DEFAULT";
  const logMessage = `[${timestamp}] [${level}] [${logServerName}] ${message} ${argumentsJoined}`;
  const serverLogs = mcpLogsPerServer.get(logServerName) || [];
  serverLogs.push(logMessage);
  mcpLogsPerServer.set(logServerName, serverLogs);
}
const mcpLogger = {
  trace(message, serverName, ...arguments_) {
    const serverNamePrefix = serverName ? `[${serverName}] ` : "";
    mcpLogChannel.trace(`${serverNamePrefix}${message}`, ...arguments_);
    storeMCPLogMessage(message, "trace", serverName, ...arguments_);
  },
  debug(message, serverName, ...arguments_) {
    const serverNamePrefix = serverName ? `[${serverName}] ` : "";
    mcpLogChannel.debug(`${serverNamePrefix}${message}`, ...arguments_);
    storeMCPLogMessage(message, "debug", serverName, ...arguments_);
  },
  info(message, serverName, ...arguments_) {
    const serverNamePrefix = serverName ? `[${serverName}] ` : "";
    mcpLogChannel.info(`${serverNamePrefix}${message}`, ...arguments_);
    storeMCPLogMessage(message, "info", serverName, ...arguments_);
  },
  warn(message, serverName, ...arguments_) {
    const serverNamePrefix = serverName ? `[${serverName}] ` : "";
    mcpLogChannel.warn(`${serverNamePrefix}${message}`, ...arguments_);
    storeMCPLogMessage(message, "warn", serverName, ...arguments_);
  },
  error(error, serverName, ...arguments_) {
    const serverNamePrefix = serverName ? `[${serverName}] ` : "";
    mcpLogChannel.error(`${serverNamePrefix}${error}`, ...arguments_);
    storeMCPLogMessage(`${error}`, "error", serverName, ...arguments_);
  },
  getLogsForServer(serverName) {
    return mcpLogsPerServer.get(serverName) || [];
  },
  show() {
    mcpLogChannel.show();
  },
  capture() {
    const logsString = Array.from(mcpLogsPerServer.values()).flatMap((it) => it).join("\n");
    mcpLogsPerServer.clear();
    mcpLogChannel.clear();
    return logsString;
  }
};
const powersLogChannel = vscode.window.createOutputChannel("Kiro - Powers", { log: true });
const powersLogs = [];
function storePowersLogMessage(message, level, ...arguments_) {
  const argumentsJoined = arguments_.map((a) => typeof a === "object" ? JSON.stringify(a) : a).join(" ");
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
  const logMessage = `[${timestamp}] [${level}] ${message} ${argumentsJoined}`;
  powersLogs.push(logMessage);
}
const powersLogger = {
  trace(message, ...arguments_) {
    powersLogChannel.trace(message, ...arguments_);
    storePowersLogMessage(message, "trace", ...arguments_);
  },
  debug(message, ...arguments_) {
    powersLogChannel.debug(message, ...arguments_);
    storePowersLogMessage(message, "debug", ...arguments_);
  },
  info(message, ...arguments_) {
    powersLogChannel.info(message, ...arguments_);
    storePowersLogMessage(message, "info", ...arguments_);
  },
  warn(message, ...arguments_) {
    powersLogChannel.warn(message, ...arguments_);
    storePowersLogMessage(message, "warn", ...arguments_);
  },
  error(error, ...arguments_) {
    powersLogChannel.error(error, ...arguments_);
    storePowersLogMessage(`${error}`, "error", ...arguments_);
  },
  show() {
    powersLogChannel.show();
  },
  capture() {
    const logsString = powersLogs.join("\n");
    powersLogs.length = 0;
    powersLogChannel.clear();
    return logsString;
  }
};
const logOutputChannels = {
  kiro: channel,
  mcp: mcpLogChannel,
  powers: powersLogChannel
};
const execAsync = promisify(exec);
const MIDWAY_COMMAND = "mwinit";
const WHICH_COMMAND = process.platform == "win32" ? "where.exe" : "which";
async function isMwinitToolAvailable() {
  try {
    await execAsync(`${WHICH_COMMAND} ${MIDWAY_COMMAND}`);
    return true;
  } catch {
    return false;
  }
}
const CONTENT_COLLECTION_SECTION = "telemetry";
const CONTENT_COLLECTION_KEY = "dataSharingAndPromptLogging.contentCollectionForServiceImprovement";
function getContentCollectionOptIn() {
  try {
    return vscode.workspace.getConfiguration(CONTENT_COLLECTION_SECTION).get(CONTENT_COLLECTION_KEY, false);
  } catch {
    return false;
  }
}
var MetricNamespace = /* @__PURE__ */ ((MetricNamespace2) => {
  MetricNamespace2["Onboarding"] = "kiro.onboarding";
  MetricNamespace2["Auth"] = "kiro.auth";
  MetricNamespace2["Session"] = "kiro.session";
  MetricNamespace2["Feature"] = "kiro.feature";
  MetricNamespace2["User"] = "kiro.user";
  MetricNamespace2["Tool"] = "kiro.tool";
  MetricNamespace2["Operation"] = "kiro.operation";
  MetricNamespace2["Periodic"] = "kiro.periodic";
  return MetricNamespace2;
})(MetricNamespace || {});
const DEFAULT_MACHINE_ID = "UNDETERMINED_MACHINE_ID";
function getMachineId() {
  try {
    return machineIdSync();
  } catch (_e) {
    return vscode.env.machineId || DEFAULT_MACHINE_ID;
  }
}
const MACHINE_ID = getMachineId();
const semanticVersion = semver.parse(vscode.kiroVersion ?? "0.0.0");
const KIRO_CLIENT_VERSION = `${semanticVersion?.major}.${semanticVersion?.minor}`;
function userAttributes() {
  return {
    KiroClientVersion: KIRO_CLIENT_VERSION,
    machineId: MACHINE_ID
  };
}
function getUserActivityMetricAttributes(activity) {
  const attributes = {
    ...userAttributes(),
    Activity: activity
  };
  return attributes;
}
class BaggageSpanProcessor {
  keys;
  constructor(options) {
    this.keys = options.keys;
  }
  /**
   * Called when a span is started
   * @param span The span that was started
   * @param parentContext The parent context, if any
   */
  onStart(span, parentContext) {
    const baggage = propagation.getBaggage(parentContext);
    if (!baggage) {
      return;
    }
    this.keys.forEach((key) => {
      const entry = baggage.getEntry(key);
      if (entry) {
        span.setAttribute(key, entry.value);
      }
    });
  }
  /**
   * Called when a span ends
   * @param _span The span that ended
   */
  onEnd(_span) {
  }
  /**
   * Shuts down the processor
   */
  shutdown() {
    return Promise.resolve();
  }
  /**
   * Forces the processor to flush any pending spans
   */
  forceFlush() {
    return Promise.resolve();
  }
}
let hasOpenedIDECount;
let startedOnboardingAuthFlowCount;
let failedOnboardingAuthFlowCount;
let canceledOnboardingAuthFlowCount;
let abandonedOnboardingAuthFlowCount;
let finishedOnboardingAuthFlowCount;
let badUserInputOnboardingAuthFlowCount;
function initializeCounters$3() {
  const onboardingMeter = metrics.getMeterProvider().getMeter(MetricNamespace.Onboarding);
  hasOpenedIDECount = onboardingMeter.createCounter("opened_IDE_count", {
    description: "Counts the number of times the IDE has been opened",
    unit: "number"
  });
  startedOnboardingAuthFlowCount = onboardingMeter.createCounter("started_auth_count", {
    description: "Counts the number of times the IDE has started the auth onboarding flow",
    unit: "number"
  });
  failedOnboardingAuthFlowCount = onboardingMeter.createCounter("failed_auth_count", {
    description: "Counts the number of times the IDE has failed the onboarding auth flow",
    unit: "number"
  });
  canceledOnboardingAuthFlowCount = onboardingMeter.createCounter("canceled_auth_count", {
    description: "Counts the number of times a user canceled the onboarding auth flow",
    unit: "number"
  });
  abandonedOnboardingAuthFlowCount = onboardingMeter.createCounter("abandoned_auth_count", {
    description: "Counts the number of times a user abandons the onboarding auth flow (timeout)",
    unit: "number"
  });
  finishedOnboardingAuthFlowCount = onboardingMeter.createCounter("finished_auth_count", {
    description: "Counts the number of times the IDE has finished the onboarding auth flow",
    unit: "number"
  });
  badUserInputOnboardingAuthFlowCount = onboardingMeter.createCounter("bad_user_input_count", {
    description: "Counts the number of times bad user input was encountered during onboarding",
    unit: "number"
  });
}
function recordOnboardingStep(type) {
  try {
    if (!isInitialized()) {
      return;
    }
    const activity = "onboarding";
    const attributes = getUserActivityMetricAttributes(activity);
    switch (type) {
      case "opened-IDE":
        hasOpenedIDECount.add(1, attributes);
        break;
      case "started-login":
        startedOnboardingAuthFlowCount.add(1, attributes);
        break;
      case "failed-login":
        failedOnboardingAuthFlowCount.add(1, attributes);
        break;
      case "canceled-login":
        canceledOnboardingAuthFlowCount.add(1, attributes);
        break;
      case "abandoned-login":
        abandonedOnboardingAuthFlowCount.add(1, attributes);
        break;
      case "finished-login":
        finishedOnboardingAuthFlowCount.add(1, attributes);
        break;
      case "bad-user-input":
        badUserInputOnboardingAuthFlowCount.add(1, attributes);
        break;
    }
  } catch (e) {
    logger.error("Failed to record feature latency: ", e);
  }
}
let githubLoginCount;
let googleLoginCount;
let enterpriseIdcLoginCount;
let internalIdcLoginCount;
let builderIdLoginCount;
let externalIdpLoginCount;
function initializeCounters$2() {
  const authTypeMeter = metrics.getMeterProvider().getMeter(MetricNamespace.User);
  githubLoginCount = authTypeMeter.createCounter("github_login_count", {
    description: "Counts the number of times users have logged in with GitHub",
    unit: "number"
  });
  googleLoginCount = authTypeMeter.createCounter("google_login_count", {
    description: "Counts the number of times users have logged in with Google",
    unit: "number"
  });
  enterpriseIdcLoginCount = authTypeMeter.createCounter("enterprise_idc_login_count", {
    description: "Counts the number of times users have logged in with IdC",
    unit: "number"
  });
  internalIdcLoginCount = authTypeMeter.createCounter("idc_internal_login_count", {
    description: "Counts the number of times users have logged in with IdC",
    unit: "number"
  });
  builderIdLoginCount = authTypeMeter.createCounter("builder_id_login_count", {
    description: "Counts the number of times users have logged in with Builder ID",
    unit: "number"
  });
  externalIdpLoginCount = authTypeMeter.createCounter("external_idp_login_count", {
    description: "Counts the number of times users have logged in with External IdP",
    unit: "number"
  });
}
function recordAuthFromSource(source) {
  try {
    if (!isInitialized()) {
      return;
    }
    const activity = "login";
    const attributes = getUserActivityMetricAttributes(activity);
    if (source.authMethod == "social") {
      switch (source.provider) {
        case "Google":
          googleLoginCount.add(1, attributes);
          break;
        case "Github":
          githubLoginCount.add(1, attributes);
          break;
      }
    } else if (source.authMethod == "IdC") {
      switch (source.provider) {
        case "BuilderId":
          builderIdLoginCount.add(1, attributes);
          break;
        case "Enterprise":
          enterpriseIdcLoginCount.add(1, attributes);
          break;
        case "Internal":
          internalIdcLoginCount.add(1, attributes);
          break;
      }
    } else if (source.authMethod == "external_idp") {
      externalIdpLoginCount.add(1, attributes);
    }
  } catch (e) {
    logger.error("Failed to record auth login metrics: ", e);
  }
}
const AGENT_SUGGESTED_PREFIX = "Agent suggested bash execution count:";
const USER_ACTION_PREFIX = "User action count:";
let agentSuggestedCommand;
let agentCommandRequiredReview;
let userRejectedCommand;
let userAcceptedCommand;
let userTrustedCommand;
let userSelectedTrustOptionFull;
let userSelectedTrustOptionPartial;
let userSelectedTrustOptionBase;
let userDeselectedTrustOption;
const EVENT_COUNTER_MAP = /* @__PURE__ */ new Map();
function initializeEventCounterMap() {
  EVENT_COUNTER_MAP.set("agent-suggested-command", agentSuggestedCommand);
  EVENT_COUNTER_MAP.set("agent-command-required-review", agentCommandRequiredReview);
  EVENT_COUNTER_MAP.set("user-rejected-command", userRejectedCommand);
  EVENT_COUNTER_MAP.set("user-accepted-command", userAcceptedCommand);
  EVENT_COUNTER_MAP.set("user-trusted-command", userTrustedCommand);
  EVENT_COUNTER_MAP.set("user-selected-trust-option-full", userSelectedTrustOptionFull);
  EVENT_COUNTER_MAP.set("user-selected-trust-option-partial", userSelectedTrustOptionPartial);
  EVENT_COUNTER_MAP.set("user-selected-trust-option-base", userSelectedTrustOptionBase);
  EVENT_COUNTER_MAP.set("user-deselected-trust-option", userDeselectedTrustOption);
}
function initializeCounters$1() {
  const commandMeter = metrics.getMeterProvider().getMeter(MetricNamespace.Session);
  agentSuggestedCommand = commandMeter.createCounter("agent_suggested_command", {
    description: `${AGENT_SUGGESTED_PREFIX} total`,
    unit: "number"
  });
  agentCommandRequiredReview = commandMeter.createCounter("agent_command_required_review", {
    description: `${AGENT_SUGGESTED_PREFIX} required manual review`,
    unit: "number"
  });
  userRejectedCommand = commandMeter.createCounter("user_rejected_command", {
    description: `${USER_ACTION_PREFIX} rejected command`,
    unit: "number"
  });
  userAcceptedCommand = commandMeter.createCounter("user_accepted_command", {
    description: `${USER_ACTION_PREFIX} accepted command`,
    unit: "number"
  });
  userTrustedCommand = commandMeter.createCounter("user_trusted_command", {
    description: `${USER_ACTION_PREFIX} trusted command`,
    unit: "number"
  });
  userSelectedTrustOptionFull = commandMeter.createCounter("user_selected_trust_option_full", {
    description: `${USER_ACTION_PREFIX} selected full trust option`,
    unit: "number"
  });
  userSelectedTrustOptionPartial = commandMeter.createCounter("user_selected_trust_option_partial", {
    description: `${USER_ACTION_PREFIX} selected partial trust option`,
    unit: "number"
  });
  userSelectedTrustOptionBase = commandMeter.createCounter("user_selected_trust_option_base", {
    description: `${USER_ACTION_PREFIX} selected base trust option`,
    unit: "number"
  });
  userDeselectedTrustOption = commandMeter.createCounter("user_deselected_trust_option", {
    description: `${USER_ACTION_PREFIX} cancelled trust selection`,
    unit: "number"
  });
  initializeEventCounterMap();
}
function recordBashToolEvent(type) {
  try {
    const activity = "bash_execution";
    const attributes = getUserActivityMetricAttributes(activity);
    const counter = EVENT_COUNTER_MAP.get(type);
    if (counter) {
      counter.add(1, attributes);
    }
  } catch (e) {
    logger.error("Failed to record bash execution outcome: ", e);
  }
}
var WorkflowType;
(function(WorkflowType2) {
  WorkflowType2["RequirementsFirst"] = "requirements-first";
  WorkflowType2["DesignFirst"] = "design-first";
  WorkflowType2["FastTask"] = "fast-task";
})(WorkflowType || (WorkflowType = {}));
var SpecType;
(function(SpecType2) {
  SpecType2["Feature"] = "feature";
  SpecType2["Bugfix"] = "bugfix";
  SpecType2["QuickSpec"] = "quick-spec";
})(SpecType || (SpecType = {}));
var IDEListenableEvent;
(function(IDEListenableEvent2) {
  IDEListenableEvent2["FileEdited"] = "fileEdited";
  IDEListenableEvent2["FileCreated"] = "fileCreated";
  IDEListenableEvent2["FileDeleted"] = "fileDeleted";
  IDEListenableEvent2["UserTriggered"] = "userTriggered";
  IDEListenableEvent2["UserPrompt"] = "promptSubmit";
  IDEListenableEvent2["AgentStop"] = "agentStop";
  IDEListenableEvent2["PreToolUse"] = "preToolUse";
  IDEListenableEvent2["PostToolUse"] = "postToolUse";
  IDEListenableEvent2["PreTaskExecution"] = "preTaskExecution";
  IDEListenableEvent2["PostTaskExecution"] = "postTaskExecution";
  IDEListenableEvent2["SessionStart"] = "sessionStart";
})(IDEListenableEvent || (IDEListenableEvent = {}));
var HookActionEvent;
(function(HookActionEvent2) {
  HookActionEvent2["AskAgent"] = "askAgent";
  HookActionEvent2["RunCommand"] = "runCommand";
})(HookActionEvent || (HookActionEvent = {}));
var ConfigKey;
(function(ConfigKey2) {
  ConfigKey2["DevMode"] = "enableDevMode";
  ConfigKey2["TrustedCommands"] = "trustedCommands";
  ConfigKey2["CommandDenylist"] = "commandDenylist";
  ConfigKey2["AutoApproveAgentCommands"] = "autoApproveAgentCommands";
  ConfigKey2["ConfigureMCP"] = "configureMCP";
  ConfigKey2["ExecuteBashTimeoutMs"] = "executeBashTimeoutMs";
  ConfigKey2["EnableRepositoryMapIndex"] = "enableRepositoryMapIndex";
  ConfigKey2["TrustedTools"] = "trustedTools";
})(ConfigKey || (ConfigKey = {}));
({
  [ConfigKey.DevMode]: false,
  [ConfigKey.TrustedCommands]: [],
  [ConfigKey.CommandDenylist]: [],
  [ConfigKey.AutoApproveAgentCommands]: [],
  [ConfigKey.ConfigureMCP]: "Disabled",
  [ConfigKey.ExecuteBashTimeoutMs]: void 0,
  [ConfigKey.EnableRepositoryMapIndex]: false,
  [ConfigKey.TrustedTools]: []
});
var ConfigNamespace;
(function(ConfigNamespace2) {
  ConfigNamespace2["Extension"] = "kiroAgent";
  ConfigNamespace2["Test"] = "kiroAgent.test";
})(ConfigNamespace || (ConfigNamespace = {}));
var ExecutionStatus;
(function(ExecutionStatus2) {
  ExecutionStatus2["Queued"] = "Queued";
  ExecutionStatus2["InProgress"] = "InProgress";
  ExecutionStatus2["Paused"] = "Paused";
  ExecutionStatus2["NeedAction"] = "NeedAction";
  ExecutionStatus2["Success"] = "Success";
  ExecutionStatus2["Failed"] = "Failed";
  ExecutionStatus2["Canceled"] = "Canceled";
  ExecutionStatus2["Yielded"] = "Yielded";
})(ExecutionStatus || (ExecutionStatus = {}));
var ExecutionAssignment;
(function(ExecutionAssignment2) {
  ExecutionAssignment2["Queued"] = "Queued";
  ExecutionAssignment2["Active"] = "Active";
  ExecutionAssignment2["History"] = "History";
})(ExecutionAssignment || (ExecutionAssignment = {}));
var ChangeType;
(function(ChangeType2) {
  ChangeType2["Code"] = "Code";
})(ChangeType || (ChangeType = {}));
var OperationStatus;
(function(OperationStatus2) {
  OperationStatus2["PendingAction"] = "PendingAction";
  OperationStatus2["Running"] = "Running";
  OperationStatus2["Success"] = "Success";
  OperationStatus2["Error"] = "Error";
  OperationStatus2["Accepted"] = "Accepted";
  OperationStatus2["Rejected"] = "Rejected";
  OperationStatus2["Canceled"] = "Canceled";
  OperationStatus2["HandledError"] = "HandledError";
})(OperationStatus || (OperationStatus = {}));
var AutonomyMode;
(function(AutonomyMode2) {
  AutonomyMode2["Autopilot"] = "Autopilot";
  AutonomyMode2["Supervised"] = "Supervised";
})(AutonomyMode || (AutonomyMode = {}));
var TaskStatus;
(function(TaskStatus2) {
  TaskStatus2["NotStarted"] = "not_started";
  TaskStatus2["Queued"] = "queued";
  TaskStatus2["InProgress"] = "in_progress";
  TaskStatus2["Completed"] = "completed";
})(TaskStatus || (TaskStatus = {}));
var TelemetryNamespace;
(function(TelemetryNamespace2) {
  TelemetryNamespace2["Application"] = "kiro.application";
  TelemetryNamespace2["Feature"] = "kiro.feature";
  TelemetryNamespace2["Continue"] = "kiro.continue";
  TelemetryNamespace2["Agent"] = "kiro.agent";
  TelemetryNamespace2["Tool"] = "kiro.tool";
  TelemetryNamespace2["Parser"] = "kiro.parser";
  TelemetryNamespace2["Onboarding"] = "kiro.onboarding";
  TelemetryNamespace2["Webview"] = "kiro.webview";
  TelemetryNamespace2["Auth"] = "kiro.auth";
  TelemetryNamespace2["Billing"] = "kiro.billing";
  TelemetryNamespace2["Profiles"] = "kiro.profiles";
  TelemetryNamespace2["RemoteTools"] = "kiro.remote-tools";
  TelemetryNamespace2["Spec"] = "kiro.spec";
  TelemetryNamespace2["Chat"] = "kiro.chat";
  TelemetryNamespace2["Io"] = "kiro.io";
  TelemetryNamespace2["RemoteSession"] = "kiro.remote-session";
  TelemetryNamespace2["CloudConfig"] = "kiro.cloud-config";
})(TelemetryNamespace || (TelemetryNamespace = {}));
var JourneyId;
(function(JourneyId2) {
  JourneyId2["Onboarding"] = "onboarding";
})(JourneyId || (JourneyId = {}));
var TelemetryAttributes;
(function(TelemetryAttributes2) {
  TelemetryAttributes2["RequestId"] = "requestId";
  TelemetryAttributes2["ConversationId"] = "conversationId";
  TelemetryAttributes2["ExecutionId"] = "executionId";
  TelemetryAttributes2["ModelIdentifier"] = "ModelIdentifier";
  TelemetryAttributes2["ModeIdentifier"] = "ModeIdentifier";
  TelemetryAttributes2["UserId"] = "userId";
  TelemetryAttributes2["AgentMode"] = "agentMode";
  TelemetryAttributes2["Workflow"] = "workflow";
  TelemetryAttributes2["TurnId"] = "turnId";
  TelemetryAttributes2["RootTurnId"] = "rootTurnId";
  TelemetryAttributes2["XRayTraceId"] = "AWS-XRAY-TRACE-ID";
})(TelemetryAttributes || (TelemetryAttributes = {}));
var AuthError;
(function(AuthError2) {
  AuthError2["INVALID_TOKEN"] = "INVALID_TOKEN";
  AuthError2["NETWORK_ERROR"] = "NETWORK_ERROR";
  AuthError2["UNEXPECTED_ERROR"] = "UNEXPECTED_ERROR";
})(AuthError || (AuthError = {}));
var PowersErrorName;
(function(PowersErrorName2) {
  PowersErrorName2["InvalidPowerError"] = "InvalidPowerError";
  PowersErrorName2["McpJsonNotFoundError"] = "McpJsonNotFoundError";
  PowersErrorName2["McpJsonFetchError"] = "McpJsonFetchError";
  PowersErrorName2["PowerAlreadyInstalledError"] = "PowerAlreadyInstalledError";
  PowersErrorName2["PowerNotFoundError"] = "PowerNotFoundError";
  PowersErrorName2["PowerNotInstalledError"] = "PowerNotInstalledError";
  PowersErrorName2["PowerRegistryLoadError"] = "PowerRegistryLoadError";
  PowersErrorName2["PowerRegistrySaveError"] = "PowerRegistrySaveError";
  PowersErrorName2["PowerValidationError"] = "PowerValidationError";
  PowersErrorName2["PowerRegistryDataError"] = "PowerRegistryDataError";
  PowersErrorName2["RepositoryCloneError"] = "RepositoryCloneError";
  PowersErrorName2["InstallFileSystemError"] = "InstallFileSystemError";
  PowersErrorName2["UnknownError"] = "UnknownError";
})(PowersErrorName || (PowersErrorName = {}));
function deriveUserCohort(provider) {
  if (provider === void 0) return "unknown";
  if (provider === "Internal") return "internal";
  if (provider === "Enterprise" || provider === "ExternalIdp") return "enterprise";
  return "external";
}
let resolver;
function setUserCohortResolver(fn) {
  resolver = fn;
}
function getUserCohort() {
  try {
    return resolver?.() ?? "unknown";
  } catch {
    return "unknown";
  }
}
const APPLICATION_NAME = "kiroAgent";
const APPLICATION_VERSION = "0.0.1";
const USER_MACHINE_ID = getMachineId();
const EXPORT_INTERVAL_MILLIS = 6e4;
let isTelemetryInitialized = false;
function isInitialized() {
  return isTelemetryInitialized;
}
function initializeBaggagePropagation(propagator) {
  propagation.setGlobalPropagator(propagator);
}
function initializeTelemetry(configuration) {
  setUserCohortResolver(configuration.resolveUserCohort);
  const TELEMETRY_ENDPOINT = configuration.endpoint;
  const resource = Resource.empty().merge(
    new Resource({
      [ATTR_SERVICE_NAME]: APPLICATION_NAME,
      [ATTR_SERVICE_VERSION]: APPLICATION_VERSION
    })
  );
  const traceExporter = new OTLPTraceExporter({
    url: TELEMETRY_ENDPOINT + "/v1/traces",
    headers: {
      "x-kiro-machineid": USER_MACHINE_ID
    }
  });
  const metricExporter = new OTLPMetricExporter({
    // CloudWatch expects delta aggregation. If this is cumulative, cloudwatch
    // will collect duplicate metrics and our sample counts will be inflated
    url: TELEMETRY_ENDPOINT + "/v1/metrics",
    temporalityPreference: AggregationTemporality.DELTA,
    headers: {
      "x-kiro-machineid": USER_MACHINE_ID
    }
  });
  const exportInterval = configuration.exportIntervalMillis ?? EXPORT_INTERVAL_MILLIS;
  const metricReader = new PeriodicExportingMetricReader({
    exporter: metricExporter,
    exportIntervalMillis: exportInterval,
    ...configuration.exportTimeoutMillis !== void 0 && {
      exportTimeoutMillis: configuration.exportTimeoutMillis
    }
  });
  const meterProvider = new MeterProvider({
    resource,
    views: [
      new View({
        instrumentType: InstrumentType.HISTOGRAM,
        aggregation: new ExponentialHistogramAggregation()
      })
    ]
  });
  meterProvider.addMetricReader(metricReader);
  metrics.setGlobalMeterProvider(meterProvider);
  const batchSpanProcessor = new BatchSpanProcessor(traceExporter);
  const baggageSpanProcessor = new BaggageSpanProcessor({
    // Only extract known baggage keys
    keys: Object.values(TelemetryAttributes)
  });
  const idGenerator = new AWSXRayIdGenerator();
  const textMapPropagator = new AWSXRayPropagator();
  const telemetrySDK = new NodeSDK({
    textMapPropagator,
    resource,
    spanProcessors: [batchSpanProcessor, baggageSpanProcessor],
    traceExporter,
    idGenerator,
    autoDetectResources: false
  });
  telemetrySDK.start();
  initializeBaggagePropagation(textMapPropagator);
  initializeCounters$3();
  initializeCounters$2();
  initializeToolCounters();
  initializeCounters$1();
  initializeCounters();
  isTelemetryInitialized = true;
  recordOnboardingStep("opened-IDE");
  return new vscode.Disposable(() => {
    void meterProvider.shutdown();
    void telemetrySDK.shutdown();
  });
}
let optOutHeaderSentCount;
let optOutHeaderOmittedCount;
function initializeCounters() {
  const meter = metrics.getMeterProvider().getMeter(MetricNamespace.User);
  optOutHeaderSentCount = meter.createCounter("contentCollection.optOutHeaderSent", {
    description: "Counts requests where the client stamped x-amzn-codewhisperer-optout",
    unit: "number"
  });
  optOutHeaderOmittedCount = meter.createCounter("contentCollection.optOutHeaderOmitted", {
    description: "Counts requests where the client omitted x-amzn-codewhisperer-optout (opted in)",
    unit: "number"
  });
}
function recordOptOutHeaderDecision(optOutHeaderSent, signInMethod) {
  try {
    if (!isInitialized()) {
      return;
    }
    const attributes = { ...userAttributes(), Operation: signInMethod };
    if (optOutHeaderSent) {
      optOutHeaderSentCount.add(1, attributes);
    } else {
      optOutHeaderOmittedCount.add(1, attributes);
    }
  } catch (e) {
    logger.error("Failed to record content collection opt-out metrics: ", e);
  }
}
function isAbortError(error) {
  return error instanceof Error && (error.name.includes("Abort") || error.message.includes("Aborted"));
}
function isBlockedAccessError(error) {
  return error instanceof Error && (error.name.includes("NewUserAccessPausedError") || error.message.includes("Kiro access not available for this account"));
}
function mapUnknownToErrorType(error) {
  if (isAbortError(error)) {
    return "AbortedError";
  }
  if (!(error instanceof Error)) {
    return "UnknownError";
  }
  const name = error.name && error.name !== "Error" ? error.name : error.constructor.name;
  if (name === "Error") {
    const code = error.code;
    if (typeof code === "string" && code.length > 0) {
      return code;
    }
  }
  return name;
}
class TrustedError extends Error {
}
export {
  APPLICATION_NAME as A,
  CONTENT_COLLECTION_KEY as C,
  MetricNamespace as M,
  TrustedError as T,
  isBlockedAccessError as a,
  logger as b,
  mcpLogger as c,
  TelemetryNamespace as d,
  isMwinitToolAvailable as e,
  recordOnboardingStep as f,
  getContentCollectionOptIn as g,
  recordAuthFromSource as h,
  isAbortError as i,
  APPLICATION_VERSION as j,
  CONTENT_COLLECTION_SECTION as k,
  logOutputChannels as l,
  mapUnknownToErrorType as m,
  deriveUserCohort as n,
  getUserCohort as o,
  powersLogger as p,
  initializeBaggagePropagation as q,
  recordOptOutHeaderDecision as r,
  initializeTelemetry as s,
  isInitialized as t,
  recordBashToolEvent as u,
  TelemetryAttributes as v,
  getMachineId as w
};
