import { createRequire as _cjsReq } from 'module'; if(typeof require === 'undefined') var require = _cjsReq(import.meta.url);
import {
  ErrorCodes,
  GuildCLIError,
  axios_default,
  clearAuthToken,
  debug,
  getAuthToken,
  getGuildcoreUrl,
  getIapHeaders,
  getUserAgent,
  retry,
  shouldClearAuthToken
} from "./chunk-JQRJ4A4S.js";

// src/lib/api-client.ts
var GuildAPIClient = class {
  client;
  baseUrl;
  enableRetry;
  maxRetries;
  constructor(options = {}) {
    this.baseUrl = options.baseUrl || getGuildcoreUrl();
    this.enableRetry = options.enableRetry !== false;
    this.maxRetries = options.maxRetries || 3;
    this.client = axios_default.create({
      baseURL: this.baseUrl,
      timeout: options.defaultTimeout || 3e4,
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
        "User-Agent": getUserAgent()
      }
    });
    debug(
      `API Client initialized: ${this.baseUrl}, retry: ${this.enableRetry}, max retries: ${this.maxRetries}`
    );
  }
  /**
   * Make an HTTP request with automatic auth header injection
   * @param method - HTTP method
   * @param endpoint - API endpoint path
   * @param config - Axios request configuration
   * @returns Response data
   * @throws Error with specific error codes for proper error handling
   */
  async request(method, endpoint, config = {}) {
    const makeRequest = async () => {
      const iapHeaders = await getIapHeaders(this.baseUrl);
      config.headers = {
        ...config.headers,
        ...iapHeaders
      };
      const requiresAuth = !endpoint.startsWith("/oauth/") && !endpoint.startsWith("/hello");
      if (requiresAuth) {
        const token = await getAuthToken();
        if (!token) {
          throw new GuildCLIError(
            ErrorCodes.AUTH_REQUIRED,
            "Authentication required. Please run: guild auth login"
          );
        }
        config.headers = {
          ...config.headers,
          Authorization: `Bearer ${token}`
        };
      }
      debug(`Making ${method} request to ${endpoint}`);
      try {
        const response = await this.client.request({
          method,
          url: endpoint,
          ...config
        });
        debug(`Request successful: ${method} ${endpoint}`);
        return response.data;
      } catch (error) {
        if (error && typeof error === "object" && "response" in error && error.response?.status === 401) {
          const resp = error.response;
          const data = resp?.data;
          const message = typeof data === "object" && data && "message" in data ? data.message : void 0;
          if (shouldClearAuthToken(message)) {
            debug("Guild auth failure (401), clearing token");
            await clearAuthToken();
            throw new GuildCLIError(
              ErrorCodes.AUTH_TOKEN_INVALID,
              "Your authentication token is invalid or expired. Please run: guild auth login"
            );
          }
          debug(`Non-auth 401: ${message ?? "no message"}`);
        }
        throw error;
      }
    };
    if (this.enableRetry) {
      return await retry(makeRequest, {
        maxAttempts: this.maxRetries
      });
    } else {
      return await makeRequest();
    }
  }
  /**
   * Make a GET request
   */
  async get(endpoint, config) {
    return this.request("GET", endpoint, config);
  }
  /**
   * Make a POST request
   */
  async post(endpoint, data, config) {
    return this.request("POST", endpoint, { ...config, data });
  }
  /**
   * Make a PUT request
   */
  async put(endpoint, data, config) {
    return this.request("PUT", endpoint, { ...config, data });
  }
  /**
   * Make a PATCH request
   */
  async patch(endpoint, data, config) {
    return this.request("PATCH", endpoint, { ...config, data });
  }
  /**
   * Make a DELETE request
   */
  async delete(endpoint, config) {
    return this.request("DELETE", endpoint, config);
  }
  /**
   * Fetch all items from a paginated endpoint by paging through results.
   * Use for display commands or ID-based lookups where you need the complete list.
   *
   * @param endpoint - API endpoint path (may include query params)
   * @returns Flat array of all items across all pages
   */
  async fetchAll(endpoint) {
    const PAGE_SIZE = 100;
    const allItems = [];
    let offset = 0;
    while (true) {
      const separator = endpoint.includes("?") ? "&" : "?";
      const url = `${endpoint}${separator}limit=${PAGE_SIZE}&offset=${offset}`;
      const response = await this.get(url);
      allItems.push(...response.items);
      offset += response.pagination.limit;
      if (!response.pagination.has_more) break;
    }
    return allItems;
  }
};

// src/lib/guild-config.ts
import * as fs from "fs/promises";
import * as path from "path";
import * as os from "os";
var GLOBAL_CONFIG_DIR = ".guild";
var GLOBAL_CONFIG_FILE = "config.json";
var LOCAL_CONFIG_FILE = "guild.json";
function getGlobalConfigDir() {
  return path.join(os.homedir(), GLOBAL_CONFIG_DIR);
}
function getGlobalConfigPath() {
  return path.join(getGlobalConfigDir(), GLOBAL_CONFIG_FILE);
}
function getLocalConfigPath(cwd = process.cwd()) {
  return path.join(cwd, LOCAL_CONFIG_FILE);
}
async function fileExists(filePath) {
  return fs.access(filePath).then(() => true).catch(() => false);
}
async function loadGlobalConfig() {
  const configPath = getGlobalConfigPath();
  if (!await fileExists(configPath)) {
    debug("Global config not found at %s", configPath);
    return void 0;
  }
  try {
    const content = await fs.readFile(configPath, "utf-8");
    const config = JSON.parse(content);
    debug("Loaded global config: %O", config);
    return config;
  } catch (error) {
    debug("Failed to parse global config: %s", error);
    return void 0;
  }
}
async function loadLocalConfig(cwd = process.cwd()) {
  const configPath = getLocalConfigPath(cwd);
  if (!await fileExists(configPath)) {
    debug("Local config not found at %s", configPath);
    return void 0;
  }
  try {
    const content = await fs.readFile(configPath, "utf-8");
    const config = JSON.parse(content);
    debug("Loaded local config: %O", config);
    return config;
  } catch (error) {
    debug("Failed to parse local config: %s", error);
    return void 0;
  }
}
async function loadConfig(cwd = process.cwd()) {
  const [local, global] = await Promise.all([loadLocalConfig(cwd), loadGlobalConfig()]);
  return { local, global };
}
async function saveGlobalConfig(config) {
  const configDir = getGlobalConfigDir();
  const configPath = getGlobalConfigPath();
  await fs.mkdir(configDir, { recursive: true });
  const existing = await loadGlobalConfig() || {};
  const merged = { ...existing, ...config };
  await fs.writeFile(configPath, JSON.stringify(merged, null, 2) + "\n");
  debug("Saved global config: %O", merged);
}
async function getWorkspaceId(cwd = process.cwd()) {
  if (process.env.GUILD_WORKSPACE_ID) {
    debug(
      "Using workspace from GUILD_WORKSPACE_ID env var: %s",
      process.env.GUILD_WORKSPACE_ID
    );
    return { workspaceId: process.env.GUILD_WORKSPACE_ID, source: "env" };
  }
  const config = await loadConfig(cwd);
  if (config.local?.workspace_id) {
    debug("Using workspace from local config: %s", config.local.workspace_id);
    return { workspaceId: config.local.workspace_id, source: "local" };
  }
  if (config.global?.default_workspace) {
    debug("Using workspace from global config: %s", config.global.default_workspace);
    return { workspaceId: config.global.default_workspace, source: "global" };
  }
  debug("No workspace configured in local or global config");
  return void 0;
}
async function isAgentDirectory(cwd = process.cwd()) {
  return fileExists(getLocalConfigPath(cwd));
}
function getWorkspaceSourceLabel(source) {
  if (source === "local") return "guild.json";
  if (source === "global") return "global config";
  return void 0;
}

// src/lib/event-filter.ts
var USER_EVENT_TYPES = [
  "user_message",
  "agent_notification_message",
  "agent_notification_progress",
  "agent_notification_error",
  "credentials_request",
  "agent_install_request",
  "trigger_message",
  "system_error"
];
var SYSTEM_EVENT_TYPES = [
  "agent_console",
  "runtime_start",
  "runtime_running",
  "runtime_waiting",
  "runtime_error",
  "runtime_done",
  "llm_start",
  "llm_done"
];
var DEFAULT_EVENT_TYPES = new Set(USER_EVENT_TYPES);
function parseEventFilter(raw) {
  const tokens = raw.split(",").map((t) => t.trim()).filter(Boolean);
  if (tokens.length === 1 && tokens[0] === "none") {
    return /* @__PURE__ */ new Set();
  }
  const result = /* @__PURE__ */ new Set();
  for (const token of tokens) {
    switch (token) {
      case "all":
        for (const t of USER_EVENT_TYPES) result.add(t);
        for (const t of SYSTEM_EVENT_TYPES) result.add(t);
        break;
      case "user":
        for (const t of USER_EVENT_TYPES) result.add(t);
        break;
      case "system":
        for (const t of SYSTEM_EVENT_TYPES) result.add(t);
        break;
      default:
        result.add(token);
    }
  }
  return result;
}
function shouldShowEvent(type, filter) {
  return filter.has(type);
}

export {
  GuildAPIClient,
  getGlobalConfigDir,
  getGlobalConfigPath,
  getLocalConfigPath,
  loadGlobalConfig,
  loadLocalConfig,
  loadConfig,
  saveGlobalConfig,
  getWorkspaceId,
  isAgentDirectory,
  getWorkspaceSourceLabel,
  USER_EVENT_TYPES,
  SYSTEM_EVENT_TYPES,
  DEFAULT_EVENT_TYPES,
  parseEventFilter,
  shouldShowEvent
};
//# sourceMappingURL=chunk-RJHD6XTV.js.map
