#!/usr/bin/env node
'use strict';

var commander = require('commander');
var fs = require('fs');
var autonomousAgent = require('@epicdm/flowstate-agents/agent/autonomous-agent');
var nanoid = require('nanoid');
var child_process = require('child_process');

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var fs__namespace = /*#__PURE__*/_interopNamespace(fs);

// src/core/ObsSessionContext.ts
var ObsSessionContext = class _ObsSessionContext {
  static instance;
  context = {};
  /**
   * Private constructor to enforce singleton pattern
   */
  constructor() {
  }
  /**
   * Get singleton instance
   * @returns The singleton instance of ObsSessionContext
   */
  static getInstance() {
    if (!this.instance) {
      this.instance = new _ObsSessionContext();
    }
    return this.instance;
  }
  /**
   * Set session context and update environment variables
   * This performs a shallow merge with existing context.
   *
   * @param data - Partial session context data to set
   *
   * @example
   * ```typescript
   * const obsContext = ObsSessionContext.getInstance();
   * obsContext.setContext({
   *   projectId: 'proj-123',
   *   taskId: 'task-456'
   * });
   * ```
   */
  setContext(data) {
    this.context = { ...this.context, ...data };
    if (data.projectId) {
      process.env.FLOWSTATE_PROJECT_ID = data.projectId;
    }
    if (data.taskId) {
      process.env.FLOWSTATE_TASK_ID = data.taskId;
    }
    if (data.specName) {
      process.env.FLOWSTATE_SPEC = data.specName;
    }
    if (data.userId) {
      process.env.FLOWSTATE_USER_ID = data.userId;
    }
    if (data.gitBranch) {
      process.env.FLOWSTATE_GIT_BRANCH = data.gitBranch;
    }
    if (data.workingDirectory) {
      process.env.FLOWSTATE_WORKING_DIR = data.workingDirectory;
    }
  }
  /**
   * Get current session context
   * @returns Current session context data
   *
   * @example
   * ```typescript
   * const obsContext = ObsSessionContext.getInstance();
   * const context = obsContext.getContext();
   * console.log(context.projectId);
   * ```
   */
  getContext() {
    return { ...this.context };
  }
  /**
   * Clear all session context and environment variables
   *
   * @example
   * ```typescript
   * const obsContext = ObsSessionContext.getInstance();
   * obsContext.clearContext();
   * ```
   */
  clearContext() {
    this.context = {};
    delete process.env.FLOWSTATE_PROJECT_ID;
    delete process.env.FLOWSTATE_TASK_ID;
    delete process.env.FLOWSTATE_SPEC;
    delete process.env.FLOWSTATE_USER_ID;
    delete process.env.FLOWSTATE_GIT_BRANCH;
    delete process.env.FLOWSTATE_WORKING_DIR;
  }
  /**
   * Reset singleton instance (primarily for testing)
   * @internal
   */
  static resetInstance() {
    if (this.instance) {
      this.instance.clearContext();
    }
    this.instance = null;
  }
};
var program = new commander.Command();
program.name("flowstate-agent").description("Autonomous agent for Epic FlowState spec workflow execution").version("1.0.0");
program.command("run").description("Run autonomous agent for a spec workflow").requiredOption("--spec-name <name>", "Specification name").requiredOption("--description <desc>", "Specification description").option("--config <path>", "Path to agent config file", "./agent-config.json").option("--server-url <url>", "RxDB server URL (overrides config)", process.env.RXDB_SERVER_URL).option("--auth-token <token>", "Auth token (overrides config)", process.env.AUTH_TOKEN).option("--domain-id <id>", "Domain ID (overrides config)", process.env.DOMAIN_ID).option("--user-id <id>", "User ID (overrides config)", process.env.USER_ID).option("--org-id <id>", "Org ID (overrides config)", process.env.ORG_ID).option(
  "--claude-api-key <key>",
  "Claude API key (overrides config)",
  process.env.ANTHROPIC_API_KEY
).action(async (options) => {
  const obsContext = ObsSessionContext.getInstance();
  try {
    console.log("[INFO] Loading agent configuration...");
    const config = loadConfig(options);
    const gitBranch = getCurrentGitBranch();
    const contextData = {
      specName: options.specName,
      userId: config.userId,
      workingDirectory: process.cwd()
    };
    if (gitBranch) contextData.gitBranch = gitBranch;
    obsContext.setContext(contextData);
    const agent = new autonomousAgent.AutonomousAgent(config);
    await agent.initialize();
    await agent.executeSpec(options.specName, options.description);
    await agent.stop();
    process.exit(0);
  } catch (error) {
    console.error("[ERROR] Agent execution failed:", error);
    process.exit(1);
  } finally {
    obsContext.clearContext();
  }
});
program.command("status").description("Get agent status").option("--config <path>", "Path to agent config file", "./agent-config.json").action(async (options) => {
  try {
    const config = loadConfig(options);
    const agent = new autonomousAgent.AutonomousAgent(config);
    await agent.initialize();
    const status = agent.getStatus();
    console.log("Agent Status:", JSON.stringify(status, null, 2));
    await agent.stop();
    process.exit(0);
  } catch (error) {
    console.error("[ERROR] Failed to get status:", error);
    process.exit(1);
  }
});
program.command("init").description("Create default agent configuration file").option("--output <path>", "Output path for config file", "./agent-config.json").action((options) => {
  try {
    const defaultConfig = {
      agentId: nanoid.nanoid(10),
      agentName: "flowstate-agent",
      autoApprove: ["requirements", "design"],
      manualApprove: ["tasks"],
      maxRetries: 3,
      retryDelayMs: 2e3,
      maxConcurrentTasks: 1,
      logLevel: "info",
      logToFile: false,
      serverUrl: process.env.KONG_GATEWAY_URL || "http://localhost:7080",
      authToken: process.env.AUTH_TOKEN || "",
      domainId: process.env.DOMAIN_ID || "",
      userId: process.env.USER_ID || "",
      orgId: process.env.ORG_ID || "",
      collections: [
        "projects",
        "milestones",
        "tasks",
        "logs",
        "approvals",
        "templates",
        "steeringdocuments"
      ],
      claudeApiKey: process.env.ANTHROPIC_API_KEY || "",
      claudeModel: "claude-sonnet-4-5-20250929",
      claudeMaxTokens: 4096
    };
    fs__namespace.writeFileSync(options.output, JSON.stringify(defaultConfig, null, 2));
    console.log(`[INFO] Created agent configuration at: ${options.output}`);
    console.log("[INFO] Please update the configuration with your RxDB server credentials");
    process.exit(0);
  } catch (error) {
    console.error("[ERROR] Failed to create config:", error);
    process.exit(1);
  }
});
function getCurrentGitBranch() {
  try {
    const branch = child_process.execSync("git rev-parse --abbrev-ref HEAD", {
      cwd: process.cwd(),
      stdio: "pipe",
      encoding: "utf-8"
    }).trim();
    return branch;
  } catch {
    return void 0;
  }
}
function loadConfig(options) {
  let config = {};
  if (fs__namespace.existsSync(options.config)) {
    const fileContent = fs__namespace.readFileSync(options.config, "utf-8");
    config = JSON.parse(fileContent);
    console.log(`[INFO] Loaded config from: ${options.config}`);
  } else {
    console.log("[WARN] Config file not found, using defaults and environment variables");
    config = {
      agentId: nanoid.nanoid(10),
      agentName: "flowstate-agent",
      autoApprove: ["requirements", "design"],
      manualApprove: ["tasks"],
      maxRetries: 3,
      retryDelayMs: 2e3,
      maxConcurrentTasks: 1,
      logLevel: "info",
      collections: [
        "projects",
        "milestones",
        "tasks",
        "logs",
        "approvals",
        "templates",
        "steeringdocuments"
      ]
    };
  }
  const finalConfig = {
    agentId: config.agentId || nanoid.nanoid(10),
    agentName: config.agentName || "flowstate-agent",
    autoApprove: config.autoApprove || ["requirements", "design"],
    manualApprove: config.manualApprove || ["tasks"],
    maxRetries: config.maxRetries || 3,
    retryDelayMs: config.retryDelayMs || 2e3,
    maxConcurrentTasks: config.maxConcurrentTasks || 1,
    logLevel: config.logLevel || "info",
    logToFile: config.logToFile || false,
    serverUrl: options.serverUrl || config.serverUrl || process.env.KONG_GATEWAY_URL || "http://localhost:7080",
    authToken: options.authToken || config.authToken || "",
    domainId: options.domainId || config.domainId || "flowstate-dev",
    userId: options.userId || config.userId,
    orgId: options.orgId || config.orgId,
    collections: config.collections || [
      "projects",
      "milestones",
      "tasks",
      "logs",
      "approvals",
      "templates",
      "steeringdocuments"
    ],
    ...config.logFilePath && { logFilePath: config.logFilePath },
    ...(options.claudeApiKey || config.claudeApiKey) && {
      claudeApiKey: options.claudeApiKey || config.claudeApiKey
    },
    ...config.claudeModel && { claudeModel: config.claudeModel },
    ...config.claudeMaxTokens && { claudeMaxTokens: config.claudeMaxTokens }
  };
  if (!finalConfig.orgId) {
    console.error("[cli-agent] ORG_ID is required. Set env var or configure in agent config.");
    process.exit(1);
  }
  if (!finalConfig.userId) {
    console.error("[cli-agent] USER_ID is required. Set env var or configure in agent config.");
    process.exit(1);
  }
  return finalConfig;
}
program.parse();
//# sourceMappingURL=cli-agent.js.map
//# sourceMappingURL=cli-agent.js.map