var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require2() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));

// src/agents/discipline.ts
var discipline_exports = {};
__export(discipline_exports, {
  DISCIPLINE_CONFIGS: () => DISCIPLINE_CONFIGS,
  DisciplineAgent: () => DisciplineAgent,
  allAgents: () => allAgents,
  clearAgentCache: () => clearAgentCache,
  getAgent: () => getAgent,
  routeToDiscipline: () => routeToDiscipline
});
function routeToDiscipline(task) {
  const lower = task.toLowerCase();
  let best = "quick";
  let bestScore = 0;
  for (const entry of KEYWORD_MAP) {
    let score = 0;
    for (const kw of entry.keywords) {
      if (lower.includes(kw)) {
        score += kw.length;
      }
    }
    if (score > bestScore) {
      bestScore = score;
      best = entry.discipline;
    }
  }
  return best;
}
function buildStepPrompt(step2, upstreamResults) {
  const action = step2.config?.["prompt"] ?? step2.name;
  const deps = step2.config?.["dependencies"];
  if (deps && deps.length > 0) {
    const contextParts = [];
    for (const depId of deps) {
      const result = upstreamResults.get(depId);
      if (result?.output) {
        const depStep = step2.config?.["__depNames"];
        const depName = depStep?.[depId] ?? depId;
        contextParts.push(`### Output from step "${depName}" (${depId}):
${result.output}`);
      }
    }
    if (contextParts.length > 0) {
      return `## Context from previous steps

${contextParts.join("\n\n")}

---

## Your task

${action}`;
    }
  }
  return action;
}
function buildSystemPrompt(config, step2, workflowName) {
  return [
    config.systemPrompt,
    "",
    `You are executing step "${step2.name}" (${step2.id}) of the SoloFlow workflow "${workflowName}".`,
    "You have access to all OpenClaw tools. Use them to complete your task.",
    "When done, provide a concise summary of what you accomplished.",
    "Include any important results, file paths, or data that downstream steps may need."
  ].join("\n");
}
function getAgent(discipline) {
  let agent = agentCache.get(discipline);
  if (!agent) {
    agent = new DisciplineAgent(discipline);
    agentCache.set(discipline, agent);
  }
  return agent;
}
function clearAgentCache() {
  agentCache.clear();
}
function allAgents() {
  const map = /* @__PURE__ */ new Map();
  for (const d of ["deep", "quick", "visual", "ultrabrain"]) {
    map.set(d, getAgent(d));
  }
  return map;
}
var DISCIPLINE_CONFIGS, KEYWORD_MAP, DisciplineAgent, LRUAgentCache, agentCache;
var init_discipline = __esm({
  "src/agents/discipline.ts"() {
    "use strict";
    DISCIPLINE_CONFIGS = {
      deep: {
        defaultModel: "minimax-portal/MiniMax-M2.7-highspeed",
        maxTokens: 8192,
        temperature: 0.3,
        stepTimeoutMs: 12e4,
        systemPrompt: "You are a deep-reasoning agent. Perform thorough research, multi-step analysis, and produce well-structured, detailed output. Prefer correctness over speed. Use tools when needed to complete your task."
      },
      quick: {
        defaultModel: "minimax-portal/MiniMax-M2.7-highspeed",
        maxTokens: 2048,
        temperature: 0.5,
        stepTimeoutMs: 6e4,
        systemPrompt: "You are a fast-response agent. Complete the task quickly with a concise answer. Optimise for speed and brevity. Use tools when needed."
      },
      visual: {
        defaultModel: "minimax-portal/MiniMax-M2.7-highspeed",
        maxTokens: 4096,
        temperature: 0.6,
        stepTimeoutMs: 12e4,
        systemPrompt: "You are a visual/frontend agent. Focus on UI design, frontend code, image generation, and visual quality. Produce pixel-perfect output. Use tools when needed."
      },
      ultrabrain: {
        defaultModel: "minimax-portal/MiniMax-M2.7-highspeed",
        maxTokens: 16384,
        temperature: 0.2,
        stepTimeoutMs: 3e5,
        systemPrompt: "You are an ultrabrain agent. Solve hard logic, algorithms, and architecture problems. Use chain-of-thought reasoning. Prioritise rigour and correctness. Use tools when needed."
      }
    };
    KEYWORD_MAP = [
      {
        keywords: ["research", "analyze", "analyse", "investigate", "deep dive", "compare", "review", "report", "summarize", "summarise"],
        discipline: "deep"
      },
      {
        keywords: ["quick", "fast", "simple", "lookup", "convert", "format", "tell me", "what is", "who is"],
        discipline: "quick"
      },
      {
        keywords: ["design", "ui", "frontend", "layout", "image", "screenshot", "visual", "css", "html", "component", "figma", "mockup"],
        discipline: "visual"
      },
      {
        keywords: ["algorithm", "architecture", "optimize", "optimise", "refactor", "logic", "complex", "math", "prove", "derive", "solve", "debug", "reverse-engineer"],
        discipline: "ultrabrain"
      }
    ];
    DisciplineAgent = class {
      discipline;
      config;
      currentWorkflow = null;
      constructor(discipline) {
        this.discipline = discipline;
        this.config = DISCIPLINE_CONFIGS[discipline];
      }
      /** Classify an arbitrary input string to a discipline. */
      classify(input) {
        return routeToDiscipline(input);
      }
      /**
       * Execute a workflow step via OpenClaw subagent.
       *
       * The subagent gets its own session with full tool access.
       * Upstream step results are injected as context in the prompt.
       */
      async execute(step2, api, upstreamResults, workflowName) {
        if (!api) {
          return {
            stepId: step2.id,
            discipline: this.discipline,
            output: null,
            error: "OpenClaw API not provided \u2014 cannot execute without runtime"
          };
        }
        const startedAt = Date.now();
        this.currentWorkflow = step2.id;
        const prompt = buildStepPrompt(step2, upstreamResults ?? /* @__PURE__ */ new Map());
        buildSystemPrompt(this.config, step2, workflowName ?? "unknown");
        try {
          const runtime = api.runtime;
          if (!runtime?.subagent?.run) {
            return {
              stepId: step2.id,
              discipline: this.discipline,
              output: null,
              error: "api.runtime.subagent not available \u2014 plugin may need subagent permission"
            };
          }
          const sessionKey = `agent:main:subagent:soloflow:${step2.id}:${Date.now()}`;
          const { runId } = await runtime.subagent.run({
            sessionKey,
            message: prompt,
            model: this.config.defaultModel || void 0
          });
          const runResult = await runtime.subagent.waitForRun({
            runId,
            timeoutMs: this.config.stepTimeoutMs
          });
          if (runResult?.error) {
            return {
              stepId: step2.id,
              discipline: this.discipline,
              output: null,
              durationMs: Date.now() - startedAt,
              error: runResult.error
            };
          }
          let output = null;
          try {
            const { messages } = await runtime.subagent.getSessionMessages({
              sessionKey,
              limit: 5
            });
            for (let i = messages.length - 1; i >= 0; i--) {
              const msg = messages[i];
              if (!msg || msg.role !== "assistant") continue;
              const content = msg.content;
              if (typeof content === "string") {
                output = content;
              } else if (Array.isArray(content)) {
                const textParts = content.filter((block) => block.type === "text").map((block) => block.text).filter(Boolean);
                if (textParts.length > 0) {
                  output = textParts.join("\n");
                }
              }
              if (output) break;
            }
          } catch (e) {
            console.warn(`error: ${e}`);
          }
          return {
            stepId: step2.id,
            discipline: this.discipline,
            output,
            durationMs: Date.now() - startedAt
          };
        } catch (err) {
          return {
            stepId: step2.id,
            discipline: this.discipline,
            output: null,
            durationMs: Date.now() - startedAt,
            error: err instanceof Error ? err.message : String(err)
          };
        } finally {
          this.currentWorkflow = null;
        }
      }
    };
    LRUAgentCache = class {
      constructor(maxSize = 20) {
        this.maxSize = maxSize;
      }
      maxSize;
      cache = /* @__PURE__ */ new Map();
      get(discipline) {
        const agent = this.cache.get(discipline);
        if (agent !== void 0) {
          this.cache.delete(discipline);
          this.cache.set(discipline, agent);
        }
        return agent;
      }
      set(discipline, agent) {
        if (this.cache.has(discipline)) {
          this.cache.delete(discipline);
        } else if (this.cache.size >= this.maxSize) {
          const firstKey = this.cache.keys().next().value;
          if (firstKey !== void 0) this.cache.delete(firstKey);
        }
        this.cache.set(discipline, agent);
      }
      clear() {
        this.cache.clear();
      }
    };
    agentCache = new LRUAgentCache(20);
  }
});

// src/hooks/index.ts
var hooks_exports = {};
__export(hooks_exports, {
  HookSystem: () => HookSystem,
  getMetrics: () => getMetrics,
  hookSystem: () => hookSystem,
  onStepComplete: () => onStepComplete,
  onStepError: () => onStepError,
  onWorkflowComplete: () => onWorkflowComplete,
  onWorkflowFail: () => onWorkflowFail,
  onWorkflowStart: () => onWorkflowStart,
  registerBuiltinHooks: () => registerBuiltinHooks,
  registerHooks: () => registerHooks,
  unregisterHooks: () => unregisterHooks
});
function getMetrics() {
  return metrics;
}
function onWorkflowStart(ctx) {
  metrics.started++;
  console.log(
    `[SoloFlow] workflow started: ${ctx.workflow?.name ?? ctx.workflow?.id ?? "unknown"} (${ctx.workflow?.steps.size ?? 0} steps)`
  );
}
function onWorkflowComplete(ctx) {
  metrics.completed++;
  const wf = ctx.workflow;
  if (wf) {
    metrics.totalDurationMs += Date.now() - wf.createdAt;
  }
  console.log(
    `[SoloFlow] workflow completed: ${wf?.name ?? wf?.id ?? "unknown"} duration\u2248${metrics.totalDurationMs}ms`
  );
}
function onWorkflowFail(ctx) {
  metrics.failed++;
  console.error(
    `[SoloFlow] workflow failed: ${ctx.workflow?.name ?? ctx.workflow?.id ?? "unknown"}`,
    ctx.metadata?.["error"] ?? ""
  );
}
function onStepComplete(ctx) {
  console.log(
    `[SoloFlow] step completed: ${ctx.step?.name ?? ctx.step?.id ?? "unknown"} in workflow ${ctx.workflow?.id ?? "?"}`
  );
}
function onStepError(ctx) {
  console.error(
    `[SoloFlow] step failed: ${ctx.step?.name ?? ctx.step?.id ?? "unknown"} in workflow ${ctx.workflow?.id ?? "?"}`,
    ctx.step?.error ?? ctx.metadata?.["error"] ?? ""
  );
}
function registerBuiltinHooks(system = hookSystem) {
  const unsubs = [
    system.register("workflow:started", onWorkflowStart),
    system.register("workflow:completed", onWorkflowComplete),
    system.register("workflow:failed", onWorkflowFail),
    system.register("step:completed", onStepComplete),
    system.register("step:failed", onStepError)
  ];
  return () => unsubs.forEach((fn) => fn());
}
function registerHooks(_api, _system = hookSystem) {
  return () => {
  };
}
function unregisterHooks(_api) {
}
var HookSystem, hookSystem, metrics;
var init_hooks = __esm({
  "src/hooks/index.ts"() {
    "use strict";
    HookSystem = class {
      handlers = /* @__PURE__ */ new Map();
      /** Register a handler for an event. Returns an unsubscribe function. */
      register(event, handler) {
        let set = this.handlers.get(event);
        if (!set) {
          set = /* @__PURE__ */ new Set();
          this.handlers.set(event, set);
        }
        set.add(handler);
        return () => this.unregister(event, handler);
      }
      /** Remove a specific handler from an event. */
      unregister(event, handler) {
        this.handlers.get(event)?.delete(handler);
      }
      /** Emit an event synchronously. Non-throwing — errors are swallowed. */
      emit(event, context) {
        const set = this.handlers.get(event);
        if (!set) return;
        for (const handler of set) {
          try {
            handler(context);
          } catch (e) {
            console.warn(`error: ${e}`);
          }
        }
      }
      /** Emit an event asynchronously. All handlers run in parallel; errors are swallowed. */
      async emitAsync(event, context) {
        const set = this.handlers.get(event);
        if (!set) return;
        const promises = [...set].map(async (handler) => {
          try {
            await handler(context);
          } catch (e) {
            console.warn(`error: ${e}`);
          }
        });
        await Promise.all(promises);
      }
      /** Remove all handlers for every event. */
      clear() {
        this.handlers.clear();
      }
    };
    hookSystem = new HookSystem();
    metrics = { started: 0, completed: 0, failed: 0, totalDurationMs: 0 };
  }
});

// src/memory/entity-extractor.ts
var EntityExtractor;
var init_entity_extractor = __esm({
  "src/memory/entity-extractor.ts"() {
    "use strict";
    EntityExtractor = class {
      // Regex patterns for common entity types
      patterns = /* @__PURE__ */ new Map();
      llmExtractor = null;
      constructor() {
        this.initPatterns();
      }
      /** Set an optional LLM-based entity extractor */
      setLLMExtractor(fn) {
        this.llmExtractor = fn;
      }
      /**
       * Decompose a document into paragraphs + entities (R³Mem pipeline).
       * Returns paragraphs with their extracted entities.
       */
      async decompose(document) {
        const start = Date.now();
        const paragraphs = this.splitIntoParagraphs(document);
        let allEntities = [];
        let method = "regex";
        for (const para of paragraphs) {
          const regexEntities = this.extractByRegex(para.content, para.id);
          let llmEntities = [];
          if (this.llmExtractor && para.content.length > 50) {
            try {
              llmEntities = await this.llmExtractor(para.content);
              method = "combined";
            } catch (e) {
              console.warn(`error: ${e}`);
            }
          }
          const regexTexts = new Set(regexEntities.map((e) => e.text.toLowerCase()));
          for (const re of regexEntities) {
            allEntities.push(re);
          }
          for (const le of llmEntities) {
            if (!regexTexts.has(le.text.toLowerCase())) {
              allEntities.push({ ...le, confidence: le.confidence * 0.8 });
            }
          }
          para.entities = [...regexEntities, ...llmEntities.filter(
            (le) => !regexTexts.has(le.text.toLowerCase())
          )];
        }
        const seen = /* @__PURE__ */ new Map();
        for (const entity of allEntities) {
          const key = `${entity.type}:${entity.text.toLowerCase()}`;
          const existing = seen.get(key);
          if (!existing || entity.confidence > existing.confidence) {
            seen.set(key, entity);
          }
        }
        const dedupedEntities = Array.from(seen.values());
        return {
          paragraphs,
          entities: dedupedEntities,
          stats: {
            paragraphCount: paragraphs.length,
            entityCount: dedupedEntities.length,
            method,
            durationMs: Date.now() - start
          }
        };
      }
      /** Extract entities using regex patterns only */
      extractByRegex(text, sourceId) {
        const entities = [];
        for (const [type, patterns] of this.patterns) {
          for (const pattern of patterns) {
            try {
              for (const match of text.matchAll(pattern)) {
                const matched = match[1] || match[0] || "";
                if (matched.length >= 2 && matched.length <= 100) {
                  entities.push({
                    text: matched,
                    type,
                    confidence: 0.7,
                    sourceId
                  });
                }
              }
            } catch (e) {
              console.warn(`error: ${e}`);
            }
          }
        }
        return entities;
      }
      /** Query entities by type and/or text */
      queryEntities(entities, filter) {
        let results = entities;
        if (filter?.types?.length) {
          results = results.filter((e) => filter.types.includes(e.type));
        }
        if (filter?.text) {
          const query = filter.text.toLowerCase();
          results = results.filter(
            (e) => e.text.toLowerCase().includes(query) || query.includes(e.text.toLowerCase())
          );
        }
        if (filter?.minConfidence) {
          results = results.filter((e) => e.confidence >= filter.minConfidence);
        }
        const seen = /* @__PURE__ */ new Set();
        return results.filter((e) => {
          const key = e.text.toLowerCase();
          if (seen.has(key)) return false;
          seen.add(key);
          return true;
        });
      }
      splitIntoParagraphs(document) {
        const content = document.content;
        const separators = content.includes("\n\n") ? "\n\n" : "\n";
        const chunks = content.split(separators).filter((c) => c.trim().length > 10);
        return chunks.map((chunk, idx) => ({
          id: `para_${document.id}_${idx}`,
          sourceDocumentId: document.id,
          index: idx + 1,
          content: chunk.trim(),
          createdAt: document.createdAt
        }));
      }
      initPatterns() {
        this.patterns.set("tool", [
          /(?:use|using|called|tool|command|run)\s+`([^`]+)`/gi,
          /(?:called|named)\s+["']([^"']+)["']/gi,
          /\b(?:npm|npx|pip|cargo|go|docker|kubectl|git|gh|openclaw|mcporter|skillhub)\s+(\S+)/gi,
          /\b([A-Z][a-z]+(?:[A-Z][a-z]+)+)\b/g
          // PascalCase tool names
        ]);
        this.patterns.set("project", [
          /\b([A-Z][a-z]+(?:Press|Flow|Hub|Bot|Kit|Lib|Engine|CLI|API|SDK))\b/g,
          /(?:repo|project|module)\s+["']?([\w\-./]+)["']?/gi,
          /([\w\-]+)\/([\w\-]+)(?:\.git)?/g
          // owner/repo pattern
        ]);
        this.patterns.set("person", [
          /(?:user|author|created by|maintained by|said|says)\s+["']?([A-Z][a-z]+(?:\s+[A-Z][a-z]+)?)["']?/gi
        ]);
        this.patterns.set("organization", [
          /\b(?:OpenAI|Anthropic|Google|Meta|Microsoft|Apple|Amazon|GitHub|Cloudflare|Vercel|Netlify|OpenClaw)\b/gi
        ]);
        this.patterns.set("date", [
          /\b(\d{4}[-/]\d{2}[-/]\d{2})\b/g,
          /\b(\d{1,2}:\d{2}(?::\d{2})?(?:\s*[AP]M)?)\b/gi,
          /\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\w*\s+\d{1,2},?\s+\d{4}\b/gi
        ]);
        this.patterns.set("concept", [
          /\b(?:DAG|FSM|RRF|MMR|FTS5|NER|LLM|MCP|API|SDK|RBAC|SQLite|FTS|JSON|YAML|TypeScript|JavaScript|Python)\b/gi
        ]);
        this.patterns.set("location", [
          /\b(?:Beijing|Shanghai|Tokyo|London|New York|San Francisco|Berlin|Paris)\b/gi
        ]);
      }
    };
  }
});

// src/memory/working-memory.ts
var DEFAULT_WORKING_CAPACITY, WorkingMemory;
var init_working_memory = __esm({
  "src/memory/working-memory.ts"() {
    "use strict";
    DEFAULT_WORKING_CAPACITY = 256;
    WorkingMemory = class {
      store = /* @__PURE__ */ new Map();
      capacity;
      namespace;
      constructor(namespace, capacity = DEFAULT_WORKING_CAPACITY) {
        this.namespace = namespace;
        this.capacity = capacity;
      }
      set(key, value, source = "system", extra) {
        const existing = this.findByKey(key);
        const now2 = Date.now();
        if (existing) {
          const updated = {
            ...existing,
            value,
            source,
            updatedAt: now2,
            tags: extra?.tags ?? existing.tags,
            workflowId: extra?.workflowId ?? existing.workflowId,
            stepId: extra?.stepId ?? existing.stepId
          };
          this.store.set(existing.id, updated);
          return updated;
        }
        this.evictIfNeeded();
        const entry = {
          id: `wm_${this.namespace}_${now2}_${crypto.randomUUID()}`,
          namespace: this.namespace,
          key,
          value,
          source,
          workflowId: extra?.workflowId,
          stepId: extra?.stepId,
          tags: extra?.tags ?? [],
          createdAt: now2,
          updatedAt: now2
        };
        this.store.set(entry.id, entry);
        return entry;
      }
      get(key) {
        return this.findByKey(key);
      }
      getByStep(stepId) {
        const results = [];
        for (const entry of this.store.values()) {
          if (entry.stepId === stepId) results.push(entry);
        }
        return results;
      }
      getByWorkflow(workflowId) {
        const results = [];
        for (const entry of this.store.values()) {
          if (entry.workflowId === workflowId) results.push(entry);
        }
        return results;
      }
      delete(key) {
        const entry = this.findByKey(key);
        if (!entry) return false;
        return this.store.delete(entry.id);
      }
      clear() {
        this.store.clear();
      }
      get size() {
        return this.store.size;
      }
      query(query) {
        const text = query.text?.toLowerCase();
        const tags = query.tags;
        const results = [];
        for (const entry of this.store.values()) {
          let score = 1;
          if (text) {
            const haystack = `${entry.key} ${JSON.stringify(entry.value)} ${entry.tags.join(" ")}`.toLowerCase();
            if (!haystack.includes(text)) continue;
            score = 0.6 + 0.4 * (text.length / haystack.length);
          }
          if (tags?.length) {
            const hasAll = tags.every((t) => entry.tags.includes(t));
            if (!hasAll) continue;
          }
          results.push({ tier: "working", entry, score });
        }
        results.sort((a, b) => b.score - a.score);
        return results.slice(0, query.limit ?? 10);
      }
      all() {
        return Array.from(this.store.values());
      }
      findByKey(key) {
        for (const entry of this.store.values()) {
          if (entry.key === key) return entry;
        }
        return void 0;
      }
      evictIfNeeded() {
        if (this.store.size < this.capacity) return;
        let oldest;
        for (const entry of this.store.values()) {
          if (!oldest || entry.updatedAt < oldest.updatedAt) {
            oldest = entry;
          }
        }
        if (oldest) this.store.delete(oldest.id);
      }
    };
  }
});

// src/memory/episodic-memory.ts
var DEFAULT_EPISODIC_CAPACITY, DEFAULT_COMPRESSION_THRESHOLD_MS, EpisodicMemory;
var init_episodic_memory = __esm({
  "src/memory/episodic-memory.ts"() {
    "use strict";
    DEFAULT_EPISODIC_CAPACITY = 500;
    DEFAULT_COMPRESSION_THRESHOLD_MS = 12 * 60 * 60 * 1e3;
    EpisodicMemory = class {
      store = /* @__PURE__ */ new Map();
      persistCallback = null;
      capacity;
      compressionThresholdMs;
      namespace;
      constructor(namespace, capacity = DEFAULT_EPISODIC_CAPACITY, compressionThresholdMs = DEFAULT_COMPRESSION_THRESHOLD_MS) {
        this.namespace = namespace;
        this.capacity = capacity;
        this.compressionThresholdMs = compressionThresholdMs;
      }
      storeExecution(workflow) {
        const existingKey = Array.from(this.store.keys()).find(
          (key) => this.store.get(key)?.workflowId === workflow.id
        );
        if (existingKey) this.store.delete(existingKey);
        if (this.deletePersistCallback) {
          try {
            this.deletePersistCallback(workflow.id);
          } catch (e) {
            console.warn(`non-critical: ${e}`);
          }
        }
        const now2 = Date.now();
        const durationMs = this.computeDuration(workflow);
        const stepSummary = Array.from(workflow.steps.values()).map((step2) => ({
          stepId: step2.id,
          name: step2.name,
          discipline: step2.discipline,
          durationMs: step2.startedAt && step2.completedAt ? step2.completedAt - step2.startedAt : 0,
          success: step2.state === "completed"
        }));
        const entry = {
          id: `ep_${this.namespace}_${now2}_${crypto.randomUUID()}`,
          namespace: this.namespace,
          workflowId: workflow.id,
          workflowName: workflow.name,
          finalState: workflow.state,
          durationMs,
          stepSummary,
          compressed: false,
          rawData: this.serializeWorkflow(workflow),
          source: "workflow_execution",
          tags: [workflow.name, workflow.state, ...this.extractDisciplines(stepSummary)],
          createdAt: now2,
          updatedAt: now2
        };
        this.store.set(entry.id, entry);
        if (this.persistCallback) {
          try {
            this.persistCallback(entry);
          } catch (e) {
            console.warn(`non-critical: ${e}`);
          }
        }
        this.triggerCompressionIfNeeded();
        this.evictIfNeeded();
        return entry;
      }
      getRecentExecutions(limit = 10) {
        const sorted = Array.from(this.store.values()).sort(
          (a, b) => b.createdAt - a.createdAt
        );
        return sorted.slice(0, limit);
      }
      getByWorkflow(workflowId) {
        const results = [];
        for (const entry of this.store.values()) {
          if (entry.workflowId === workflowId) results.push(entry);
        }
        return results;
      }
      searchExecutions(query) {
        const text = query.text?.toLowerCase();
        const tags = query.tags;
        const results = [];
        for (const entry of this.store.values()) {
          let score = 1;
          if (query.workflowId && entry.workflowId !== query.workflowId) continue;
          if (text) {
            const haystack = this.entryToSearchable(entry);
            if (!haystack.includes(text)) continue;
            score = 0.5 + 0.5 * (text.length / haystack.length);
          }
          if (tags?.length) {
            const hasAll = tags.every((t) => entry.tags.includes(t));
            if (!hasAll) continue;
          }
          results.push({ tier: "episodic", entry, score });
        }
        results.sort((a, b) => b.score - a.score);
        return results.slice(0, query.limit ?? 10);
      }
      delete(id) {
        return this.store.delete(id);
      }
      clear() {
        this.store.clear();
      }
      get size() {
        return this.store.size;
      }
      all() {
        return Array.from(this.store.values());
      }
      /** Restore entries from an external store (e.g., SQLite) */
      restoreEntries(entries) {
        for (const entry of entries) {
          this.store.set(entry.id, entry);
        }
      }
      deletePersistCallback = null;
      /** Set an external persist callback — called on every storeExecution() */
      setPersistCallback(cb) {
        this.persistCallback = cb;
      }
      setDeletePersistCallback(cb) {
        this.deletePersistCallback = cb;
      }
      compressOldEntries() {
        const threshold = Date.now() - this.compressionThresholdMs;
        let compressed = 0;
        for (const [id, entry] of this.store) {
          if (!entry.compressed && entry.createdAt < threshold && entry.rawData) {
            try {
              const raw = entry.rawData;
              const steps = raw?.steps ?? [];
              const keyResults = [];
              for (const step2 of steps) {
                if (step2.result && step2.state === "completed") {
                  const r = String(step2.result);
                  keyResults.push(r.length > 150 ? r.slice(0, 147) + "..." : r);
                } else if (step2.error) {
                  keyResults.push(`ERROR: ${String(step2.error).slice(0, 150)}`);
                }
              }
              const condensedResults = keyResults.length > 0 ? keyResults.join("\n") : void 0;
              const compressedEntry = {
                ...entry,
                rawData: void 0,
                compressed: true,
                source: "compressed_dag",
                tags: [...entry.tags, "compressed"],
                condensedResults,
                updatedAt: Date.now()
              };
              this.store.set(id, compressedEntry);
              compressed++;
            } catch (e) {
              console.warn(`error: ${e}`);
              const compressedEntry = {
                ...entry,
                rawData: void 0,
                compressed: true,
                source: "compressed_dag",
                tags: [...entry.tags, "compressed"],
                updatedAt: Date.now()
              };
              this.store.set(id, compressedEntry);
              compressed++;
            }
          }
        }
        return compressed;
      }
      computeDuration(workflow) {
        let earliest = Infinity;
        let latest = 0;
        for (const step2 of workflow.steps.values()) {
          if (step2.startedAt != null && step2.startedAt < earliest) earliest = step2.startedAt;
          if (step2.completedAt != null && step2.completedAt > latest) latest = step2.completedAt;
        }
        if (earliest === Infinity) return 0;
        return latest - earliest;
      }
      serializeWorkflow(workflow) {
        return {
          id: workflow.id,
          name: workflow.name,
          state: workflow.state,
          steps: Array.from(workflow.steps.entries()).map(([id, step2]) => ({
            id,
            name: step2.name,
            state: step2.state,
            result: step2.result,
            error: step2.error,
            startedAt: step2.startedAt,
            completedAt: step2.completedAt
          })),
          metadata: workflow.metadata
        };
      }
      extractDisciplines(summary) {
        const disciplines = new Set(summary.map((s) => s.discipline));
        return Array.from(disciplines);
      }
      entryToSearchable(entry) {
        const parts = [
          entry.workflowName,
          entry.finalState,
          ...entry.tags,
          ...entry.stepSummary.map((s) => `${s.name} ${s.discipline} ${s.success ? "success" : "failure"}`)
        ];
        if (entry.condensedResults) {
          parts.push(entry.condensedResults);
        }
        if (entry.rawData && typeof entry.rawData === "object" && Array.isArray(entry.rawData.steps)) {
          for (const step2 of entry.rawData.steps) {
            if (step2.result) {
              parts.push(String(step2.result));
            }
          }
        }
        return parts.join(" ").toLowerCase();
      }
      triggerCompressionIfNeeded() {
        if (this.store.size > this.capacity * 0.8) {
          this.compressOldEntries();
        }
      }
      evictIfNeeded() {
        while (this.store.size > this.capacity) {
          const entries = Array.from(this.store.values());
          let oldestCompressed;
          for (const entry of entries) {
            if (entry.compressed) {
              if (!oldestCompressed || entry.createdAt < oldestCompressed.createdAt) {
                oldestCompressed = entry;
              }
            }
          }
          if (oldestCompressed) {
            this.store.delete(oldestCompressed.id);
          } else {
            let oldest;
            for (const entry of entries) {
              if (!oldest || entry.createdAt < oldest.createdAt) {
                oldest = entry;
              }
            }
            if (oldest) this.store.delete(oldest.id);
          }
        }
      }
    };
  }
});

// src/memory/semantic-memory.ts
function cosineSimilarity(a, b) {
  if (a.length !== b.length || a.length === 0) return 0;
  let dot = 0;
  let normA = 0;
  let normB = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }
  const denom = Math.sqrt(normA) * Math.sqrt(normB);
  return denom === 0 ? 0 : dot / denom;
}
var DAY_MS, YEAR_MS, DEFAULT_FORGETTING_CONFIG, SemanticMemory;
var init_semantic_memory = __esm({
  "src/memory/semantic-memory.ts"() {
    "use strict";
    DAY_MS = 24 * 60 * 60 * 1e3;
    YEAR_MS = 365 * DAY_MS;
    DEFAULT_FORGETTING_CONFIG = {
      base: 1,
      stability: 14 * DAY_MS,
      importanceThreshold: 0.45,
      /** C-HLR+ per-category half-lives */
      categoryHalfLives: {
        fact: 14 * DAY_MS,
        preference: 30 * DAY_MS,
        skill: 60 * DAY_MS,
        pattern: 60 * DAY_MS,
        rule: 120 * DAY_MS
      }
    };
    SemanticMemory = class {
      store = /* @__PURE__ */ new Map();
      namespace;
      forgettingConfig;
      adapter = null;
      constructor(namespace, forgettingConfig) {
        this.namespace = namespace;
        this.forgettingConfig = { ...DEFAULT_FORGETTING_CONFIG, ...forgettingConfig };
      }
      setAdapter(adapter) {
        this.adapter = adapter;
      }
      async storeFact(key, value, importance = 0.5, extra) {
        const existing = this.findByKey(key);
        const now2 = Date.now();
        const category = extra?.category ?? existing?.category ?? "fact";
        const stability = this.computeStability(importance, category);
        const retrievability = this.computeRetrievability(now2, now2, stability, importance);
        if (existing) {
          const updated = {
            ...existing,
            value,
            importance,
            category: extra?.category ?? existing.category,
            tags: extra?.tags ?? existing.tags,
            embedding: extra?.embedding ?? existing.embedding,
            stability,
            retrievability,
            updatedAt: now2
          };
          this.store.set(existing.id, updated);
          await this.persistToAdapter(updated);
          return updated;
        }
        const entry = {
          id: `sm_${this.namespace}_${now2}_${crypto.randomUUID()}`,
          namespace: this.namespace,
          key,
          value,
          category,
          importance,
          accessCount: 0,
          lastAccessedAt: now2,
          stability,
          retrievability,
          embedding: extra?.embedding,
          tags: extra?.tags ?? [],
          createdAt: now2,
          updatedAt: now2
        };
        this.store.set(entry.id, entry);
        await this.persistToAdapter(entry);
        return entry;
      }
      async getFacts(query) {
        const entries = this.adapter?.connected ? await this.queryFromAdapter(query) : this.queryLocal(query);
        for (const result of entries) {
          if ("accessCount" in result.entry) {
            const sem = result.entry;
            const now2 = Date.now();
            const consolidated = this.consolidate({ ...sem, accessCount: sem.accessCount + 1, lastAccessedAt: now2 });
            const updated = {
              ...consolidated,
              retrievability: this.computeRetrievability(consolidated.createdAt, now2, consolidated.stability, consolidated.importance)
            };
            this.store.set(sem.id, updated);
            try {
              await this.persistToAdapter(updated);
            } catch (e) {
              console.warn(`non-critical: ${e}`);
            }
          }
        }
        return entries;
      }
      get(key) {
        const entry = this.findByKey(key);
        if (!entry) return void 0;
        const now2 = Date.now();
        const retrievability = this.computeRetrievability(
          entry.createdAt,
          now2,
          entry.stability,
          entry.importance
        );
        if (retrievability < this.forgettingConfig.importanceThreshold) return void 0;
        const consolidated = this.consolidate({ ...entry, accessCount: entry.accessCount + 1, lastAccessedAt: now2 });
        const updated = {
          ...consolidated,
          retrievability: this.computeRetrievability(consolidated.createdAt, now2, consolidated.stability, consolidated.importance),
          updatedAt: now2
        };
        this.store.set(entry.id, updated);
        try {
          this.persistToAdapter(updated);
        } catch (e) {
          console.warn(`non-critical: ${e}`);
        }
        return updated;
      }
      delete(key) {
        const entry = this.findByKey(key);
        if (!entry) return false;
        return this.store.delete(entry.id);
      }
      clear() {
        this.store.clear();
      }
      get size() {
        return this.store.size;
      }
      all() {
        return Array.from(this.store.values());
      }
      pruneForgotten() {
        const now2 = Date.now();
        let pruned = 0;
        for (const [id, entry] of this.store) {
          const r = this.computeRetrievability(entry.createdAt, now2, entry.stability, entry.importance);
          if (r < this.forgettingConfig.importanceThreshold) {
            this.store.delete(id);
            pruned++;
          }
        }
        return pruned;
      }
      refreshRetrievability() {
        const now2 = Date.now();
        for (const [id, entry] of this.store) {
          const r = this.computeRetrievability(entry.createdAt, now2, entry.stability, entry.importance);
          this.store.set(id, { ...entry, retrievability: r });
        }
      }
      computeRetrievability(createdAt, now2, stability, importance) {
        const elapsed = now2 - createdAt;
        if (stability <= 0) return 0;
        const decay = this.forgettingConfig.base * Math.exp(-elapsed / stability);
        return Math.max(0, Math.min(1, decay * importance));
      }
      computeStability(importance, category) {
        const baseStability = this.forgettingConfig.categoryHalfLives?.[category ?? "fact"] ?? this.forgettingConfig.stability;
        return baseStability * (0.5 + importance);
      }
      /** Spaced repetition: each access restrengthens the memory with diminishing returns */
      consolidate(entry) {
        const easeFactor = Math.max(0.05, 0.3 / (1 + entry.accessCount * 0.1));
        const newStability = entry.stability * (1 + easeFactor);
        return {
          ...entry,
          stability: Math.min(newStability, YEAR_MS)
        };
      }
      queryLocal(query) {
        const now2 = Date.now();
        const text = query.text?.toLowerCase();
        const tags = query.tags;
        const minR = query.minRetrievability ?? this.forgettingConfig.importanceThreshold;
        const results = [];
        for (const entry of this.store.values()) {
          const r = this.computeRetrievability(entry.createdAt, now2, entry.stability, entry.importance);
          if (r < minR) continue;
          if (query.category && entry.category !== query.category) continue;
          let score = r;
          if (text) {
            const haystack = `${entry.key} ${JSON.stringify(entry.value)} ${entry.tags.join(" ")}`.toLowerCase();
            if (!haystack.includes(text)) continue;
            score *= 0.5 + 0.5 * (text.length / haystack.length);
          }
          if (tags?.length) {
            const hasAll = tags.every((t) => entry.tags.includes(t));
            if (!hasAll) continue;
          }
          if (query.embedding && entry.embedding) {
            const similarity = cosineSimilarity(query.embedding, entry.embedding);
            score *= similarity;
          }
          results.push({
            tier: "semantic",
            entry: { ...entry, retrievability: r },
            score
          });
        }
        results.sort((a, b) => b.score - a.score);
        return results.slice(0, query.limit ?? 10);
      }
      async queryFromAdapter(query) {
        if (!this.adapter?.connected) return this.queryLocal(query);
        try {
          const adapterResults = await this.adapter.querySemantic(query);
          return adapterResults.map((entry) => ({
            tier: "semantic",
            entry,
            score: entry.retrievability
          }));
        } catch (e) {
          const msg = e instanceof Error ? e.message : String(e);
          console.warn(`SemanticMemory: adapter query failed, falling back to local: ${msg}`);
          return this.queryLocal(query);
        }
      }
      async persistToAdapter(entry) {
        if (!this.adapter?.connected) return;
        try {
          await this.adapter.storeSemantic(entry);
        } catch (e) {
          const msg = e instanceof Error ? e.message : String(e);
          console.warn(`SemanticMemory: adapter store failed for "${entry.key}" (non-critical, local copy valid): ${msg}`);
        }
      }
      findByKey(key) {
        for (const entry of this.store.values()) {
          if (entry.key === key) return entry;
        }
        return void 0;
      }
    };
  }
});

// src/memory/bridge.ts
var LobsterPressBridge, InMemoryFallbackAdapter;
var init_bridge = __esm({
  "src/memory/bridge.ts"() {
    "use strict";
    LobsterPressBridge = class {
      _connected = false;
      semanticBackend = null;
      compressorBackend = null;
      dbPath;
      constructor(config) {
        this.dbPath = config?.dbPath;
      }
      get connected() {
        return this._connected;
      }
      async init() {
        try {
          const mod = await this.tryImport();
          if (!mod) {
            this._connected = false;
            return;
          }
          this.semanticBackend = new mod.SemanticMemory(
            this.dbPath ? { dbPath: this.dbPath } : void 0
          );
          this.compressorBackend = new mod.DAGCompressor();
          this._connected = true;
        } catch (e) {
          console.warn(`error: ${e}`);
          this._connected = false;
        }
      }
      async storeSemantic(entry) {
        if (!this.semanticBackend) throw new Error("lobster-press not connected");
        await this.semanticBackend.store(entry.key, entry.value, {
          id: entry.id,
          namespace: entry.namespace,
          category: entry.category,
          importance: entry.importance,
          tags: entry.tags,
          embedding: entry.embedding,
          stability: entry.stability,
          retrievability: entry.retrievability,
          createdAt: entry.createdAt,
          updatedAt: entry.updatedAt
        });
      }
      async querySemantic(query) {
        if (!this.semanticBackend) throw new Error("lobster-press not connected");
        const results = await this.semanticBackend.query(
          query.text ?? "",
          query.limit ?? 10
        );
        return results.map((r) => {
          const meta = r.meta;
          return {
            id: meta?.["id"] ?? `lp_${Date.now()}`,
            namespace: meta?.["namespace"] ?? "default",
            key: r.key,
            value: r.value,
            category: meta?.["category"] ?? "fact",
            importance: meta?.["importance"] ?? 0.5,
            accessCount: meta?.["accessCount"] ?? 0,
            lastAccessedAt: meta?.["lastAccessedAt"] ?? Date.now(),
            stability: meta?.["stability"] ?? 1,
            retrievability: meta?.["retrievability"] ?? 1,
            embedding: meta?.["embedding"],
            tags: meta?.["tags"] ?? [],
            createdAt: meta?.["createdAt"] ?? Date.now(),
            updatedAt: meta?.["updatedAt"] ?? Date.now()
          };
        });
      }
      async compressEpisodic(entries) {
        if (!this.compressorBackend) throw new Error("lobster-press not connected");
        const withData = entries.filter((e) => e.rawData != null);
        if (withData.length === 0) return entries;
        const rawArray = withData.map((e) => e.rawData);
        const compressed = await this.compressorBackend.compress(rawArray);
        return entries.map((entry, i) => {
          if (entry.rawData == null) return entry;
          return {
            ...entry,
            rawData: compressed[i] ?? entry.rawData,
            compressed: true,
            source: "compressed_dag",
            tags: [...entry.tags, "compressed"],
            updatedAt: Date.now()
          };
        });
      }
      async close() {
        if (this.semanticBackend) {
          try {
            await this.semanticBackend.close();
          } catch (e) {
            console.warn(`error: ${e}`);
          }
        }
        this.semanticBackend = null;
        this.compressorBackend = null;
        this._connected = false;
      }
      async tryImport() {
        try {
          const moduleName = "lobster-press";
          return await import(moduleName);
        } catch (e) {
          console.warn(`error: ${e}`);
          return null;
        }
      }
    };
    InMemoryFallbackAdapter = class {
      _store = /* @__PURE__ */ new Map();
      get connected() {
        return true;
      }
      async init() {
      }
      async storeSemantic(entry) {
        this._store.set(entry.id, entry);
      }
      async querySemantic(query) {
        const text = query.text?.toLowerCase();
        const results = [];
        for (const entry of this._store.values()) {
          if (text) {
            const haystack = `${entry.key} ${JSON.stringify(entry.value)}`.toLowerCase();
            if (!haystack.includes(text)) continue;
          }
          if (query.category && entry.category !== query.category) continue;
          results.push(entry);
        }
        return results.slice(0, query.limit ?? 10);
      }
      async compressEpisodic(entries) {
        return entries.map((entry) => ({
          ...entry,
          rawData: void 0,
          compressed: true,
          source: "compressed_dag",
          tags: [...entry.tags, "compressed"],
          updatedAt: Date.now()
        }));
      }
      async close() {
        this._store.clear();
      }
    };
  }
});

// src/memory/unified-retriever.ts
function normalize2(input) {
  return input.toLowerCase().trim().replace(/\s+/g, " ");
}
var UnifiedRetriever;
var init_unified_retriever = __esm({
  "src/memory/unified-retriever.ts"() {
    "use strict";
    UnifiedRetriever = class {
      config;
      ftsSearchFn = null;
      vectorSearchFn = null;
      loadEpisodicByIdFn = null;
      constructor(config) {
        this.config = {
          rrfK: 60,
          episodicWeight: 0.4,
          vectorWeight: 0.3,
          semanticWeight: 0.3,
          ...config
        };
      }
      setFTSSearch(fn) {
        this.ftsSearchFn = fn;
      }
      setVectorSearch(fn) {
        this.vectorSearchFn = fn;
      }
      setEpisodicLoader(fn) {
        this.loadEpisodicByIdFn = fn;
      }
      async search(queryText, episodicResults, semanticResults, limit = 10) {
        const allCandidates = [];
        const prefetchLimit = limit * 4;
        const seenIds = /* @__PURE__ */ new Set();
        for (const r of episodicResults) {
          seenIds.add(r.entry.id);
          allCandidates.push({ id: r.entry.id, tier: "episodic", score: r.score, entry: r.entry });
        }
        if (this.ftsSearchFn) {
          try {
            const ftsIds = this.ftsSearchFn(queryText, prefetchLimit);
            for (const id of ftsIds) {
              if (seenIds.has(id)) continue;
              const entry = this.loadEpisodicByIdFn?.(id);
              if (entry) {
                seenIds.add(id);
                allCandidates.push({ id, tier: "episodic", score: 0.6, entry });
              }
            }
          } catch (e) {
            console.warn(`FTS5 not available: ${e}`);
          }
        }
        if (this.vectorSearchFn) {
          try {
            const vectorResults = await this.vectorSearchFn(queryText, prefetchLimit);
            for (const vr of vectorResults) {
              if (seenIds.has(vr.id)) {
                const existing = allCandidates.find((c) => c.id === vr.id);
                if (existing) existing.score *= 1 + vr.score;
              } else {
                seenIds.add(vr.id);
                allCandidates.push({
                  id: vr.id,
                  tier: "episodic",
                  score: vr.score,
                  entry: {
                    id: vr.id,
                    workflowId: vr.id.replace(/^(wf_|step_)/, "").split("_")[0],
                    workflowName: vr.id
                  }
                });
              }
            }
          } catch (e) {
            console.warn(`Vector not available: ${e}`);
          }
        }
        for (const r of semanticResults) {
          if (seenIds.has(r.entry.id)) continue;
          seenIds.add(r.entry.id);
          allCandidates.push({ id: r.entry.id, tier: "semantic", score: r.score * 1.2, entry: r.entry });
        }
        const rrfScores = this.reciprocalRankFusion(allCandidates);
        const results = [];
        for (const [id, rrfScore] of rrfScores) {
          const candidate = allCandidates.find((c) => c.id === id);
          if (!candidate) continue;
          results.push({ tier: candidate.tier, entry: candidate.entry, score: rrfScore });
        }
        const now2 = Date.now();
        for (const r of results) {
          const createdAt = r.entry.createdAt ?? r.entry.timestamp ?? now2;
          r.score = this.timeDecay(r.score, createdAt);
        }
        const diversified = this.maximalMarginalRelevance(results, 0.7, limit);
        return diversified;
      }
      /**
       * Search workflow templates by keyword matching.
       * Uses RRF fusion + MMR reranking.
       */
      searchTemplates(query, templates, limit = 10) {
        if (templates.length === 0) return [];
        const queryTokens = new Set(normalize2(query).split(/[^\w\u4e00-\u9fff]+/).filter((t) => t.length >= 2));
        if (queryTokens.size === 0) return [];
        const fieldGroups = [];
        const nameScores = [];
        const descScores = [];
        const triggerScores = [];
        const tagScores = [];
        for (let i = 0; i < templates.length; i++) {
          const t = templates[i];
          const nameTokens = normalize2(t.name).split(/[^\w\u4e00-\u9fff]+/);
          const nameHits = nameTokens.filter((tk) => queryTokens.has(tk)).length;
          const nameScore = nameTokens.length > 0 ? nameHits / nameTokens.length : 0;
          nameScores.push({ idx: i, score: nameScore });
          if (t.description) {
            const descTokens = normalize2(t.description).split(/[^\w\u4e00-\u9fff]+/);
            const descHits = descTokens.filter((tk) => queryTokens.has(tk)).length;
            const descScore = descTokens.length > 0 ? descHits / descTokens.length : 0;
            descScores.push({ idx: i, score: descScore });
          }
          if (t.triggers?.length) {
            let bestTriggerScore = 0;
            for (const tr of t.triggers) {
              const trTokens = normalize2(tr).split(/[^\w\u4e00-\u9fff]+/);
              const trHits = trTokens.filter((tk) => queryTokens.has(tk)).length;
              bestTriggerScore = Math.max(bestTriggerScore, trTokens.length > 0 ? trHits / trTokens.length : 0);
            }
            triggerScores.push({ idx: i, score: bestTriggerScore });
          }
          if (t.tags?.length) {
            const tagTokens = t.tags.flatMap((tag) => normalize2(tag).split(/[^\w\u4e00-\u9fff]+/));
            const tagHits = tagTokens.filter((tk) => queryTokens.has(tk)).length;
            const tagScore = tagTokens.length > 0 ? tagHits / tagTokens.length : 0;
            tagScores.push({ idx: i, score: tagScore });
          }
        }
        fieldGroups.push(nameScores, descScores, triggerScores, tagScores);
        const rrfScores = /* @__PURE__ */ new Map();
        for (const group of fieldGroups) {
          const ranked = [...group].sort((a, b) => b.score - a.score);
          for (let rank = 0; rank < ranked.length; rank++) {
            const { idx } = ranked[rank];
            const rrf = 1 / (this.config.rrfK + rank + 1);
            rrfScores.set(idx, (rrfScores.get(idx) ?? 0) + rrf);
          }
        }
        const candidates = [];
        for (const [idx, score] of rrfScores) {
          if (score === 0) continue;
          candidates.push({
            tier: "semantic",
            entry: { ...templates[idx], _templateIdx: idx },
            score
          });
        }
        const diversified = this.maximalMarginalRelevance(candidates, 0.7, limit);
        return diversified.map((r) => {
          const idx = r.entry._templateIdx;
          return {
            template: templates[idx],
            score: r.score
          };
        });
      }
      /**
       * Apply time decay to a score.
       * Recent results retain high weight; 14-day-old results drop to ~0.3x.
       */
      timeDecay(score, createdAtMs, halfLifeDays = 14) {
        const ageMs = Date.now() - createdAtMs;
        const ageDays = ageMs / (24 * 60 * 60 * 1e3);
        if (ageDays < 0) return score;
        return score * (0.3 + 0.7 * Math.pow(0.5, ageDays / halfLifeDays));
      }
      /**
       * Maximal Marginal Relevance — rerank for diversity.
       * Greedily selects candidates maximizing: rel - (1-λ) * max_sim_to_selected.
       * Similarity approximated by id prefix or tier match.
       */
      maximalMarginalRelevance(candidates, lambda = 0.7, limit) {
        if (candidates.length <= limit) return [...candidates];
        const selected = [];
        const remaining = [...candidates];
        remaining.sort((a, b) => b.score - a.score);
        selected.push(remaining.shift());
        while (selected.length < limit && remaining.length > 0) {
          let bestIdx = 0;
          let bestMmr = -Infinity;
          for (let i = 0; i < remaining.length; i++) {
            const c = remaining[i];
            const rel = c.score;
            let maxSim = 0;
            for (const s of selected) {
              const sim = this.candidateSimilarity(c, s);
              if (sim > maxSim) maxSim = sim;
            }
            const mmr = rel - (1 - lambda) * maxSim;
            if (mmr > bestMmr) {
              bestMmr = mmr;
              bestIdx = i;
            }
          }
          selected.push(remaining.splice(bestIdx, 1)[0]);
        }
        return selected;
      }
      /** Approximate similarity between two candidates (no vectors available). */
      candidateSimilarity(a, b) {
        if (a.tier === b.tier) {
          const idA = a.entry.id ?? "";
          const idB = b.entry.id ?? "";
          const prefixLen = this.commonPrefixLength(idA, idB);
          if (prefixLen > 3) return 0.8;
          return 0.3;
        }
        return 0;
      }
      commonPrefixLength(a, b) {
        let len = 0;
        const max = Math.min(a.length, b.length);
        while (len < max && a[len] === b[len]) len++;
        return len;
      }
      reciprocalRankFusion(candidates) {
        const { rrfK } = this.config;
        const scores = /* @__PURE__ */ new Map();
        const ranked = [...candidates].sort((a, b) => b.score - a.score);
        for (let rank = 0; rank < ranked.length; rank++) {
          const c = ranked[rank];
          const weight = c.tier === "semantic" ? this.config.semanticWeight : this.config.episodicWeight;
          const rrf = weight / (rrfK + rank + 1);
          scores.set(c.id, (scores.get(c.id) ?? 0) + rrf);
        }
        return scores;
      }
    };
  }
});

// src/memory/r3mem-store.ts
var r3mem_store_exports = {};
__export(r3mem_store_exports, {
  R3MemStore: () => R3MemStore
});
var R3MemStore;
var init_r3mem_store = __esm({
  "src/memory/r3mem-store.ts"() {
    "use strict";
    R3MemStore = class {
      db;
      // better-sqlite3 Database
      constructor(db) {
        this.db = db;
      }
      /** Initialize tables (called from migrations) */
      static createTables(db) {
        try {
          db.exec(`
        CREATE TABLE IF NOT EXISTS r3mem_documents (
          id TEXT PRIMARY KEY,
          source_type TEXT NOT NULL,
          content TEXT NOT NULL,
          created_at INTEGER NOT NULL,
          compressed INTEGER DEFAULT 0
        )
      `);
          db.exec(`
        CREATE TABLE IF NOT EXISTS r3mem_paragraphs (
          id TEXT PRIMARY KEY,
          document_id TEXT NOT NULL REFERENCES r3mem_documents(id),
          para_index INTEGER NOT NULL,
          content TEXT NOT NULL,
          created_at INTEGER NOT NULL,
          UNIQUE(document_id, para_index)
        )
      `);
          db.exec(`
        CREATE TABLE IF NOT EXISTS r3mem_entities (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          text TEXT NOT NULL,
          type TEXT NOT NULL,
          confidence REAL NOT NULL,
          source_paragraph_id TEXT,
          source_document_id TEXT,
          first_seen_at INTEGER NOT NULL,
          last_seen_at INTEGER NOT NULL,
          occurrence_count INTEGER DEFAULT 1,
          UNIQUE(text, type)
        )
      `);
          db.exec(`CREATE INDEX IF NOT EXISTS idx_r3mem_para_doc ON r3mem_paragraphs(document_id)`);
          db.exec(`CREATE INDEX IF NOT EXISTS idx_r3mem_entity_type ON r3mem_entities(type)`);
          db.exec(`CREATE INDEX IF NOT EXISTS idx_r3mem_entity_text ON r3mem_entities(text)`);
          db.exec(`CREATE INDEX IF NOT EXISTS idx_r3mem_entity_doc ON r3mem_entities(source_document_id)`);
        } catch (e) {
        }
      }
      /** Store a decomposed document with its paragraphs and entities */
      storeDecomposition(document, paragraphs, entities) {
        try {
          this.db.prepare(`
        INSERT OR REPLACE INTO r3mem_documents (id, source_type, content, created_at)
        VALUES (?, ?, ?, ?)
      `).run(document.id, document.sourceType, document.content, document.createdAt);
          const insertPara = this.db.prepare(`
        INSERT OR REPLACE INTO r3mem_paragraphs (id, document_id, para_index, content, created_at)
        VALUES (?, ?, ?, ?, ?)
      `);
          for (const para of paragraphs) {
            insertPara.run(para.id, para.sourceDocumentId, para.index, para.content, para.createdAt);
          }
          const upsertEntity = this.db.prepare(`
        INSERT INTO r3mem_entities (text, type, confidence, source_paragraph_id, source_document_id, first_seen_at, last_seen_at, occurrence_count)
        VALUES (?, ?, ?, ?, ?, ?, ?, 1)
        ON CONFLICT(text, type) DO UPDATE SET
          confidence = MAX(confidence, excluded.confidence),
          last_seen_at = MAX(last_seen_at, excluded.last_seen_at),
          occurrence_count = occurrence_count + 1
      `);
          const now2 = Date.now();
          for (const entity of entities) {
            upsertEntity.run(
              entity.text,
              entity.type,
              entity.confidence,
              entity.sourceId,
              entity.sourceId.startsWith("para_") ? entity.sourceId.slice(5).split("_")[0] : document.id,
              now2,
              now2
            );
          }
        } catch (e) {
        }
      }
      /** Query entities with optional filters */
      queryEntities(filter) {
        try {
          let sql = "SELECT * FROM r3mem_entities WHERE 1=1";
          const params = [];
          if (filter?.types?.length) {
            const placeholders = filter.types.map(() => "?").join(",");
            sql += ` AND type IN (${placeholders})`;
            params.push(...filter.types);
          }
          if (filter?.text) {
            sql += " AND text LIKE ?";
            params.push(`%${filter.text}%`);
          }
          if (filter?.minConfidence) {
            sql += " AND confidence >= ?";
            params.push(filter.minConfidence);
          }
          if (filter?.minOccurrences) {
            sql += " AND occurrence_count >= ?";
            params.push(filter.minOccurrences);
          }
          sql += " ORDER BY occurrence_count DESC, confidence DESC";
          if (filter?.limit) {
            sql += " LIMIT ?";
            params.push(filter.limit);
          }
          const rows = this.db.prepare(sql).all(...params);
          return rows.map((row) => ({
            text: row.text,
            type: row.type,
            confidence: row.confidence,
            sourceId: row.source_paragraph_id || row.source_document_id
          }));
        } catch (e) {
          console.warn(`error: ${e}`);
          return [];
        }
      }
      /** Get paragraphs for a specific document */
      getParagraphs(documentId) {
        try {
          const rows = this.db.prepare(
            "SELECT * FROM r3mem_paragraphs WHERE document_id = ? ORDER BY para_index"
          ).all(documentId);
          return rows.map((row) => ({
            id: row.id,
            sourceDocumentId: row.document_id,
            index: row.para_index,
            content: row.content,
            createdAt: row.created_at
          }));
        } catch (e) {
          console.warn(`error: ${e}`);
          return [];
        }
      }
      /** Get stats */
      getStats() {
        try {
          const docCount = this.db.prepare("SELECT COUNT(*) as c FROM r3mem_documents").get().c;
          const paraCount = this.db.prepare("SELECT COUNT(*) as c FROM r3mem_paragraphs").get().c;
          const entityCount = this.db.prepare("SELECT COUNT(*) as c FROM r3mem_entities").get().c;
          const typeRows = this.db.prepare(
            "SELECT type, COUNT(*) as c FROM r3mem_entities GROUP BY type"
          ).all();
          const entityTypes = {};
          for (const row of typeRows) {
            entityTypes[row.type] = row.c;
          }
          return { documentCount: docCount, paragraphCount: paraCount, entityCount, entityTypes };
        } catch (e) {
          console.warn(`error: ${e}`);
          return { documentCount: 0, paragraphCount: 0, entityCount: 0, entityTypes: {} };
        }
      }
      /** Delete a document and its paragraphs (entities are kept — they've been learned) */
      deleteDocument(documentId) {
        try {
          this.db.prepare("DELETE FROM r3mem_paragraphs WHERE document_id = ?").run(documentId);
          const result = this.db.prepare("DELETE FROM r3mem_documents WHERE id = ?").run(documentId);
          return result.changes > 0;
        } catch (e) {
          console.warn(`error: ${e}`);
          return false;
        }
      }
      /** Mark document as compressed */
      markCompressed(documentId) {
        try {
          this.db.prepare("UPDATE r3mem_documents SET compressed = 1 WHERE id = ?").run(documentId);
        } catch (e) {
          console.warn(`non-critical: ${e}`);
        }
      }
    };
  }
});

// src/memory/index.ts
var memory_exports = {};
__export(memory_exports, {
  EntityExtractor: () => EntityExtractor,
  EpisodicMemory: () => EpisodicMemory,
  InMemoryFallbackAdapter: () => InMemoryFallbackAdapter,
  LobsterPressBridge: () => LobsterPressBridge,
  MemorySystem: () => MemorySystem,
  R3MemStore: () => R3MemStore,
  SemanticMemory: () => SemanticMemory,
  UnifiedRetriever: () => UnifiedRetriever,
  WorkingMemory: () => WorkingMemory
});
var DEFAULT_NAMESPACE, MemorySystem;
var init_memory = __esm({
  "src/memory/index.ts"() {
    "use strict";
    init_entity_extractor();
    init_working_memory();
    init_episodic_memory();
    init_semantic_memory();
    init_bridge();
    init_unified_retriever();
    init_r3mem_store();
    DEFAULT_NAMESPACE = "default";
    MemorySystem = class {
      working;
      episodic;
      semantic;
      entityExtractor;
      unifiedRetriever = null;
      bridge = null;
      fallback = null;
      _r3memStore = null;
      initialized = false;
      namespace;
      config;
      constructor(config = {}) {
        this.config = config;
        this.namespace = config.namespace ?? DEFAULT_NAMESPACE;
        this.working = new WorkingMemory(this.namespace, config.workingCapacity);
        this.entityExtractor = new EntityExtractor();
        this.episodic = new EpisodicMemory(
          this.namespace,
          config.episodicCapacity,
          config.compressionThresholdMs
        );
        this.semantic = new SemanticMemory(this.namespace, config.forgetting);
      }
      async init() {
        if (this.initialized) return;
        let adapter;
        if (!this.config.disableLobsterPress && !this.bridge) {
          this.bridge = new LobsterPressBridge({
            dbPath: this.config.lobsterPressDbPath
          });
          await this.bridge.init();
          if (this.bridge.connected) {
            adapter = this.bridge;
          } else {
            this.fallback = new InMemoryFallbackAdapter();
            await this.fallback.init();
            adapter = this.fallback;
          }
          this.semantic.setAdapter(adapter);
        }
        this.initialized = true;
      }
      setUnifiedSources(opts) {
        if (!this.unifiedRetriever) {
          this.unifiedRetriever = new UnifiedRetriever();
        }
        if (opts.ftsSearch) this.unifiedRetriever.setFTSSearch(opts.ftsSearch);
        if (opts.vectorSearch) this.unifiedRetriever.setVectorSearch(opts.vectorSearch);
        if (opts.episodicLoader) this.unifiedRetriever.setEpisodicLoader(opts.episodicLoader);
      }
      async query(query) {
        const resolvedQuery = this.resolveQuery(query);
        const tiers = resolvedQuery.tiers ?? ["working", "episodic", "semantic"];
        const allResults = [];
        if (tiers.includes("working")) {
          allResults.push(...this.working.query(resolvedQuery));
        }
        let episodicResults = [];
        let semanticResults = [];
        if (tiers.includes("episodic")) {
          episodicResults = this.episodic.searchExecutions(resolvedQuery);
        }
        if (tiers.includes("semantic")) {
          semanticResults = await this.semantic.getFacts(resolvedQuery);
        }
        if (this.unifiedRetriever && resolvedQuery.text) {
          const unified = await this.unifiedRetriever.search(
            resolvedQuery.text,
            episodicResults,
            semanticResults,
            resolvedQuery.limit
          );
          allResults.push(...unified);
        } else {
          allResults.push(...episodicResults, ...semanticResults);
        }
        allResults.sort((a, b) => b.score - a.score);
        const limit = resolvedQuery.limit ?? 10;
        const sliced = allResults.slice(0, limit);
        return {
          entries: sliced,
          totalMatches: allResults.length,
          query: resolvedQuery
        };
      }
      async storeWorkflowExecution(workflow) {
        this.episodic.storeExecution(workflow);
      }
      async storeFact(key, value, importance = 0.5, extra) {
        return this.semantic.storeFact(key, value, importance, extra);
      }
      /** Initialize R³Mem store with a raw SQLite database */
      setR3MemStore(store) {
        this._r3memStore = store;
      }
      /** Decompose a document into paragraphs + entities (R³Mem pipeline) */
      async decomposeDocument(doc) {
        const result = await this.entityExtractor.decompose(doc);
        if (this._r3memStore) {
          try {
            this._r3memStore.storeDecomposition(doc, result.paragraphs, result.entities);
          } catch (e) {
            console.warn(`non-critical: ${e}`);
          }
        }
        return result;
      }
      /** Query entities from R³Mem store */
      queryEntities(filter) {
        if (!this._r3memStore) return [];
        return this._r3memStore.queryEntities(filter);
      }
      /** Get R³Mem stats */
      getR3MemStats() {
        if (!this._r3memStore) return null;
        return this._r3memStore.getStats();
      }
      getStats() {
        return {
          namespace: this.namespace,
          initialized: this.initialized,
          lobsterPressConnected: this.bridge?.connected ?? false,
          working: { entries: this.working.size },
          episodic: { entries: this.episodic.size },
          semantic: { entries: this.semantic.size }
        };
      }
      async prune() {
        const forgottenFacts = this.semantic.pruneForgotten();
        const compressedEpisodes = this.episodic.compressOldEntries();
        return { forgottenFacts, compressedEpisodes };
      }
      async close() {
        if (this.bridge) {
          await this.bridge.close();
          this.bridge = null;
        }
        if (this.fallback) {
          await this.fallback.close();
          this.fallback = null;
        }
        this.working.clear();
        this.initialized = false;
      }
      resolveQuery(query) {
        return {
          ...query,
          namespace: query.namespace ?? this.namespace,
          limit: query.limit ?? 10
        };
      }
    };
  }
});

// src/vector/types.ts
var DEFAULT_SEARCH_OPTIONS;
var init_types = __esm({
  "src/vector/types.ts"() {
    "use strict";
    DEFAULT_SEARCH_OPTIONS = {
      rrf: { k: 60, ftsWeight: 0.5, vectorWeight: 0.5 },
      mmr: { lambda: 0.7, prefetchFactor: 3 },
      timeDecay: { halfLifeMs: 14 * 24 * 60 * 60 * 1e3 },
      normalization: { minScore: 0.45 },
      defaultTopK: 10
    };
  }
});

// src/vector/embedder.ts
var embedder_exports = {};
__export(embedder_exports, {
  EmbeddingError: () => EmbeddingError,
  cosineSimilarity: () => cosineSimilarity2,
  createEmbedder: () => createEmbedder,
  deserializeEmbedding: () => deserializeEmbedding,
  normalizeInPlace: () => normalizeInPlace,
  serializeEmbedding: () => serializeEmbedding
});
function createEmbedder(config) {
  const defaults = PROVIDER_DEFAULTS[config.type];
  const model = config.model ?? defaults.model;
  const dimensions = config.dimensions ?? defaults.dimensions;
  switch (config.type) {
    case "openai":
      return new OpenAIEmbedder(config.apiBase ?? "https://api.openai.com/v1", config.apiKey ?? "", model, dimensions, config.batchSize ?? 32);
    case "glm":
      return new GLMEmbedder(config.apiBase ?? "https://open.bigmodel.cn/api/paas/v4", config.apiKey ?? "", model, dimensions);
    case "minimax":
      return new OpenAIEmbedder(config.apiBase ?? "https://api.minimax.chat/v1", config.apiKey ?? "", model, dimensions, config.batchSize ?? 32);
    case "local":
      return new LocalEmbedder(model, dimensions);
    case "mock":
      return new MockEmbedder(dimensions);
  }
}
function normalizeInPlace(vec) {
  let norm = 0;
  for (let i = 0; i < vec.length; i++) {
    norm += vec[i] * vec[i];
  }
  norm = Math.sqrt(norm);
  if (norm > 0) {
    for (let i = 0; i < vec.length; i++) {
      vec[i] = vec[i] / norm;
    }
  }
}
function cosineSimilarity2(a, b) {
  if (a.length !== b.length || a.length === 0) return 0;
  let dot = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
  }
  return dot;
}
function serializeEmbedding(vec) {
  const buffer = new ArrayBuffer(vec.byteLength);
  new Float32Array(buffer).set(vec);
  return btoa(String.fromCharCode(...new Uint8Array(buffer)));
}
function deserializeEmbedding(data, dimensions) {
  const binary = atob(data);
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) {
    bytes[i] = binary.charCodeAt(i);
  }
  return new Float32Array(bytes.buffer, 0, dimensions);
}
var PROVIDER_DEFAULTS, OpenAIEmbedder, GLMEmbedder, LocalEmbedder, MockEmbedder, EmbeddingError;
var init_embedder = __esm({
  "src/vector/embedder.ts"() {
    "use strict";
    PROVIDER_DEFAULTS = {
      openai: { model: "text-embedding-3-small", dimensions: 1536 },
      local: { model: "bge-m3", dimensions: 1024 },
      mock: { model: "mock", dimensions: 128 },
      glm: { model: "embedding-3", dimensions: 2048 },
      minimax: { model: "text-embedding-01", dimensions: 1536 }
    };
    OpenAIEmbedder = class {
      dimensions;
      providerType = "openai";
      apiBase;
      apiKey;
      model;
      batchSize;
      constructor(apiBase, apiKey, model, dimensions, batchSize) {
        this.apiBase = apiBase;
        this.apiKey = apiKey;
        this.model = model;
        this.dimensions = dimensions;
        this.batchSize = batchSize;
      }
      async embed(text) {
        const results = await this.embedBatch([text]);
        return results[0];
      }
      async embedBatch(texts) {
        const allEmbeddings = [];
        for (let i = 0; i < texts.length; i += this.batchSize) {
          const batch = texts.slice(i, i + this.batchSize);
          const response = await fetch(`${this.apiBase}/embeddings`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              ...this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {}
            },
            body: JSON.stringify({
              model: this.model,
              input: batch,
              dimensions: this.dimensions
            })
          });
          if (!response.ok) {
            throw new EmbeddingError(`OpenAI API error: ${response.status} ${response.statusText}`);
          }
          const json = await response.json();
          const sorted = json.data.sort((a, b) => a.index - b.index);
          for (const item of sorted) {
            allEmbeddings.push(new Float32Array(item.embedding));
          }
        }
        return allEmbeddings;
      }
    };
    GLMEmbedder = class {
      dimensions;
      providerType = "glm";
      apiBase;
      apiKey;
      model;
      constructor(apiBase, apiKey, model, dimensions) {
        this.apiBase = apiBase;
        this.apiKey = apiKey;
        this.model = model;
        this.dimensions = dimensions;
      }
      async embed(text) {
        const results = await this.embedBatch([text]);
        return results[0];
      }
      async embedBatch(texts) {
        const response = await fetch(`${this.apiBase}/embeddings`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${this.apiKey}`
          },
          body: JSON.stringify({ model: this.model, input: texts })
        });
        if (!response.ok) {
          throw new EmbeddingError(`GLM API error: ${response.status} ${response.statusText}`);
        }
        const json = await response.json();
        const sorted = (json.data || json.embeddings || []).sort((a, b) => a.index - b.index);
        return sorted.map((item) => new Float32Array(item.embedding));
      }
    };
    LocalEmbedder = class {
      dimensions;
      providerType = "local";
      constructor(_model, dimensions) {
        this.dimensions = dimensions;
      }
      async embed(text) {
        return this.embedBatch([text]).then((r) => r[0]);
      }
      async embedBatch(texts) {
        return texts.map((text) => this.simpleHashEmbed(text, this.dimensions));
      }
      simpleHashEmbed(text, dims) {
        const vec = new Float32Array(dims);
        const normalized = text.toLowerCase().trim();
        if (normalized.length === 0) return vec;
        for (let i = 0; i < dims; i++) {
          let hash = i;
          for (let j = 0; j < normalized.length; j++) {
            const ch = normalized.charCodeAt(j);
            hash = (hash << 5) - hash + ch + i * 31 | 0;
          }
          vec[i] = hash;
        }
        normalizeInPlace(vec);
        return vec;
      }
    };
    MockEmbedder = class {
      dimensions;
      providerType = "mock";
      constructor(dimensions) {
        this.dimensions = dimensions;
      }
      async embed(text) {
        const vec = new Float32Array(this.dimensions);
        for (let i = 0; i < this.dimensions; i++) {
          vec[i] = Math.sin(text.charCodeAt(i % text.length) * (i + 1) * 0.1);
        }
        normalizeInPlace(vec);
        return vec;
      }
      async embedBatch(texts) {
        return Promise.all(texts.map((t) => this.embed(t)));
      }
    };
    EmbeddingError = class extends Error {
      constructor(message) {
        super(message);
        this.name = "EmbeddingError";
      }
    };
  }
});

// src/vector/retriever.ts
var HybridRetriever;
var init_retriever = __esm({
  "src/vector/retriever.ts"() {
    "use strict";
    init_types();
    init_embedder();
    HybridRetriever = class {
      constructor(embedder, store, options) {
        this.embedder = embedder;
        this.store = store;
        this.options = {
          rrf: { ...DEFAULT_SEARCH_OPTIONS.rrf, ...options?.rrf },
          mmr: { ...DEFAULT_SEARCH_OPTIONS.mmr, ...options?.mmr },
          timeDecay: { ...DEFAULT_SEARCH_OPTIONS.timeDecay, ...options?.timeDecay },
          normalization: { ...DEFAULT_SEARCH_OPTIONS.normalization, ...options?.normalization },
          defaultTopK: options?.defaultTopK ?? DEFAULT_SEARCH_OPTIONS.defaultTopK
        };
      }
      embedder;
      store;
      options;
      async search(query, topK) {
        const k = topK ?? this.options.defaultTopK;
        const queryEmbedding = await this.embedder.embed(query);
        const prefetchLimit = Math.max(k * this.options.mmr.prefetchFactor, 50);
        const [ftsResults, vectorResults] = await Promise.all([
          this.store.ftsSearch(query, prefetchLimit),
          this.store.vectorSearch(queryEmbedding, prefetchLimit)
        ]);
        const rrfCandidates = this.reciprocalRankFusion(ftsResults, vectorResults);
        const allIds = rrfCandidates.map((c) => c.id);
        const [docMap, embeddingMap] = await Promise.all([
          this.store.getDocuments(allIds),
          this.store.getAllEmbeddings(allIds)
        ]);
        const mmrCandidates = this.mmrDeduplicate(
          rrfCandidates,
          embeddingMap,
          k
        );
        const now2 = Date.now();
        const scored = mmrCandidates.map((cand) => {
          const doc = docMap.get(cand.id);
          const timeDecay = this.computeTimeDecay(doc?.createdAt ?? now2, now2);
          const finalScore = cand.mmrScore * timeDecay;
          return { candidate: cand, doc, timeDecay, finalScore };
        });
        const maxScore = Math.max(...scored.map((s) => s.finalScore), 1e-9);
        const results = [];
        for (const item of scored) {
          const normalized = item.finalScore / maxScore;
          if (normalized < this.options.normalization.minScore) continue;
          const doc = item.doc;
          if (!doc) continue;
          results.push({
            id: item.candidate.id,
            workflowId: doc.workflowId,
            stepId: doc.stepId,
            title: doc.title,
            snippet: doc.content.slice(0, 300),
            score: normalized,
            scoreBreakdown: {
              ftsScore: item.candidate.ftsScore,
              vectorScore: item.candidate.vectorScore,
              rrfScore: item.candidate.rrfScore,
              mmrScore: item.candidate.mmrScore,
              timeDecay: item.timeDecay,
              finalScore: normalized
            },
            similarity: item.candidate.vectorScore,
            timestamp: doc.createdAt,
            metadata: doc.metadata
          });
        }
        results.sort((a, b) => b.score - a.score);
        return results.slice(0, k);
      }
      reciprocalRankFusion(ftsResults, vectorResults) {
        const { k, ftsWeight, vectorWeight } = this.options.rrf;
        const candidateMap = /* @__PURE__ */ new Map();
        for (const result of ftsResults) {
          const rrf = ftsWeight / (k + result.rank + 1);
          candidateMap.set(result.id, {
            id: result.id,
            rrfScore: rrf,
            ftsRank: result.rank,
            vectorRank: Infinity,
            ftsScore: result.score,
            vectorScore: 0
          });
        }
        for (const result of vectorResults) {
          const rrf = vectorWeight / (k + result.rank + 1);
          const existing = candidateMap.get(result.id);
          if (existing) {
            existing.rrfScore += rrf;
            existing.vectorRank = result.rank;
            existing.vectorScore = result.similarity;
          } else {
            candidateMap.set(result.id, {
              id: result.id,
              rrfScore: rrf,
              ftsRank: Infinity,
              vectorRank: result.rank,
              ftsScore: 0,
              vectorScore: result.similarity
            });
          }
        }
        const candidates = Array.from(candidateMap.values());
        candidates.sort((a, b) => b.rrfScore - a.rrfScore);
        return candidates;
      }
      mmrDeduplicate(candidates, embeddingMap, topK) {
        const { lambda } = this.options.mmr;
        const selected = [];
        const remaining = candidates.map((c) => ({
          ...c,
          mmrScore: c.rrfScore,
          embedding: embeddingMap.get(c.id) ?? new Float32Array(0)
        }));
        while (selected.length < topK && remaining.length > 0) {
          let bestIdx = 0;
          let bestMMR = -Infinity;
          for (let i = 0; i < remaining.length; i++) {
            const cand = remaining[i];
            const relevance = cand.rrfScore;
            let maxSimToSelected = 0;
            for (const sel of selected) {
              const sim = cosineSimilarity2(cand.embedding, sel.embedding);
              if (sim > maxSimToSelected) maxSimToSelected = sim;
            }
            const mmr = lambda * relevance - (1 - lambda) * maxSimToSelected;
            if (mmr > bestMMR) {
              bestMMR = mmr;
              bestIdx = i;
            }
          }
          const chosen = remaining.splice(bestIdx, 1)[0];
          chosen.mmrScore = bestMMR;
          selected.push(chosen);
        }
        return selected;
      }
      computeTimeDecay(createdAt, now2) {
        const { halfLifeMs } = this.options.timeDecay;
        if (halfLifeMs <= 0) return 1;
        const elapsed = now2 - createdAt;
        return Math.pow(0.5, elapsed / halfLifeMs);
      }
    };
  }
});

// src/vector/indexer.ts
var VectorIndexer;
var init_indexer = __esm({
  "src/vector/indexer.ts"() {
    "use strict";
    init_embedder();
    VectorIndexer = class {
      constructor(embedder, dbPath = ":memory:") {
        this.embedder = embedder;
        this.dbPath = dbPath;
      }
      embedder;
      db = null;
      dbPath;
      async init() {
        if (this.db) return;
        this.db = await this.openDatabase();
        this.db.exec("PRAGMA journal_mode=WAL");
        this.db.exec("PRAGMA synchronous=NORMAL");
        this.db.exec(`
      CREATE TABLE IF NOT EXISTS vector_documents (
        id TEXT PRIMARY KEY,
        workflow_id TEXT NOT NULL,
        step_id TEXT,
        doc_type TEXT NOT NULL CHECK(doc_type IN ('workflow', 'step')),
        title TEXT NOT NULL,
        content TEXT NOT NULL,
        embedding_data TEXT NOT NULL,
        embedding_dims INTEGER NOT NULL,
        created_at INTEGER NOT NULL,
        updated_at INTEGER NOT NULL,
        metadata TEXT NOT NULL DEFAULT '{}'
      )
    `);
        this.db.exec(`
      CREATE INDEX IF NOT EXISTS idx_vec_workflow ON vector_documents(workflow_id)
    `);
        this.db.exec(`
      CREATE INDEX IF NOT EXISTS idx_vec_step ON vector_documents(step_id)
    `);
        this.db.exec(`
      CREATE INDEX IF NOT EXISTS idx_vec_type ON vector_documents(doc_type)
    `);
        this.db.exec(`
      CREATE VIRTUAL TABLE IF NOT EXISTS vector_fts USING fts5(
        id UNINDEXED,
        title,
        content,
        doc_type,
        content='vector_documents',
        content_rowid='rowid'
      )
    `);
        this.db.exec(`
      CREATE TRIGGER IF NOT EXISTS vector_fts_insert AFTER INSERT ON vector_documents BEGIN
        INSERT INTO vector_fts(rowid, id, title, content, doc_type)
        VALUES (new.rowid, new.id, new.title, new.content, new.doc_type);
      END
    `);
        this.db.exec(`
      CREATE TRIGGER IF NOT EXISTS vector_fts_delete AFTER DELETE ON vector_documents BEGIN
        INSERT INTO vector_fts(vector_fts, rowid, id, title, content, doc_type)
        VALUES ('delete', old.rowid, old.id, old.title, old.content, old.doc_type);
      END
    `);
        this.db.exec(`
      CREATE TRIGGER IF NOT EXISTS vector_fts_update AFTER UPDATE ON vector_documents BEGIN
        INSERT INTO vector_fts(vector_fts, rowid, id, title, content, doc_type)
        VALUES ('delete', old.rowid, old.id, old.title, old.content, old.doc_type);
        INSERT INTO vector_fts(rowid, id, title, content, doc_type)
        VALUES (new.rowid, new.id, new.title, new.content, new.doc_type);
      END
    `);
      }
      async indexWorkflow(workflow) {
        this.ensureReady();
        const content = this.workflowToContent(workflow);
        const embedding = await this.embedder.embed(content);
        const id = `wf_${workflow.id}`;
        const now2 = Date.now();
        const doc = {
          id,
          workflowId: workflow.id,
          stepId: void 0,
          docType: "workflow",
          content,
          title: workflow.name,
          embedding: { data: serializeEmbedding(embedding), dimensions: embedding.length },
          createdAt: workflow.createdAt,
          updatedAt: now2,
          metadata: { description: workflow.description, state: workflow.state, stepCount: workflow.steps.size }
        };
        this.upsertDocument(doc);
        return id;
      }
      async indexStep(step2, workflowId) {
        this.ensureReady();
        const content = this.stepToContent(step2);
        const embedding = await this.embedder.embed(content);
        const id = `step_${workflowId}_${step2.id}`;
        const now2 = Date.now();
        const doc = {
          id,
          workflowId,
          stepId: step2.id,
          docType: "step",
          content,
          title: step2.name,
          embedding: { data: serializeEmbedding(embedding), dimensions: embedding.length },
          createdAt: step2.startedAt ?? now2,
          updatedAt: step2.completedAt ?? now2,
          metadata: { discipline: step2.discipline, state: step2.state, config: step2.config }
        };
        this.upsertDocument(doc);
        return id;
      }
      async indexWorkflowWithSteps(workflow) {
        const ids = [];
        const wfId = await this.indexWorkflow(workflow);
        ids.push(wfId);
        for (const step2 of workflow.steps.values()) {
          const stepId = await this.indexStep(step2, workflow.id);
          ids.push(stepId);
        }
        return ids;
      }
      async deleteByWorkflow(workflowId) {
        this.ensureReady();
        const result = this.db.prepare("DELETE FROM vector_documents WHERE workflow_id = ?").run(workflowId);
        return result.changes;
      }
      async deleteByStep(workflowId, stepId) {
        this.ensureReady();
        const id = `step_${workflowId}_${stepId}`;
        const result = this.db.prepare("DELETE FROM vector_documents WHERE id = ?").run(id);
        return result.changes > 0;
      }
      getStats() {
        this.ensureReady();
        const total = this.db.prepare("SELECT COUNT(*) as count FROM vector_documents").get().count;
        const workflows = this.db.prepare("SELECT COUNT(*) as count FROM vector_documents WHERE doc_type = 'workflow'").get().count;
        const dims = this.embedder.dimensions;
        return {
          totalDocuments: total,
          workflowDocuments: workflows,
          stepDocuments: total - workflows,
          dimensions: dims,
          provider: this.embedder.providerType,
          estimatedSizeBytes: total * dims * 4
        };
      }
      async ftsSearch(query, limit) {
        this.ensureReady();
        const escaped = query.replace(/"/g, '""');
        const ftsQuery = `"${escaped}"`;
        const rows = this.db.prepare(`
      SELECT vd.id, fts.rank
      FROM vector_fts fts
      JOIN vector_documents vd ON fts.id = vd.id
      WHERE vector_fts MATCH ?
      ORDER BY fts.rank
      LIMIT ?
    `).all(ftsQuery, limit);
        return rows.map((row, idx) => ({
          id: row.id,
          rank: idx,
          score: 1 / (1 + Math.abs(row.rank))
        }));
      }
      async vectorSearch(embedding, limit) {
        this.ensureReady();
        const rows = this.db.prepare(
          "SELECT id, embedding_data, embedding_dims FROM vector_documents"
        ).all();
        const scored = [];
        for (const row of rows) {
          const stored = deserializeEmbedding(row.embedding_data, row.embedding_dims);
          const sim = cosineSimilarity2(embedding, stored);
          scored.push({ id: row.id, similarity: sim, rank: 0 });
        }
        scored.sort((a, b) => b.similarity - a.similarity);
        for (let i = 0; i < scored.length; i++) {
          scored[i].rank = i;
        }
        return scored.slice(0, limit);
      }
      async getDocuments(ids) {
        this.ensureReady();
        const result = /* @__PURE__ */ new Map();
        if (ids.length === 0) return result;
        const placeholders = ids.map(() => "?").join(",");
        const rows = this.db.prepare(
          `SELECT * FROM vector_documents WHERE id IN (${placeholders})`
        ).all(...ids);
        for (const row of rows) {
          result.set(row.id, this.rowToDoc(row));
        }
        return result;
      }
      async getAllEmbeddings(ids) {
        this.ensureReady();
        const result = /* @__PURE__ */ new Map();
        if (ids.length === 0) return result;
        const placeholders = ids.map(() => "?").join(",");
        const rows = this.db.prepare(
          `SELECT id, embedding_data, embedding_dims FROM vector_documents WHERE id IN (${placeholders})`
        ).all(...ids);
        for (const row of rows) {
          result.set(row.id, deserializeEmbedding(row.embedding_data, row.embedding_dims));
        }
        return result;
      }
      async close() {
        if (this.db) {
          this.db.close();
          this.db = null;
        }
      }
      upsertDocument(doc) {
        this.db.prepare(`
      INSERT INTO vector_documents (id, workflow_id, step_id, doc_type, title, content, embedding_data, embedding_dims, created_at, updated_at, metadata)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      ON CONFLICT(id) DO UPDATE SET
        title = excluded.title,
        content = excluded.content,
        embedding_data = excluded.embedding_data,
        embedding_dims = excluded.embedding_dims,
        updated_at = excluded.updated_at,
        metadata = excluded.metadata
    `).run(
          doc.id,
          doc.workflowId,
          doc.stepId ?? null,
          doc.docType,
          doc.title,
          doc.content,
          doc.embedding.data,
          doc.embedding.dimensions,
          doc.createdAt,
          doc.updatedAt,
          JSON.stringify(doc.metadata)
        );
      }
      rowToDoc(row) {
        return {
          id: row.id,
          workflowId: row.workflow_id,
          stepId: row.step_id ?? void 0,
          docType: row.doc_type,
          title: row.title,
          content: row.content,
          embedding: { data: row.embedding_data, dimensions: row.embedding_dims },
          createdAt: row.created_at,
          updatedAt: row.updated_at,
          metadata: JSON.parse(row.metadata)
        };
      }
      workflowToContent(workflow) {
        const stepDescriptions = Array.from(workflow.steps.values()).map((s) => `${s.name} (${s.discipline}): ${this.configToText(s.config)}`).join("; ");
        return [
          `Workflow: ${workflow.name}`,
          workflow.description,
          `State: ${workflow.state}`,
          `Steps: ${stepDescriptions}`
        ].filter(Boolean).join("\n");
      }
      stepToContent(step2) {
        return [
          `Step: ${step2.name}`,
          `Discipline: ${step2.discipline}`,
          `State: ${step2.state}`,
          this.configToText(step2.config),
          step2.error ? `Error: ${step2.error}` : "",
          step2.result ? `Result: ${JSON.stringify(step2.result)}` : ""
        ].filter(Boolean).join("\n");
      }
      configToText(config) {
        try {
          return JSON.stringify(config);
        } catch (e) {
          console.warn(`error: ${e}`);
          return String(config);
        }
      }
      ensureReady() {
        if (!this.db) throw new Error("VectorIndexer not initialized. Call init() first.");
      }
      async openDatabase() {
        const { default: Database2 } = await import("better-sqlite3");
        return new Database2(this.dbPath);
      }
    };
  }
});

// src/vector/embedding-config.ts
var embedding_config_exports = {};
__export(embedding_config_exports, {
  detectEmbeddingConfig: () => detectEmbeddingConfig,
  validateEmbeddingConfig: () => validateEmbeddingConfig
});
import { readFileSync } from "fs";
import { join } from "path";
import { homedir } from "os";
function detectEmbeddingConfig() {
  try {
    const configPath = join(homedir(), ".openclaw", "openclaw.json");
    const raw = readFileSync(configPath, "utf-8");
    const config = JSON.parse(raw);
    const providers = config.models?.providers;
    if (!providers) return { type: "local" };
    const zai = providers["zai"];
    if (zai?.apiKey) {
      return {
        type: "glm",
        apiBase: zai.baseUrl || "https://open.bigmodel.cn/api/paas/v4",
        apiKey: zai.apiKey,
        model: "embedding-3",
        dimensions: 2048
      };
    }
    const minimax = providers["minimax"];
    if (minimax?.apiKey) {
      return {
        type: "minimax",
        apiBase: minimax.baseUrl || "https://api.minimax.chat/v1",
        apiKey: minimax.apiKey,
        model: "text-embedding-01",
        dimensions: 1536
      };
    }
    for (const [name, provider] of Object.entries(providers)) {
      if (name === "zai" || name === "minimax") continue;
      if (provider?.apiKey && provider?.baseUrl) {
        return {
          type: "openai",
          apiBase: provider.baseUrl,
          apiKey: provider.apiKey,
          dimensions: 1536
        };
      }
    }
  } catch (e) {
    console.warn(`error: ${e}`);
  }
  return { type: "local" };
}
async function validateEmbeddingConfig(config) {
  try {
    const { createEmbedder: createEmbedder2 } = await Promise.resolve().then(() => (init_embedder(), embedder_exports));
    const embedder = createEmbedder2(config);
    const result = await embedder.embed("test");
    return result.length === embedder.dimensions && result.some((v) => v !== 0);
  } catch (e) {
    console.warn(`error: ${e}`);
    return false;
  }
}
var init_embedding_config = __esm({
  "src/vector/embedding-config.ts"() {
    "use strict";
  }
});

// src/vector/index.ts
var vector_exports = {};
__export(vector_exports, {
  HybridRetriever: () => HybridRetriever,
  VectorIndexer: () => VectorIndexer,
  VectorSearchSystem: () => VectorSearchSystem,
  createEmbedder: () => createEmbedder,
  detectEmbeddingConfig: () => detectEmbeddingConfig,
  validateEmbeddingConfig: () => validateEmbeddingConfig
});
var VectorSearchSystem;
var init_vector = __esm({
  "src/vector/index.ts"() {
    "use strict";
    init_types();
    init_embedder();
    init_retriever();
    init_indexer();
    init_embedder();
    init_embedding_config();
    init_retriever();
    init_indexer();
    VectorSearchSystem = class {
      embedder;
      indexer;
      retriever;
      semanticMemory = null;
      episodicMemory = null;
      initialized = false;
      constructor(config) {
        this.embedder = createEmbedder(config.embedding);
        this.indexer = new VectorIndexer(
          this.embedder,
          config.dbPath
        );
        this.retriever = new HybridRetriever(
          this.embedder,
          this.indexer,
          config.search
        );
      }
      async init() {
        if (this.initialized) return;
        await this.indexer.init();
        this.initialized = true;
      }
      async searchWorkflows(query, topK) {
        this.ensureReady();
        const results = await this.retriever.search(query, topK);
        const workflowIds = new Set(
          results.filter((r) => !r.stepId).map((r) => r.workflowId)
        );
        for (const r of results) {
          workflowIds.add(r.workflowId);
        }
        return Array.from(workflowIds).map((id) => ({
          id,
          name: results.find((r) => r.workflowId === id)?.title ?? "Unknown",
          description: "",
          steps: /* @__PURE__ */ new Map(),
          dag: { nodes: /* @__PURE__ */ new Map(), edges: [], layers: [] },
          state: "completed",
          currentSteps: [],
          createdAt: Date.now(),
          updatedAt: Date.now(),
          metadata: {}
        }));
      }
      async searchSteps(query, topK) {
        this.ensureReady();
        const results = await this.retriever.search(query, topK);
        const stepResults = results.filter((r) => r.stepId);
        return stepResults.map((r) => ({
          workflowId: r.workflowId,
          step: {
            id: r.stepId,
            name: r.title,
            discipline: r.metadata["discipline"] ?? "quick",
            dependencies: [],
            config: r.metadata["config"] ?? {},
            state: r.metadata["state"] ?? "completed",
            result: r.metadata["result"],
            startedAt: r.timestamp,
            completedAt: r.timestamp
          }
        }));
      }
      async search(query) {
        this.ensureReady();
        const resolvedQuery = typeof query === "string" ? { text: query, mode: "auto" } : query;
        const topK = resolvedQuery.topK ?? DEFAULT_SEARCH_OPTIONS.defaultTopK;
        const results = await this.retriever.search(resolvedQuery.text, topK);
        const workflowIds = new Set(results.map((r) => r.workflowId));
        const workflows = Array.from(workflowIds).map((id) => {
          const topResult = results.find((r) => r.workflowId === id);
          return {
            id,
            name: topResult.title,
            description: "",
            steps: /* @__PURE__ */ new Map(),
            dag: { nodes: /* @__PURE__ */ new Map(), edges: [], layers: [] },
            state: "completed",
            currentSteps: [],
            createdAt: topResult.timestamp,
            updatedAt: topResult.timestamp,
            metadata: topResult.metadata
          };
        });
        const steps = results.filter((r) => r.stepId).map((r) => ({
          step: {
            id: r.stepId,
            name: r.title,
            discipline: r.metadata["discipline"] ?? "quick",
            dependencies: [],
            config: r.metadata["config"] ?? {},
            state: r.metadata["state"] ?? "completed",
            result: r.metadata["result"],
            startedAt: r.timestamp,
            completedAt: r.timestamp
          },
          workflowId: r.workflowId
        }));
        return { workflows, steps, results };
      }
      async indexWorkflow(workflow) {
        this.ensureReady();
        return this.indexer.indexWorkflowWithSteps(workflow);
      }
      async removeFromIndex(workflowId) {
        this.ensureReady();
        return this.indexer.deleteByWorkflow(workflowId);
      }
      setSemanticMemory(memory) {
        this.semanticMemory = memory;
      }
      setEpisodicMemory(memory) {
        this.episodicMemory = memory;
      }
      async searchWithMemory(query, topK) {
        this.ensureReady();
        const vectorResults = await this.retriever.search(query, topK);
        const semanticFacts = [];
        if (this.semanticMemory) {
          const memResults = await this.semanticMemory.getFacts({
            text: query,
            limit: 5
          });
          for (const r of memResults) {
            if ("key" in r.entry) {
              const entry = r.entry;
              semanticFacts.push({ key: entry.key, value: entry.value, score: r.score });
            }
          }
        }
        const episodicMatches = [];
        if (this.episodicMemory) {
          const epResults = this.episodicMemory.searchExecutions({
            text: query,
            limit: 5
          });
          for (const r of epResults) {
            if ("workflowName" in r.entry) {
              const entry = r.entry;
              episodicMatches.push({ workflowName: entry.workflowName, score: r.score });
            }
          }
        }
        return { vectorResults, semanticFacts, episodicMatches };
      }
      getStats() {
        return this.indexer.getStats();
      }
      async close() {
        await this.indexer.close();
        this.initialized = false;
      }
      ensureReady() {
        if (!this.initialized) throw new Error("VectorSearchSystem not initialized. Call init() first.");
      }
    };
  }
});

// node_modules/yaml/dist/nodes/identity.js
var require_identity = __commonJS({
  "node_modules/yaml/dist/nodes/identity.js"(exports) {
    "use strict";
    var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias");
    var DOC = /* @__PURE__ */ Symbol.for("yaml.document");
    var MAP = /* @__PURE__ */ Symbol.for("yaml.map");
    var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair");
    var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar");
    var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq");
    var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type");
    var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS;
    var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC;
    var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
    var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR;
    var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
    var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
    function isCollection(node) {
      if (node && typeof node === "object")
        switch (node[NODE_TYPE]) {
          case MAP:
          case SEQ:
            return true;
        }
      return false;
    }
    function isNode(node) {
      if (node && typeof node === "object")
        switch (node[NODE_TYPE]) {
          case ALIAS:
          case MAP:
          case SCALAR:
          case SEQ:
            return true;
        }
      return false;
    }
    var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
    exports.ALIAS = ALIAS;
    exports.DOC = DOC;
    exports.MAP = MAP;
    exports.NODE_TYPE = NODE_TYPE;
    exports.PAIR = PAIR;
    exports.SCALAR = SCALAR;
    exports.SEQ = SEQ;
    exports.hasAnchor = hasAnchor;
    exports.isAlias = isAlias;
    exports.isCollection = isCollection;
    exports.isDocument = isDocument;
    exports.isMap = isMap;
    exports.isNode = isNode;
    exports.isPair = isPair;
    exports.isScalar = isScalar;
    exports.isSeq = isSeq;
  }
});

// node_modules/yaml/dist/visit.js
var require_visit = __commonJS({
  "node_modules/yaml/dist/visit.js"(exports) {
    "use strict";
    var identity = require_identity();
    var BREAK = /* @__PURE__ */ Symbol("break visit");
    var SKIP = /* @__PURE__ */ Symbol("skip children");
    var REMOVE = /* @__PURE__ */ Symbol("remove node");
    function visit(node, visitor) {
      const visitor_ = initVisitor(visitor);
      if (identity.isDocument(node)) {
        const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
        if (cd === REMOVE)
          node.contents = null;
      } else
        visit_(null, node, visitor_, Object.freeze([]));
    }
    visit.BREAK = BREAK;
    visit.SKIP = SKIP;
    visit.REMOVE = REMOVE;
    function visit_(key, node, visitor, path4) {
      const ctrl = callVisitor(key, node, visitor, path4);
      if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
        replaceNode(key, path4, ctrl);
        return visit_(key, ctrl, visitor, path4);
      }
      if (typeof ctrl !== "symbol") {
        if (identity.isCollection(node)) {
          path4 = Object.freeze(path4.concat(node));
          for (let i = 0; i < node.items.length; ++i) {
            const ci = visit_(i, node.items[i], visitor, path4);
            if (typeof ci === "number")
              i = ci - 1;
            else if (ci === BREAK)
              return BREAK;
            else if (ci === REMOVE) {
              node.items.splice(i, 1);
              i -= 1;
            }
          }
        } else if (identity.isPair(node)) {
          path4 = Object.freeze(path4.concat(node));
          const ck = visit_("key", node.key, visitor, path4);
          if (ck === BREAK)
            return BREAK;
          else if (ck === REMOVE)
            node.key = null;
          const cv = visit_("value", node.value, visitor, path4);
          if (cv === BREAK)
            return BREAK;
          else if (cv === REMOVE)
            node.value = null;
        }
      }
      return ctrl;
    }
    async function visitAsync(node, visitor) {
      const visitor_ = initVisitor(visitor);
      if (identity.isDocument(node)) {
        const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
        if (cd === REMOVE)
          node.contents = null;
      } else
        await visitAsync_(null, node, visitor_, Object.freeze([]));
    }
    visitAsync.BREAK = BREAK;
    visitAsync.SKIP = SKIP;
    visitAsync.REMOVE = REMOVE;
    async function visitAsync_(key, node, visitor, path4) {
      const ctrl = await callVisitor(key, node, visitor, path4);
      if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
        replaceNode(key, path4, ctrl);
        return visitAsync_(key, ctrl, visitor, path4);
      }
      if (typeof ctrl !== "symbol") {
        if (identity.isCollection(node)) {
          path4 = Object.freeze(path4.concat(node));
          for (let i = 0; i < node.items.length; ++i) {
            const ci = await visitAsync_(i, node.items[i], visitor, path4);
            if (typeof ci === "number")
              i = ci - 1;
            else if (ci === BREAK)
              return BREAK;
            else if (ci === REMOVE) {
              node.items.splice(i, 1);
              i -= 1;
            }
          }
        } else if (identity.isPair(node)) {
          path4 = Object.freeze(path4.concat(node));
          const ck = await visitAsync_("key", node.key, visitor, path4);
          if (ck === BREAK)
            return BREAK;
          else if (ck === REMOVE)
            node.key = null;
          const cv = await visitAsync_("value", node.value, visitor, path4);
          if (cv === BREAK)
            return BREAK;
          else if (cv === REMOVE)
            node.value = null;
        }
      }
      return ctrl;
    }
    function initVisitor(visitor) {
      if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) {
        return Object.assign({
          Alias: visitor.Node,
          Map: visitor.Node,
          Scalar: visitor.Node,
          Seq: visitor.Node
        }, visitor.Value && {
          Map: visitor.Value,
          Scalar: visitor.Value,
          Seq: visitor.Value
        }, visitor.Collection && {
          Map: visitor.Collection,
          Seq: visitor.Collection
        }, visitor);
      }
      return visitor;
    }
    function callVisitor(key, node, visitor, path4) {
      if (typeof visitor === "function")
        return visitor(key, node, path4);
      if (identity.isMap(node))
        return visitor.Map?.(key, node, path4);
      if (identity.isSeq(node))
        return visitor.Seq?.(key, node, path4);
      if (identity.isPair(node))
        return visitor.Pair?.(key, node, path4);
      if (identity.isScalar(node))
        return visitor.Scalar?.(key, node, path4);
      if (identity.isAlias(node))
        return visitor.Alias?.(key, node, path4);
      return void 0;
    }
    function replaceNode(key, path4, node) {
      const parent = path4[path4.length - 1];
      if (identity.isCollection(parent)) {
        parent.items[key] = node;
      } else if (identity.isPair(parent)) {
        if (key === "key")
          parent.key = node;
        else
          parent.value = node;
      } else if (identity.isDocument(parent)) {
        parent.contents = node;
      } else {
        const pt = identity.isAlias(parent) ? "alias" : "scalar";
        throw new Error(`Cannot replace node with ${pt} parent`);
      }
    }
    exports.visit = visit;
    exports.visitAsync = visitAsync;
  }
});

// node_modules/yaml/dist/doc/directives.js
var require_directives = __commonJS({
  "node_modules/yaml/dist/doc/directives.js"(exports) {
    "use strict";
    var identity = require_identity();
    var visit = require_visit();
    var escapeChars = {
      "!": "%21",
      ",": "%2C",
      "[": "%5B",
      "]": "%5D",
      "{": "%7B",
      "}": "%7D"
    };
    var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]);
    var Directives = class _Directives {
      constructor(yaml, tags) {
        this.docStart = null;
        this.docEnd = false;
        this.yaml = Object.assign({}, _Directives.defaultYaml, yaml);
        this.tags = Object.assign({}, _Directives.defaultTags, tags);
      }
      clone() {
        const copy = new _Directives(this.yaml, this.tags);
        copy.docStart = this.docStart;
        return copy;
      }
      /**
       * During parsing, get a Directives instance for the current document and
       * update the stream state according to the current version's spec.
       */
      atDocument() {
        const res = new _Directives(this.yaml, this.tags);
        switch (this.yaml.version) {
          case "1.1":
            this.atNextDocument = true;
            break;
          case "1.2":
            this.atNextDocument = false;
            this.yaml = {
              explicit: _Directives.defaultYaml.explicit,
              version: "1.2"
            };
            this.tags = Object.assign({}, _Directives.defaultTags);
            break;
        }
        return res;
      }
      /**
       * @param onError - May be called even if the action was successful
       * @returns `true` on success
       */
      add(line, onError) {
        if (this.atNextDocument) {
          this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" };
          this.tags = Object.assign({}, _Directives.defaultTags);
          this.atNextDocument = false;
        }
        const parts = line.trim().split(/[ \t]+/);
        const name = parts.shift();
        switch (name) {
          case "%TAG": {
            if (parts.length !== 2) {
              onError(0, "%TAG directive should contain exactly two parts");
              if (parts.length < 2)
                return false;
            }
            const [handle, prefix] = parts;
            this.tags[handle] = prefix;
            return true;
          }
          case "%YAML": {
            this.yaml.explicit = true;
            if (parts.length !== 1) {
              onError(0, "%YAML directive should contain exactly one part");
              return false;
            }
            const [version] = parts;
            if (version === "1.1" || version === "1.2") {
              this.yaml.version = version;
              return true;
            } else {
              const isValid = /^\d+\.\d+$/.test(version);
              onError(6, `Unsupported YAML version ${version}`, isValid);
              return false;
            }
          }
          default:
            onError(0, `Unknown directive ${name}`, true);
            return false;
        }
      }
      /**
       * Resolves a tag, matching handles to those defined in %TAG directives.
       *
       * @returns Resolved tag, which may also be the non-specific tag `'!'` or a
       *   `'!local'` tag, or `null` if unresolvable.
       */
      tagName(source, onError) {
        if (source === "!")
          return "!";
        if (source[0] !== "!") {
          onError(`Not a valid tag: ${source}`);
          return null;
        }
        if (source[1] === "<") {
          const verbatim = source.slice(2, -1);
          if (verbatim === "!" || verbatim === "!!") {
            onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
            return null;
          }
          if (source[source.length - 1] !== ">")
            onError("Verbatim tags must end with a >");
          return verbatim;
        }
        const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
        if (!suffix)
          onError(`The ${source} tag has no suffix`);
        const prefix = this.tags[handle];
        if (prefix) {
          try {
            return prefix + decodeURIComponent(suffix);
          } catch (error) {
            onError(String(error));
            return null;
          }
        }
        if (handle === "!")
          return source;
        onError(`Could not resolve tag: ${source}`);
        return null;
      }
      /**
       * Given a fully resolved tag, returns its printable string form,
       * taking into account current tag prefixes and defaults.
       */
      tagString(tag) {
        for (const [handle, prefix] of Object.entries(this.tags)) {
          if (tag.startsWith(prefix))
            return handle + escapeTagName(tag.substring(prefix.length));
        }
        return tag[0] === "!" ? tag : `!<${tag}>`;
      }
      toString(doc) {
        const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : [];
        const tagEntries = Object.entries(this.tags);
        let tagNames;
        if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) {
          const tags = {};
          visit.visit(doc.contents, (_key, node) => {
            if (identity.isNode(node) && node.tag)
              tags[node.tag] = true;
          });
          tagNames = Object.keys(tags);
        } else
          tagNames = [];
        for (const [handle, prefix] of tagEntries) {
          if (handle === "!!" && prefix === "tag:yaml.org,2002:")
            continue;
          if (!doc || tagNames.some((tn) => tn.startsWith(prefix)))
            lines.push(`%TAG ${handle} ${prefix}`);
        }
        return lines.join("\n");
      }
    };
    Directives.defaultYaml = { explicit: false, version: "1.2" };
    Directives.defaultTags = { "!!": "tag:yaml.org,2002:" };
    exports.Directives = Directives;
  }
});

// node_modules/yaml/dist/doc/anchors.js
var require_anchors = __commonJS({
  "node_modules/yaml/dist/doc/anchors.js"(exports) {
    "use strict";
    var identity = require_identity();
    var visit = require_visit();
    function anchorIsValid(anchor) {
      if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
        const sa = JSON.stringify(anchor);
        const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
        throw new Error(msg);
      }
      return true;
    }
    function anchorNames(root) {
      const anchors = /* @__PURE__ */ new Set();
      visit.visit(root, {
        Value(_key, node) {
          if (node.anchor)
            anchors.add(node.anchor);
        }
      });
      return anchors;
    }
    function findNewAnchor(prefix, exclude) {
      for (let i = 1; true; ++i) {
        const name = `${prefix}${i}`;
        if (!exclude.has(name))
          return name;
      }
    }
    function createNodeAnchors(doc, prefix) {
      const aliasObjects = [];
      const sourceObjects = /* @__PURE__ */ new Map();
      let prevAnchors = null;
      return {
        onAnchor: (source) => {
          aliasObjects.push(source);
          prevAnchors ?? (prevAnchors = anchorNames(doc));
          const anchor = findNewAnchor(prefix, prevAnchors);
          prevAnchors.add(anchor);
          return anchor;
        },
        /**
         * With circular references, the source node is only resolved after all
         * of its child nodes are. This is why anchors are set only after all of
         * the nodes have been created.
         */
        setAnchors: () => {
          for (const source of aliasObjects) {
            const ref = sourceObjects.get(source);
            if (typeof ref === "object" && ref.anchor && (identity.isScalar(ref.node) || identity.isCollection(ref.node))) {
              ref.node.anchor = ref.anchor;
            } else {
              const error = new Error("Failed to resolve repeated object (this should not happen)");
              error.source = source;
              throw error;
            }
          }
        },
        sourceObjects
      };
    }
    exports.anchorIsValid = anchorIsValid;
    exports.anchorNames = anchorNames;
    exports.createNodeAnchors = createNodeAnchors;
    exports.findNewAnchor = findNewAnchor;
  }
});

// node_modules/yaml/dist/doc/applyReviver.js
var require_applyReviver = __commonJS({
  "node_modules/yaml/dist/doc/applyReviver.js"(exports) {
    "use strict";
    function applyReviver(reviver, obj, key, val) {
      if (val && typeof val === "object") {
        if (Array.isArray(val)) {
          for (let i = 0, len = val.length; i < len; ++i) {
            const v0 = val[i];
            const v1 = applyReviver(reviver, val, String(i), v0);
            if (v1 === void 0)
              delete val[i];
            else if (v1 !== v0)
              val[i] = v1;
          }
        } else if (val instanceof Map) {
          for (const k of Array.from(val.keys())) {
            const v0 = val.get(k);
            const v1 = applyReviver(reviver, val, k, v0);
            if (v1 === void 0)
              val.delete(k);
            else if (v1 !== v0)
              val.set(k, v1);
          }
        } else if (val instanceof Set) {
          for (const v0 of Array.from(val)) {
            const v1 = applyReviver(reviver, val, v0, v0);
            if (v1 === void 0)
              val.delete(v0);
            else if (v1 !== v0) {
              val.delete(v0);
              val.add(v1);
            }
          }
        } else {
          for (const [k, v0] of Object.entries(val)) {
            const v1 = applyReviver(reviver, val, k, v0);
            if (v1 === void 0)
              delete val[k];
            else if (v1 !== v0)
              val[k] = v1;
          }
        }
      }
      return reviver.call(obj, key, val);
    }
    exports.applyReviver = applyReviver;
  }
});

// node_modules/yaml/dist/nodes/toJS.js
var require_toJS = __commonJS({
  "node_modules/yaml/dist/nodes/toJS.js"(exports) {
    "use strict";
    var identity = require_identity();
    function toJS(value, arg, ctx) {
      if (Array.isArray(value))
        return value.map((v, i) => toJS(v, String(i), ctx));
      if (value && typeof value.toJSON === "function") {
        if (!ctx || !identity.hasAnchor(value))
          return value.toJSON(arg, ctx);
        const data = { aliasCount: 0, count: 1, res: void 0 };
        ctx.anchors.set(value, data);
        ctx.onCreate = (res2) => {
          data.res = res2;
          delete ctx.onCreate;
        };
        const res = value.toJSON(arg, ctx);
        if (ctx.onCreate)
          ctx.onCreate(res);
        return res;
      }
      if (typeof value === "bigint" && !ctx?.keep)
        return Number(value);
      return value;
    }
    exports.toJS = toJS;
  }
});

// node_modules/yaml/dist/nodes/Node.js
var require_Node = __commonJS({
  "node_modules/yaml/dist/nodes/Node.js"(exports) {
    "use strict";
    var applyReviver = require_applyReviver();
    var identity = require_identity();
    var toJS = require_toJS();
    var NodeBase = class {
      constructor(type) {
        Object.defineProperty(this, identity.NODE_TYPE, { value: type });
      }
      /** Create a copy of this node.  */
      clone() {
        const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
        if (this.range)
          copy.range = this.range.slice();
        return copy;
      }
      /** A plain JavaScript representation of this node. */
      toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
        if (!identity.isDocument(doc))
          throw new TypeError("A document argument is required");
        const ctx = {
          anchors: /* @__PURE__ */ new Map(),
          doc,
          keep: true,
          mapAsMap: mapAsMap === true,
          mapKeyWarned: false,
          maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
        };
        const res = toJS.toJS(this, "", ctx);
        if (typeof onAnchor === "function")
          for (const { count, res: res2 } of ctx.anchors.values())
            onAnchor(res2, count);
        return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
      }
    };
    exports.NodeBase = NodeBase;
  }
});

// node_modules/yaml/dist/nodes/Alias.js
var require_Alias = __commonJS({
  "node_modules/yaml/dist/nodes/Alias.js"(exports) {
    "use strict";
    var anchors = require_anchors();
    var visit = require_visit();
    var identity = require_identity();
    var Node = require_Node();
    var toJS = require_toJS();
    var Alias = class extends Node.NodeBase {
      constructor(source) {
        super(identity.ALIAS);
        this.source = source;
        Object.defineProperty(this, "tag", {
          set() {
            throw new Error("Alias nodes cannot have tags");
          }
        });
      }
      /**
       * Resolve the value of this alias within `doc`, finding the last
       * instance of the `source` anchor before this node.
       */
      resolve(doc, ctx) {
        let nodes;
        if (ctx?.aliasResolveCache) {
          nodes = ctx.aliasResolveCache;
        } else {
          nodes = [];
          visit.visit(doc, {
            Node: (_key, node) => {
              if (identity.isAlias(node) || identity.hasAnchor(node))
                nodes.push(node);
            }
          });
          if (ctx)
            ctx.aliasResolveCache = nodes;
        }
        let found = void 0;
        for (const node of nodes) {
          if (node === this)
            break;
          if (node.anchor === this.source)
            found = node;
        }
        return found;
      }
      toJSON(_arg, ctx) {
        if (!ctx)
          return { source: this.source };
        const { anchors: anchors2, doc, maxAliasCount } = ctx;
        const source = this.resolve(doc, ctx);
        if (!source) {
          const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
          throw new ReferenceError(msg);
        }
        let data = anchors2.get(source);
        if (!data) {
          toJS.toJS(source, null, ctx);
          data = anchors2.get(source);
        }
        if (data?.res === void 0) {
          const msg = "This should not happen: Alias anchor was not resolved?";
          throw new ReferenceError(msg);
        }
        if (maxAliasCount >= 0) {
          data.count += 1;
          if (data.aliasCount === 0)
            data.aliasCount = getAliasCount(doc, source, anchors2);
          if (data.count * data.aliasCount > maxAliasCount) {
            const msg = "Excessive alias count indicates a resource exhaustion attack";
            throw new ReferenceError(msg);
          }
        }
        return data.res;
      }
      toString(ctx, _onComment, _onChompKeep) {
        const src = `*${this.source}`;
        if (ctx) {
          anchors.anchorIsValid(this.source);
          if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
            const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
            throw new Error(msg);
          }
          if (ctx.implicitKey)
            return `${src} `;
        }
        return src;
      }
    };
    function getAliasCount(doc, node, anchors2) {
      if (identity.isAlias(node)) {
        const source = node.resolve(doc);
        const anchor = anchors2 && source && anchors2.get(source);
        return anchor ? anchor.count * anchor.aliasCount : 0;
      } else if (identity.isCollection(node)) {
        let count = 0;
        for (const item of node.items) {
          const c = getAliasCount(doc, item, anchors2);
          if (c > count)
            count = c;
        }
        return count;
      } else if (identity.isPair(node)) {
        const kc = getAliasCount(doc, node.key, anchors2);
        const vc = getAliasCount(doc, node.value, anchors2);
        return Math.max(kc, vc);
      }
      return 1;
    }
    exports.Alias = Alias;
  }
});

// node_modules/yaml/dist/nodes/Scalar.js
var require_Scalar = __commonJS({
  "node_modules/yaml/dist/nodes/Scalar.js"(exports) {
    "use strict";
    var identity = require_identity();
    var Node = require_Node();
    var toJS = require_toJS();
    var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object";
    var Scalar = class extends Node.NodeBase {
      constructor(value) {
        super(identity.SCALAR);
        this.value = value;
      }
      toJSON(arg, ctx) {
        return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);
      }
      toString() {
        return String(this.value);
      }
    };
    Scalar.BLOCK_FOLDED = "BLOCK_FOLDED";
    Scalar.BLOCK_LITERAL = "BLOCK_LITERAL";
    Scalar.PLAIN = "PLAIN";
    Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE";
    Scalar.QUOTE_SINGLE = "QUOTE_SINGLE";
    exports.Scalar = Scalar;
    exports.isScalarValue = isScalarValue;
  }
});

// node_modules/yaml/dist/doc/createNode.js
var require_createNode = __commonJS({
  "node_modules/yaml/dist/doc/createNode.js"(exports) {
    "use strict";
    var Alias = require_Alias();
    var identity = require_identity();
    var Scalar = require_Scalar();
    var defaultTagPrefix = "tag:yaml.org,2002:";
    function findTagObject(value, tagName, tags) {
      if (tagName) {
        const match = tags.filter((t) => t.tag === tagName);
        const tagObj = match.find((t) => !t.format) ?? match[0];
        if (!tagObj)
          throw new Error(`Tag ${tagName} not found`);
        return tagObj;
      }
      return tags.find((t) => t.identify?.(value) && !t.format);
    }
    function createNode(value, tagName, ctx) {
      if (identity.isDocument(value))
        value = value.contents;
      if (identity.isNode(value))
        return value;
      if (identity.isPair(value)) {
        const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx);
        map.items.push(value);
        return map;
      }
      if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) {
        value = value.valueOf();
      }
      const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;
      let ref = void 0;
      if (aliasDuplicateObjects && value && typeof value === "object") {
        ref = sourceObjects.get(value);
        if (ref) {
          ref.anchor ?? (ref.anchor = onAnchor(value));
          return new Alias.Alias(ref.anchor);
        } else {
          ref = { anchor: null, node: null };
          sourceObjects.set(value, ref);
        }
      }
      if (tagName?.startsWith("!!"))
        tagName = defaultTagPrefix + tagName.slice(2);
      let tagObj = findTagObject(value, tagName, schema.tags);
      if (!tagObj) {
        if (value && typeof value.toJSON === "function") {
          value = value.toJSON();
        }
        if (!value || typeof value !== "object") {
          const node2 = new Scalar.Scalar(value);
          if (ref)
            ref.node = node2;
          return node2;
        }
        tagObj = value instanceof Map ? schema[identity.MAP] : Symbol.iterator in Object(value) ? schema[identity.SEQ] : schema[identity.MAP];
      }
      if (onTagObj) {
        onTagObj(tagObj);
        delete ctx.onTagObj;
      }
      const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar.Scalar(value);
      if (tagName)
        node.tag = tagName;
      else if (!tagObj.default)
        node.tag = tagObj.tag;
      if (ref)
        ref.node = node;
      return node;
    }
    exports.createNode = createNode;
  }
});

// node_modules/yaml/dist/nodes/Collection.js
var require_Collection = __commonJS({
  "node_modules/yaml/dist/nodes/Collection.js"(exports) {
    "use strict";
    var createNode = require_createNode();
    var identity = require_identity();
    var Node = require_Node();
    function collectionFromPath(schema, path4, value) {
      let v = value;
      for (let i = path4.length - 1; i >= 0; --i) {
        const k = path4[i];
        if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
          const a = [];
          a[k] = v;
          v = a;
        } else {
          v = /* @__PURE__ */ new Map([[k, v]]);
        }
      }
      return createNode.createNode(v, void 0, {
        aliasDuplicateObjects: false,
        keepUndefined: false,
        onAnchor: () => {
          throw new Error("This should not happen, please report a bug.");
        },
        schema,
        sourceObjects: /* @__PURE__ */ new Map()
      });
    }
    var isEmptyPath = (path4) => path4 == null || typeof path4 === "object" && !!path4[Symbol.iterator]().next().done;
    var Collection = class extends Node.NodeBase {
      constructor(type, schema) {
        super(type);
        Object.defineProperty(this, "schema", {
          value: schema,
          configurable: true,
          enumerable: false,
          writable: true
        });
      }
      /**
       * Create a copy of this collection.
       *
       * @param schema - If defined, overwrites the original's schema
       */
      clone(schema) {
        const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
        if (schema)
          copy.schema = schema;
        copy.items = copy.items.map((it) => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it);
        if (this.range)
          copy.range = this.range.slice();
        return copy;
      }
      /**
       * Adds a value to the collection. For `!!map` and `!!omap` the value must
       * be a Pair instance or a `{ key, value }` object, which may not have a key
       * that already exists in the map.
       */
      addIn(path4, value) {
        if (isEmptyPath(path4))
          this.add(value);
        else {
          const [key, ...rest] = path4;
          const node = this.get(key, true);
          if (identity.isCollection(node))
            node.addIn(rest, value);
          else if (node === void 0 && this.schema)
            this.set(key, collectionFromPath(this.schema, rest, value));
          else
            throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
        }
      }
      /**
       * Removes a value from the collection.
       * @returns `true` if the item was found and removed.
       */
      deleteIn(path4) {
        const [key, ...rest] = path4;
        if (rest.length === 0)
          return this.delete(key);
        const node = this.get(key, true);
        if (identity.isCollection(node))
          return node.deleteIn(rest);
        else
          throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
      }
      /**
       * Returns item at `key`, or `undefined` if not found. By default unwraps
       * scalar values from their surrounding node; to disable set `keepScalar` to
       * `true` (collections are always returned intact).
       */
      getIn(path4, keepScalar) {
        const [key, ...rest] = path4;
        const node = this.get(key, true);
        if (rest.length === 0)
          return !keepScalar && identity.isScalar(node) ? node.value : node;
        else
          return identity.isCollection(node) ? node.getIn(rest, keepScalar) : void 0;
      }
      hasAllNullValues(allowScalar) {
        return this.items.every((node) => {
          if (!identity.isPair(node))
            return false;
          const n = node.value;
          return n == null || allowScalar && identity.isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag;
        });
      }
      /**
       * Checks if the collection includes a value with the key `key`.
       */
      hasIn(path4) {
        const [key, ...rest] = path4;
        if (rest.length === 0)
          return this.has(key);
        const node = this.get(key, true);
        return identity.isCollection(node) ? node.hasIn(rest) : false;
      }
      /**
       * Sets a value in this collection. For `!!set`, `value` needs to be a
       * boolean to add/remove the item from the set.
       */
      setIn(path4, value) {
        const [key, ...rest] = path4;
        if (rest.length === 0) {
          this.set(key, value);
        } else {
          const node = this.get(key, true);
          if (identity.isCollection(node))
            node.setIn(rest, value);
          else if (node === void 0 && this.schema)
            this.set(key, collectionFromPath(this.schema, rest, value));
          else
            throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
        }
      }
    };
    exports.Collection = Collection;
    exports.collectionFromPath = collectionFromPath;
    exports.isEmptyPath = isEmptyPath;
  }
});

// node_modules/yaml/dist/stringify/stringifyComment.js
var require_stringifyComment = __commonJS({
  "node_modules/yaml/dist/stringify/stringifyComment.js"(exports) {
    "use strict";
    var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#");
    function indentComment(comment, indent) {
      if (/^\n+$/.test(comment))
        return comment.substring(1);
      return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
    }
    var lineComment = (str, indent, comment) => str.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment;
    exports.indentComment = indentComment;
    exports.lineComment = lineComment;
    exports.stringifyComment = stringifyComment;
  }
});

// node_modules/yaml/dist/stringify/foldFlowLines.js
var require_foldFlowLines = __commonJS({
  "node_modules/yaml/dist/stringify/foldFlowLines.js"(exports) {
    "use strict";
    var FOLD_FLOW = "flow";
    var FOLD_BLOCK = "block";
    var FOLD_QUOTED = "quoted";
    function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
      if (!lineWidth || lineWidth < 0)
        return text;
      if (lineWidth < minContentWidth)
        minContentWidth = 0;
      const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
      if (text.length <= endStep)
        return text;
      const folds = [];
      const escapedFolds = {};
      let end = lineWidth - indent.length;
      if (typeof indentAtStart === "number") {
        if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
          folds.push(0);
        else
          end = lineWidth - indentAtStart;
      }
      let split = void 0;
      let prev = void 0;
      let overflow = false;
      let i = -1;
      let escStart = -1;
      let escEnd = -1;
      if (mode === FOLD_BLOCK) {
        i = consumeMoreIndentedLines(text, i, indent.length);
        if (i !== -1)
          end = i + endStep;
      }
      for (let ch; ch = text[i += 1]; ) {
        if (mode === FOLD_QUOTED && ch === "\\") {
          escStart = i;
          switch (text[i + 1]) {
            case "x":
              i += 3;
              break;
            case "u":
              i += 5;
              break;
            case "U":
              i += 9;
              break;
            default:
              i += 1;
          }
          escEnd = i;
        }
        if (ch === "\n") {
          if (mode === FOLD_BLOCK)
            i = consumeMoreIndentedLines(text, i, indent.length);
          end = i + indent.length + endStep;
          split = void 0;
        } else {
          if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== "	") {
            const next = text[i + 1];
            if (next && next !== " " && next !== "\n" && next !== "	")
              split = i;
          }
          if (i >= end) {
            if (split) {
              folds.push(split);
              end = split + endStep;
              split = void 0;
            } else if (mode === FOLD_QUOTED) {
              while (prev === " " || prev === "	") {
                prev = ch;
                ch = text[i += 1];
                overflow = true;
              }
              const j = i > escEnd + 1 ? i - 2 : escStart - 1;
              if (escapedFolds[j])
                return text;
              folds.push(j);
              escapedFolds[j] = true;
              end = j + endStep;
              split = void 0;
            } else {
              overflow = true;
            }
          }
        }
        prev = ch;
      }
      if (overflow && onOverflow)
        onOverflow();
      if (folds.length === 0)
        return text;
      if (onFold)
        onFold();
      let res = text.slice(0, folds[0]);
      for (let i2 = 0; i2 < folds.length; ++i2) {
        const fold = folds[i2];
        const end2 = folds[i2 + 1] || text.length;
        if (fold === 0)
          res = `
${indent}${text.slice(0, end2)}`;
        else {
          if (mode === FOLD_QUOTED && escapedFolds[fold])
            res += `${text[fold]}\\`;
          res += `
${indent}${text.slice(fold + 1, end2)}`;
        }
      }
      return res;
    }
    function consumeMoreIndentedLines(text, i, indent) {
      let end = i;
      let start = i + 1;
      let ch = text[start];
      while (ch === " " || ch === "	") {
        if (i < start + indent) {
          ch = text[++i];
        } else {
          do {
            ch = text[++i];
          } while (ch && ch !== "\n");
          end = i;
          start = i + 1;
          ch = text[start];
        }
      }
      return end;
    }
    exports.FOLD_BLOCK = FOLD_BLOCK;
    exports.FOLD_FLOW = FOLD_FLOW;
    exports.FOLD_QUOTED = FOLD_QUOTED;
    exports.foldFlowLines = foldFlowLines;
  }
});

// node_modules/yaml/dist/stringify/stringifyString.js
var require_stringifyString = __commonJS({
  "node_modules/yaml/dist/stringify/stringifyString.js"(exports) {
    "use strict";
    var Scalar = require_Scalar();
    var foldFlowLines = require_foldFlowLines();
    var getFoldOptions = (ctx, isBlock) => ({
      indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
      lineWidth: ctx.options.lineWidth,
      minContentWidth: ctx.options.minContentWidth
    });
    var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
    function lineLengthOverLimit(str, lineWidth, indentLength) {
      if (!lineWidth || lineWidth < 0)
        return false;
      const limit = lineWidth - indentLength;
      const strLen = str.length;
      if (strLen <= limit)
        return false;
      for (let i = 0, start = 0; i < strLen; ++i) {
        if (str[i] === "\n") {
          if (i - start > limit)
            return true;
          start = i + 1;
          if (strLen - start <= limit)
            return false;
        }
      }
      return true;
    }
    function doubleQuotedString(value, ctx) {
      const json = JSON.stringify(value);
      if (ctx.options.doubleQuotedAsJSON)
        return json;
      const { implicitKey } = ctx;
      const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
      const indent = ctx.indent || (containsDocumentMarker(value) ? "  " : "");
      let str = "";
      let start = 0;
      for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
        if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") {
          str += json.slice(start, i) + "\\ ";
          i += 1;
          start = i;
          ch = "\\";
        }
        if (ch === "\\")
          switch (json[i + 1]) {
            case "u":
              {
                str += json.slice(start, i);
                const code = json.substr(i + 2, 4);
                switch (code) {
                  case "0000":
                    str += "\\0";
                    break;
                  case "0007":
                    str += "\\a";
                    break;
                  case "000b":
                    str += "\\v";
                    break;
                  case "001b":
                    str += "\\e";
                    break;
                  case "0085":
                    str += "\\N";
                    break;
                  case "00a0":
                    str += "\\_";
                    break;
                  case "2028":
                    str += "\\L";
                    break;
                  case "2029":
                    str += "\\P";
                    break;
                  default:
                    if (code.substr(0, 2) === "00")
                      str += "\\x" + code.substr(2);
                    else
                      str += json.substr(i, 6);
                }
                i += 5;
                start = i + 1;
              }
              break;
            case "n":
              if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
                i += 1;
              } else {
                str += json.slice(start, i) + "\n\n";
                while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') {
                  str += "\n";
                  i += 2;
                }
                str += indent;
                if (json[i + 2] === " ")
                  str += "\\";
                i += 1;
                start = i + 1;
              }
              break;
            default:
              i += 1;
          }
      }
      str = start ? str + json.slice(start) : json;
      return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));
    }
    function singleQuotedString(value, ctx) {
      if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value))
        return doubleQuotedString(value, ctx);
      const indent = ctx.indent || (containsDocumentMarker(value) ? "  " : "");
      const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&
${indent}`) + "'";
      return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
    }
    function quotedString(value, ctx) {
      const { singleQuote } = ctx.options;
      let qs;
      if (singleQuote === false)
        qs = doubleQuotedString;
      else {
        const hasDouble = value.includes('"');
        const hasSingle = value.includes("'");
        if (hasDouble && !hasSingle)
          qs = singleQuotedString;
        else if (hasSingle && !hasDouble)
          qs = doubleQuotedString;
        else
          qs = singleQuote ? singleQuotedString : doubleQuotedString;
      }
      return qs(value, ctx);
    }
    var blockEndNewlines;
    try {
      blockEndNewlines = new RegExp("(^|(?<!\n))\n+(?!\n|$)", "g");
    } catch {
      blockEndNewlines = /\n+(?!\n|$)/g;
    }
    function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
      const { blockQuote, commentString, lineWidth } = ctx.options;
      if (!blockQuote || /\n[\t ]+$/.test(value)) {
        return quotedString(value, ctx);
      }
      const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? "  " : "");
      const literal = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.Scalar.BLOCK_FOLDED ? false : type === Scalar.Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, lineWidth, indent.length);
      if (!value)
        return literal ? "|\n" : ">\n";
      let chomp;
      let endStart;
      for (endStart = value.length; endStart > 0; --endStart) {
        const ch = value[endStart - 1];
        if (ch !== "\n" && ch !== "	" && ch !== " ")
          break;
      }
      let end = value.substring(endStart);
      const endNlPos = end.indexOf("\n");
      if (endNlPos === -1) {
        chomp = "-";
      } else if (value === end || endNlPos !== end.length - 1) {
        chomp = "+";
        if (onChompKeep)
          onChompKeep();
      } else {
        chomp = "";
      }
      if (end) {
        value = value.slice(0, -end.length);
        if (end[end.length - 1] === "\n")
          end = end.slice(0, -1);
        end = end.replace(blockEndNewlines, `$&${indent}`);
      }
      let startWithSpace = false;
      let startEnd;
      let startNlPos = -1;
      for (startEnd = 0; startEnd < value.length; ++startEnd) {
        const ch = value[startEnd];
        if (ch === " ")
          startWithSpace = true;
        else if (ch === "\n")
          startNlPos = startEnd;
        else
          break;
      }
      let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
      if (start) {
        value = value.substring(start.length);
        start = start.replace(/\n+/g, `$&${indent}`);
      }
      const indentSize = indent ? "2" : "1";
      let header = (startWithSpace ? indentSize : "") + chomp;
      if (comment) {
        header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " "));
        if (onComment)
          onComment();
      }
      if (!literal) {
        const foldedValue = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
        let literalFallback = false;
        const foldOptions = getFoldOptions(ctx, true);
        if (blockQuote !== "folded" && type !== Scalar.Scalar.BLOCK_FOLDED) {
          foldOptions.onOverflow = () => {
            literalFallback = true;
          };
        }
        const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);
        if (!literalFallback)
          return `>${header}
${indent}${body}`;
      }
      value = value.replace(/\n+/g, `$&${indent}`);
      return `|${header}
${indent}${start}${value}${end}`;
    }
    function plainString(item, ctx, onComment, onChompKeep) {
      const { type, value } = item;
      const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
      if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) {
        return quotedString(value, ctx);
      }
      if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
        return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
      }
      if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value.includes("\n")) {
        return blockString(item, ctx, onComment, onChompKeep);
      }
      if (containsDocumentMarker(value)) {
        if (indent === "") {
          ctx.forceBlockIndent = true;
          return blockString(item, ctx, onComment, onChompKeep);
        } else if (implicitKey && indent === indentStep) {
          return quotedString(value, ctx);
        }
      }
      const str = value.replace(/\n+/g, `$&
${indent}`);
      if (actualString) {
        const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str);
        const { compat, tags } = ctx.doc.schema;
        if (tags.some(test) || compat?.some(test))
          return quotedString(value, ctx);
      }
      return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
    }
    function stringifyString(item, ctx, onComment, onChompKeep) {
      const { implicitKey, inFlow } = ctx;
      const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) });
      let { type } = item;
      if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
        if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
          type = Scalar.Scalar.QUOTE_DOUBLE;
      }
      const _stringify = (_type) => {
        switch (_type) {
          case Scalar.Scalar.BLOCK_FOLDED:
          case Scalar.Scalar.BLOCK_LITERAL:
            return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep);
          case Scalar.Scalar.QUOTE_DOUBLE:
            return doubleQuotedString(ss.value, ctx);
          case Scalar.Scalar.QUOTE_SINGLE:
            return singleQuotedString(ss.value, ctx);
          case Scalar.Scalar.PLAIN:
            return plainString(ss, ctx, onComment, onChompKeep);
          default:
            return null;
        }
      };
      let res = _stringify(type);
      if (res === null) {
        const { defaultKeyType, defaultStringType } = ctx.options;
        const t = implicitKey && defaultKeyType || defaultStringType;
        res = _stringify(t);
        if (res === null)
          throw new Error(`Unsupported default string type ${t}`);
      }
      return res;
    }
    exports.stringifyString = stringifyString;
  }
});

// node_modules/yaml/dist/stringify/stringify.js
var require_stringify = __commonJS({
  "node_modules/yaml/dist/stringify/stringify.js"(exports) {
    "use strict";
    var anchors = require_anchors();
    var identity = require_identity();
    var stringifyComment = require_stringifyComment();
    var stringifyString = require_stringifyString();
    function createStringifyContext(doc, options) {
      const opt = Object.assign({
        blockQuote: true,
        commentString: stringifyComment.stringifyComment,
        defaultKeyType: null,
        defaultStringType: "PLAIN",
        directives: null,
        doubleQuotedAsJSON: false,
        doubleQuotedMinMultiLineLength: 40,
        falseStr: "false",
        flowCollectionPadding: true,
        indentSeq: true,
        lineWidth: 80,
        minContentWidth: 20,
        nullStr: "null",
        simpleKeys: false,
        singleQuote: null,
        trailingComma: false,
        trueStr: "true",
        verifyAliasOrder: true
      }, doc.schema.toStringOptions, options);
      let inFlow;
      switch (opt.collectionStyle) {
        case "block":
          inFlow = false;
          break;
        case "flow":
          inFlow = true;
          break;
        default:
          inFlow = null;
      }
      return {
        anchors: /* @__PURE__ */ new Set(),
        doc,
        flowCollectionPadding: opt.flowCollectionPadding ? " " : "",
        indent: "",
        indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : "  ",
        inFlow,
        options: opt
      };
    }
    function getTagObject(tags, item) {
      if (item.tag) {
        const match = tags.filter((t) => t.tag === item.tag);
        if (match.length > 0)
          return match.find((t) => t.format === item.format) ?? match[0];
      }
      let tagObj = void 0;
      let obj;
      if (identity.isScalar(item)) {
        obj = item.value;
        let match = tags.filter((t) => t.identify?.(obj));
        if (match.length > 1) {
          const testMatch = match.filter((t) => t.test);
          if (testMatch.length > 0)
            match = testMatch;
        }
        tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format);
      } else {
        obj = item;
        tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass);
      }
      if (!tagObj) {
        const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj);
        throw new Error(`Tag not resolved for ${name} value`);
      }
      return tagObj;
    }
    function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {
      if (!doc.directives)
        return "";
      const props = [];
      const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor;
      if (anchor && anchors.anchorIsValid(anchor)) {
        anchors$1.add(anchor);
        props.push(`&${anchor}`);
      }
      const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);
      if (tag)
        props.push(doc.directives.tagString(tag));
      return props.join(" ");
    }
    function stringify(item, ctx, onComment, onChompKeep) {
      if (identity.isPair(item))
        return item.toString(ctx, onComment, onChompKeep);
      if (identity.isAlias(item)) {
        if (ctx.doc.directives)
          return item.toString(ctx);
        if (ctx.resolvedAliases?.has(item)) {
          throw new TypeError(`Cannot stringify circular structure without alias nodes`);
        } else {
          if (ctx.resolvedAliases)
            ctx.resolvedAliases.add(item);
          else
            ctx.resolvedAliases = /* @__PURE__ */ new Set([item]);
          item = item.resolve(ctx.doc);
        }
      }
      let tagObj = void 0;
      const node = identity.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o });
      tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));
      const props = stringifyProps(node, tagObj, ctx);
      if (props.length > 0)
        ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
      const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep);
      if (!props)
        return str;
      return identity.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props}
${ctx.indent}${str}`;
    }
    exports.createStringifyContext = createStringifyContext;
    exports.stringify = stringify;
  }
});

// node_modules/yaml/dist/stringify/stringifyPair.js
var require_stringifyPair = __commonJS({
  "node_modules/yaml/dist/stringify/stringifyPair.js"(exports) {
    "use strict";
    var identity = require_identity();
    var Scalar = require_Scalar();
    var stringify = require_stringify();
    var stringifyComment = require_stringifyComment();
    function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
      const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
      let keyComment = identity.isNode(key) && key.comment || null;
      if (simpleKeys) {
        if (keyComment) {
          throw new Error("With simple keys, key nodes cannot have comments");
        }
        if (identity.isCollection(key) || !identity.isNode(key) && typeof key === "object") {
          const msg = "With simple keys, collection cannot be used as a key value";
          throw new Error(msg);
        }
      }
      let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || identity.isCollection(key) || (identity.isScalar(key) ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL : typeof key === "object"));
      ctx = Object.assign({}, ctx, {
        allNullValues: false,
        implicitKey: !explicitKey && (simpleKeys || !allNullValues),
        indent: indent + indentStep
      });
      let keyCommentDone = false;
      let chompKeep = false;
      let str = stringify.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true);
      if (!explicitKey && !ctx.inFlow && str.length > 1024) {
        if (simpleKeys)
          throw new Error("With simple keys, single line scalar must not span more than 1024 characters");
        explicitKey = true;
      }
      if (ctx.inFlow) {
        if (allNullValues || value == null) {
          if (keyCommentDone && onComment)
            onComment();
          return str === "" ? "?" : explicitKey ? `? ${str}` : str;
        }
      } else if (allNullValues && !simpleKeys || value == null && explicitKey) {
        str = `? ${str}`;
        if (keyComment && !keyCommentDone) {
          str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
        } else if (chompKeep && onChompKeep)
          onChompKeep();
        return str;
      }
      if (keyCommentDone)
        keyComment = null;
      if (explicitKey) {
        if (keyComment)
          str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
        str = `? ${str}
${indent}:`;
      } else {
        str = `${str}:`;
        if (keyComment)
          str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
      }
      let vsb, vcb, valueComment;
      if (identity.isNode(value)) {
        vsb = !!value.spaceBefore;
        vcb = value.commentBefore;
        valueComment = value.comment;
      } else {
        vsb = false;
        vcb = null;
        valueComment = null;
        if (value && typeof value === "object")
          value = doc.createNode(value);
      }
      ctx.implicitKey = false;
      if (!explicitKey && !keyComment && identity.isScalar(value))
        ctx.indentAtStart = str.length + 1;
      chompKeep = false;
      if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity.isSeq(value) && !value.flow && !value.tag && !value.anchor) {
        ctx.indent = ctx.indent.substring(2);
      }
      let valueCommentDone = false;
      const valueStr = stringify.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true);
      let ws = " ";
      if (keyComment || vsb || vcb) {
        ws = vsb ? "\n" : "";
        if (vcb) {
          const cs = commentString(vcb);
          ws += `
${stringifyComment.indentComment(cs, ctx.indent)}`;
        }
        if (valueStr === "" && !ctx.inFlow) {
          if (ws === "\n" && valueComment)
            ws = "\n\n";
        } else {
          ws += `
${ctx.indent}`;
        }
      } else if (!explicitKey && identity.isCollection(value)) {
        const vs0 = valueStr[0];
        const nl0 = valueStr.indexOf("\n");
        const hasNewline = nl0 !== -1;
        const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
        if (hasNewline || !flow) {
          let hasPropsLine = false;
          if (hasNewline && (vs0 === "&" || vs0 === "!")) {
            let sp0 = valueStr.indexOf(" ");
            if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") {
              sp0 = valueStr.indexOf(" ", sp0 + 1);
            }
            if (sp0 === -1 || nl0 < sp0)
              hasPropsLine = true;
          }
          if (!hasPropsLine)
            ws = `
${ctx.indent}`;
        }
      } else if (valueStr === "" || valueStr[0] === "\n") {
        ws = "";
      }
      str += ws + valueStr;
      if (ctx.inFlow) {
        if (valueCommentDone && onComment)
          onComment();
      } else if (valueComment && !valueCommentDone) {
        str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));
      } else if (chompKeep && onChompKeep) {
        onChompKeep();
      }
      return str;
    }
    exports.stringifyPair = stringifyPair;
  }
});

// node_modules/yaml/dist/log.js
var require_log = __commonJS({
  "node_modules/yaml/dist/log.js"(exports) {
    "use strict";
    var node_process = __require("process");
    function debug(logLevel, ...messages) {
      if (logLevel === "debug")
        console.log(...messages);
    }
    function warn(logLevel, warning) {
      if (logLevel === "debug" || logLevel === "warn") {
        if (typeof node_process.emitWarning === "function")
          node_process.emitWarning(warning);
        else
          console.warn(warning);
      }
    }
    exports.debug = debug;
    exports.warn = warn;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/merge.js
var require_merge = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/merge.js"(exports) {
    "use strict";
    var identity = require_identity();
    var Scalar = require_Scalar();
    var MERGE_KEY = "<<";
    var merge = {
      identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY,
      default: "key",
      tag: "tag:yaml.org,2002:merge",
      test: /^<<$/,
      resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {
        addToJSMap: addMergeToJSMap
      }),
      stringify: () => MERGE_KEY
    };
    var isMergeKey = (ctx, key) => (merge.identify(key) || identity.isScalar(key) && (!key.type || key.type === Scalar.Scalar.PLAIN) && merge.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge.tag && tag.default);
    function addMergeToJSMap(ctx, map, value) {
      value = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value;
      if (identity.isSeq(value))
        for (const it of value.items)
          mergeValue(ctx, map, it);
      else if (Array.isArray(value))
        for (const it of value)
          mergeValue(ctx, map, it);
      else
        mergeValue(ctx, map, value);
    }
    function mergeValue(ctx, map, value) {
      const source = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value;
      if (!identity.isMap(source))
        throw new Error("Merge sources must be maps or map aliases");
      const srcMap = source.toJSON(null, ctx, Map);
      for (const [key, value2] of srcMap) {
        if (map instanceof Map) {
          if (!map.has(key))
            map.set(key, value2);
        } else if (map instanceof Set) {
          map.add(key);
        } else if (!Object.prototype.hasOwnProperty.call(map, key)) {
          Object.defineProperty(map, key, {
            value: value2,
            writable: true,
            enumerable: true,
            configurable: true
          });
        }
      }
      return map;
    }
    exports.addMergeToJSMap = addMergeToJSMap;
    exports.isMergeKey = isMergeKey;
    exports.merge = merge;
  }
});

// node_modules/yaml/dist/nodes/addPairToJSMap.js
var require_addPairToJSMap = __commonJS({
  "node_modules/yaml/dist/nodes/addPairToJSMap.js"(exports) {
    "use strict";
    var log = require_log();
    var merge = require_merge();
    var stringify = require_stringify();
    var identity = require_identity();
    var toJS = require_toJS();
    function addPairToJSMap(ctx, map, { key, value }) {
      if (identity.isNode(key) && key.addToJSMap)
        key.addToJSMap(ctx, map, value);
      else if (merge.isMergeKey(ctx, key))
        merge.addMergeToJSMap(ctx, map, value);
      else {
        const jsKey = toJS.toJS(key, "", ctx);
        if (map instanceof Map) {
          map.set(jsKey, toJS.toJS(value, jsKey, ctx));
        } else if (map instanceof Set) {
          map.add(jsKey);
        } else {
          const stringKey = stringifyKey(key, jsKey, ctx);
          const jsValue = toJS.toJS(value, stringKey, ctx);
          if (stringKey in map)
            Object.defineProperty(map, stringKey, {
              value: jsValue,
              writable: true,
              enumerable: true,
              configurable: true
            });
          else
            map[stringKey] = jsValue;
        }
      }
      return map;
    }
    function stringifyKey(key, jsKey, ctx) {
      if (jsKey === null)
        return "";
      if (typeof jsKey !== "object")
        return String(jsKey);
      if (identity.isNode(key) && ctx?.doc) {
        const strCtx = stringify.createStringifyContext(ctx.doc, {});
        strCtx.anchors = /* @__PURE__ */ new Set();
        for (const node of ctx.anchors.keys())
          strCtx.anchors.add(node.anchor);
        strCtx.inFlow = true;
        strCtx.inStringifyKey = true;
        const strKey = key.toString(strCtx);
        if (!ctx.mapKeyWarned) {
          let jsonStr = JSON.stringify(strKey);
          if (jsonStr.length > 40)
            jsonStr = jsonStr.substring(0, 36) + '..."';
          log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
          ctx.mapKeyWarned = true;
        }
        return strKey;
      }
      return JSON.stringify(jsKey);
    }
    exports.addPairToJSMap = addPairToJSMap;
  }
});

// node_modules/yaml/dist/nodes/Pair.js
var require_Pair = __commonJS({
  "node_modules/yaml/dist/nodes/Pair.js"(exports) {
    "use strict";
    var createNode = require_createNode();
    var stringifyPair = require_stringifyPair();
    var addPairToJSMap = require_addPairToJSMap();
    var identity = require_identity();
    function createPair(key, value, ctx) {
      const k = createNode.createNode(key, void 0, ctx);
      const v = createNode.createNode(value, void 0, ctx);
      return new Pair(k, v);
    }
    var Pair = class _Pair {
      constructor(key, value = null) {
        Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });
        this.key = key;
        this.value = value;
      }
      clone(schema) {
        let { key, value } = this;
        if (identity.isNode(key))
          key = key.clone(schema);
        if (identity.isNode(value))
          value = value.clone(schema);
        return new _Pair(key, value);
      }
      toJSON(_, ctx) {
        const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
        return addPairToJSMap.addPairToJSMap(ctx, pair, this);
      }
      toString(ctx, onComment, onChompKeep) {
        return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this);
      }
    };
    exports.Pair = Pair;
    exports.createPair = createPair;
  }
});

// node_modules/yaml/dist/stringify/stringifyCollection.js
var require_stringifyCollection = __commonJS({
  "node_modules/yaml/dist/stringify/stringifyCollection.js"(exports) {
    "use strict";
    var identity = require_identity();
    var stringify = require_stringify();
    var stringifyComment = require_stringifyComment();
    function stringifyCollection(collection, ctx, options) {
      const flow = ctx.inFlow ?? collection.flow;
      const stringify2 = flow ? stringifyFlowCollection : stringifyBlockCollection;
      return stringify2(collection, ctx, options);
    }
    function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
      const { indent, options: { commentString } } = ctx;
      const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
      let chompKeep = false;
      const lines = [];
      for (let i = 0; i < items.length; ++i) {
        const item = items[i];
        let comment2 = null;
        if (identity.isNode(item)) {
          if (!chompKeep && item.spaceBefore)
            lines.push("");
          addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
          if (item.comment)
            comment2 = item.comment;
        } else if (identity.isPair(item)) {
          const ik = identity.isNode(item.key) ? item.key : null;
          if (ik) {
            if (!chompKeep && ik.spaceBefore)
              lines.push("");
            addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
          }
        }
        chompKeep = false;
        let str2 = stringify.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true);
        if (comment2)
          str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment2));
        if (chompKeep && comment2)
          chompKeep = false;
        lines.push(blockItemPrefix + str2);
      }
      let str;
      if (lines.length === 0) {
        str = flowChars.start + flowChars.end;
      } else {
        str = lines[0];
        for (let i = 1; i < lines.length; ++i) {
          const line = lines[i];
          str += line ? `
${indent}${line}` : "\n";
        }
      }
      if (comment) {
        str += "\n" + stringifyComment.indentComment(commentString(comment), indent);
        if (onComment)
          onComment();
      } else if (chompKeep && onChompKeep)
        onChompKeep();
      return str;
    }
    function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
      const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
      itemIndent += indentStep;
      const itemCtx = Object.assign({}, ctx, {
        indent: itemIndent,
        inFlow: true,
        type: null
      });
      let reqNewline = false;
      let linesAtValue = 0;
      const lines = [];
      for (let i = 0; i < items.length; ++i) {
        const item = items[i];
        let comment = null;
        if (identity.isNode(item)) {
          if (item.spaceBefore)
            lines.push("");
          addCommentBefore(ctx, lines, item.commentBefore, false);
          if (item.comment)
            comment = item.comment;
        } else if (identity.isPair(item)) {
          const ik = identity.isNode(item.key) ? item.key : null;
          if (ik) {
            if (ik.spaceBefore)
              lines.push("");
            addCommentBefore(ctx, lines, ik.commentBefore, false);
            if (ik.comment)
              reqNewline = true;
          }
          const iv = identity.isNode(item.value) ? item.value : null;
          if (iv) {
            if (iv.comment)
              comment = iv.comment;
            if (iv.commentBefore)
              reqNewline = true;
          } else if (item.value == null && ik?.comment) {
            comment = ik.comment;
          }
        }
        if (comment)
          reqNewline = true;
        let str = stringify.stringify(item, itemCtx, () => comment = null);
        reqNewline || (reqNewline = lines.length > linesAtValue || str.includes("\n"));
        if (i < items.length - 1) {
          str += ",";
        } else if (ctx.options.trailingComma) {
          if (ctx.options.lineWidth > 0) {
            reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) + (str.length + 2) > ctx.options.lineWidth);
          }
          if (reqNewline) {
            str += ",";
          }
        }
        if (comment)
          str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
        lines.push(str);
        linesAtValue = lines.length;
      }
      const { start, end } = flowChars;
      if (lines.length === 0) {
        return start + end;
      } else {
        if (!reqNewline) {
          const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
          reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
        }
        if (reqNewline) {
          let str = start;
          for (const line of lines)
            str += line ? `
${indentStep}${indent}${line}` : "\n";
          return `${str}
${indent}${end}`;
        } else {
          return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`;
        }
      }
    }
    function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
      if (comment && chompKeep)
        comment = comment.replace(/^\n+/, "");
      if (comment) {
        const ic = stringifyComment.indentComment(commentString(comment), indent);
        lines.push(ic.trimStart());
      }
    }
    exports.stringifyCollection = stringifyCollection;
  }
});

// node_modules/yaml/dist/nodes/YAMLMap.js
var require_YAMLMap = __commonJS({
  "node_modules/yaml/dist/nodes/YAMLMap.js"(exports) {
    "use strict";
    var stringifyCollection = require_stringifyCollection();
    var addPairToJSMap = require_addPairToJSMap();
    var Collection = require_Collection();
    var identity = require_identity();
    var Pair = require_Pair();
    var Scalar = require_Scalar();
    function findPair(items, key) {
      const k = identity.isScalar(key) ? key.value : key;
      for (const it of items) {
        if (identity.isPair(it)) {
          if (it.key === key || it.key === k)
            return it;
          if (identity.isScalar(it.key) && it.key.value === k)
            return it;
        }
      }
      return void 0;
    }
    var YAMLMap = class extends Collection.Collection {
      static get tagName() {
        return "tag:yaml.org,2002:map";
      }
      constructor(schema) {
        super(identity.MAP, schema);
        this.items = [];
      }
      /**
       * A generic collection parsing method that can be extended
       * to other node classes that inherit from YAMLMap
       */
      static from(schema, obj, ctx) {
        const { keepUndefined, replacer } = ctx;
        const map = new this(schema);
        const add = (key, value) => {
          if (typeof replacer === "function")
            value = replacer.call(obj, key, value);
          else if (Array.isArray(replacer) && !replacer.includes(key))
            return;
          if (value !== void 0 || keepUndefined)
            map.items.push(Pair.createPair(key, value, ctx));
        };
        if (obj instanceof Map) {
          for (const [key, value] of obj)
            add(key, value);
        } else if (obj && typeof obj === "object") {
          for (const key of Object.keys(obj))
            add(key, obj[key]);
        }
        if (typeof schema.sortMapEntries === "function") {
          map.items.sort(schema.sortMapEntries);
        }
        return map;
      }
      /**
       * Adds a value to the collection.
       *
       * @param overwrite - If not set `true`, using a key that is already in the
       *   collection will throw. Otherwise, overwrites the previous value.
       */
      add(pair, overwrite) {
        let _pair;
        if (identity.isPair(pair))
          _pair = pair;
        else if (!pair || typeof pair !== "object" || !("key" in pair)) {
          _pair = new Pair.Pair(pair, pair?.value);
        } else
          _pair = new Pair.Pair(pair.key, pair.value);
        const prev = findPair(this.items, _pair.key);
        const sortEntries = this.schema?.sortMapEntries;
        if (prev) {
          if (!overwrite)
            throw new Error(`Key ${_pair.key} already set`);
          if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
            prev.value.value = _pair.value;
          else
            prev.value = _pair.value;
        } else if (sortEntries) {
          const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0);
          if (i === -1)
            this.items.push(_pair);
          else
            this.items.splice(i, 0, _pair);
        } else {
          this.items.push(_pair);
        }
      }
      delete(key) {
        const it = findPair(this.items, key);
        if (!it)
          return false;
        const del = this.items.splice(this.items.indexOf(it), 1);
        return del.length > 0;
      }
      get(key, keepScalar) {
        const it = findPair(this.items, key);
        const node = it?.value;
        return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? void 0;
      }
      has(key) {
        return !!findPair(this.items, key);
      }
      set(key, value) {
        this.add(new Pair.Pair(key, value), true);
      }
      /**
       * @param ctx - Conversion context, originally set in Document#toJS()
       * @param {Class} Type - If set, forces the returned collection type
       * @returns Instance of Type, Map, or Object
       */
      toJSON(_, ctx, Type2) {
        const map = Type2 ? new Type2() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
        if (ctx?.onCreate)
          ctx.onCreate(map);
        for (const item of this.items)
          addPairToJSMap.addPairToJSMap(ctx, map, item);
        return map;
      }
      toString(ctx, onComment, onChompKeep) {
        if (!ctx)
          return JSON.stringify(this);
        for (const item of this.items) {
          if (!identity.isPair(item))
            throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
        }
        if (!ctx.allNullValues && this.hasAllNullValues(false))
          ctx = Object.assign({}, ctx, { allNullValues: true });
        return stringifyCollection.stringifyCollection(this, ctx, {
          blockItemPrefix: "",
          flowChars: { start: "{", end: "}" },
          itemIndent: ctx.indent || "",
          onChompKeep,
          onComment
        });
      }
    };
    exports.YAMLMap = YAMLMap;
    exports.findPair = findPair;
  }
});

// node_modules/yaml/dist/schema/common/map.js
var require_map = __commonJS({
  "node_modules/yaml/dist/schema/common/map.js"(exports) {
    "use strict";
    var identity = require_identity();
    var YAMLMap = require_YAMLMap();
    var map = {
      collection: "map",
      default: true,
      nodeClass: YAMLMap.YAMLMap,
      tag: "tag:yaml.org,2002:map",
      resolve(map2, onError) {
        if (!identity.isMap(map2))
          onError("Expected a mapping for this tag");
        return map2;
      },
      createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)
    };
    exports.map = map;
  }
});

// node_modules/yaml/dist/nodes/YAMLSeq.js
var require_YAMLSeq = __commonJS({
  "node_modules/yaml/dist/nodes/YAMLSeq.js"(exports) {
    "use strict";
    var createNode = require_createNode();
    var stringifyCollection = require_stringifyCollection();
    var Collection = require_Collection();
    var identity = require_identity();
    var Scalar = require_Scalar();
    var toJS = require_toJS();
    var YAMLSeq = class extends Collection.Collection {
      static get tagName() {
        return "tag:yaml.org,2002:seq";
      }
      constructor(schema) {
        super(identity.SEQ, schema);
        this.items = [];
      }
      add(value) {
        this.items.push(value);
      }
      /**
       * Removes a value from the collection.
       *
       * `key` must contain a representation of an integer for this to succeed.
       * It may be wrapped in a `Scalar`.
       *
       * @returns `true` if the item was found and removed.
       */
      delete(key) {
        const idx = asItemIndex(key);
        if (typeof idx !== "number")
          return false;
        const del = this.items.splice(idx, 1);
        return del.length > 0;
      }
      get(key, keepScalar) {
        const idx = asItemIndex(key);
        if (typeof idx !== "number")
          return void 0;
        const it = this.items[idx];
        return !keepScalar && identity.isScalar(it) ? it.value : it;
      }
      /**
       * Checks if the collection includes a value with the key `key`.
       *
       * `key` must contain a representation of an integer for this to succeed.
       * It may be wrapped in a `Scalar`.
       */
      has(key) {
        const idx = asItemIndex(key);
        return typeof idx === "number" && idx < this.items.length;
      }
      /**
       * Sets a value in this collection. For `!!set`, `value` needs to be a
       * boolean to add/remove the item from the set.
       *
       * If `key` does not contain a representation of an integer, this will throw.
       * It may be wrapped in a `Scalar`.
       */
      set(key, value) {
        const idx = asItemIndex(key);
        if (typeof idx !== "number")
          throw new Error(`Expected a valid index, not ${key}.`);
        const prev = this.items[idx];
        if (identity.isScalar(prev) && Scalar.isScalarValue(value))
          prev.value = value;
        else
          this.items[idx] = value;
      }
      toJSON(_, ctx) {
        const seq = [];
        if (ctx?.onCreate)
          ctx.onCreate(seq);
        let i = 0;
        for (const item of this.items)
          seq.push(toJS.toJS(item, String(i++), ctx));
        return seq;
      }
      toString(ctx, onComment, onChompKeep) {
        if (!ctx)
          return JSON.stringify(this);
        return stringifyCollection.stringifyCollection(this, ctx, {
          blockItemPrefix: "- ",
          flowChars: { start: "[", end: "]" },
          itemIndent: (ctx.indent || "") + "  ",
          onChompKeep,
          onComment
        });
      }
      static from(schema, obj, ctx) {
        const { replacer } = ctx;
        const seq = new this(schema);
        if (obj && Symbol.iterator in Object(obj)) {
          let i = 0;
          for (let it of obj) {
            if (typeof replacer === "function") {
              const key = obj instanceof Set ? it : String(i++);
              it = replacer.call(obj, key, it);
            }
            seq.items.push(createNode.createNode(it, void 0, ctx));
          }
        }
        return seq;
      }
    };
    function asItemIndex(key) {
      let idx = identity.isScalar(key) ? key.value : key;
      if (idx && typeof idx === "string")
        idx = Number(idx);
      return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
    }
    exports.YAMLSeq = YAMLSeq;
  }
});

// node_modules/yaml/dist/schema/common/seq.js
var require_seq = __commonJS({
  "node_modules/yaml/dist/schema/common/seq.js"(exports) {
    "use strict";
    var identity = require_identity();
    var YAMLSeq = require_YAMLSeq();
    var seq = {
      collection: "seq",
      default: true,
      nodeClass: YAMLSeq.YAMLSeq,
      tag: "tag:yaml.org,2002:seq",
      resolve(seq2, onError) {
        if (!identity.isSeq(seq2))
          onError("Expected a sequence for this tag");
        return seq2;
      },
      createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)
    };
    exports.seq = seq;
  }
});

// node_modules/yaml/dist/schema/common/string.js
var require_string = __commonJS({
  "node_modules/yaml/dist/schema/common/string.js"(exports) {
    "use strict";
    var stringifyString = require_stringifyString();
    var string = {
      identify: (value) => typeof value === "string",
      default: true,
      tag: "tag:yaml.org,2002:str",
      resolve: (str) => str,
      stringify(item, ctx, onComment, onChompKeep) {
        ctx = Object.assign({ actualString: true }, ctx);
        return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);
      }
    };
    exports.string = string;
  }
});

// node_modules/yaml/dist/schema/common/null.js
var require_null = __commonJS({
  "node_modules/yaml/dist/schema/common/null.js"(exports) {
    "use strict";
    var Scalar = require_Scalar();
    var nullTag = {
      identify: (value) => value == null,
      createNode: () => new Scalar.Scalar(null),
      default: true,
      tag: "tag:yaml.org,2002:null",
      test: /^(?:~|[Nn]ull|NULL)?$/,
      resolve: () => new Scalar.Scalar(null),
      stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr
    };
    exports.nullTag = nullTag;
  }
});

// node_modules/yaml/dist/schema/core/bool.js
var require_bool = __commonJS({
  "node_modules/yaml/dist/schema/core/bool.js"(exports) {
    "use strict";
    var Scalar = require_Scalar();
    var boolTag = {
      identify: (value) => typeof value === "boolean",
      default: true,
      tag: "tag:yaml.org,2002:bool",
      test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
      resolve: (str) => new Scalar.Scalar(str[0] === "t" || str[0] === "T"),
      stringify({ source, value }, ctx) {
        if (source && boolTag.test.test(source)) {
          const sv = source[0] === "t" || source[0] === "T";
          if (value === sv)
            return source;
        }
        return value ? ctx.options.trueStr : ctx.options.falseStr;
      }
    };
    exports.boolTag = boolTag;
  }
});

// node_modules/yaml/dist/stringify/stringifyNumber.js
var require_stringifyNumber = __commonJS({
  "node_modules/yaml/dist/stringify/stringifyNumber.js"(exports) {
    "use strict";
    function stringifyNumber({ format, minFractionDigits, tag, value }) {
      if (typeof value === "bigint")
        return String(value);
      const num = typeof value === "number" ? value : Number(value);
      if (!isFinite(num))
        return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf";
      let n = Object.is(value, -0) ? "-0" : JSON.stringify(value);
      if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^\d/.test(n)) {
        let i = n.indexOf(".");
        if (i < 0) {
          i = n.length;
          n += ".";
        }
        let d = minFractionDigits - (n.length - i - 1);
        while (d-- > 0)
          n += "0";
      }
      return n;
    }
    exports.stringifyNumber = stringifyNumber;
  }
});

// node_modules/yaml/dist/schema/core/float.js
var require_float = __commonJS({
  "node_modules/yaml/dist/schema/core/float.js"(exports) {
    "use strict";
    var Scalar = require_Scalar();
    var stringifyNumber = require_stringifyNumber();
    var floatNaN = {
      identify: (value) => typeof value === "number",
      default: true,
      tag: "tag:yaml.org,2002:float",
      test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
      resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
      stringify: stringifyNumber.stringifyNumber
    };
    var floatExp = {
      identify: (value) => typeof value === "number",
      default: true,
      tag: "tag:yaml.org,2002:float",
      format: "EXP",
      test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
      resolve: (str) => parseFloat(str),
      stringify(node) {
        const num = Number(node.value);
        return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
      }
    };
    var float = {
      identify: (value) => typeof value === "number",
      default: true,
      tag: "tag:yaml.org,2002:float",
      test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
      resolve(str) {
        const node = new Scalar.Scalar(parseFloat(str));
        const dot = str.indexOf(".");
        if (dot !== -1 && str[str.length - 1] === "0")
          node.minFractionDigits = str.length - dot - 1;
        return node;
      },
      stringify: stringifyNumber.stringifyNumber
    };
    exports.float = float;
    exports.floatExp = floatExp;
    exports.floatNaN = floatNaN;
  }
});

// node_modules/yaml/dist/schema/core/int.js
var require_int = __commonJS({
  "node_modules/yaml/dist/schema/core/int.js"(exports) {
    "use strict";
    var stringifyNumber = require_stringifyNumber();
    var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
    var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix);
    function intStringify(node, radix, prefix) {
      const { value } = node;
      if (intIdentify(value) && value >= 0)
        return prefix + value.toString(radix);
      return stringifyNumber.stringifyNumber(node);
    }
    var intOct = {
      identify: (value) => intIdentify(value) && value >= 0,
      default: true,
      tag: "tag:yaml.org,2002:int",
      format: "OCT",
      test: /^0o[0-7]+$/,
      resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),
      stringify: (node) => intStringify(node, 8, "0o")
    };
    var int = {
      identify: intIdentify,
      default: true,
      tag: "tag:yaml.org,2002:int",
      test: /^[-+]?[0-9]+$/,
      resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
      stringify: stringifyNumber.stringifyNumber
    };
    var intHex = {
      identify: (value) => intIdentify(value) && value >= 0,
      default: true,
      tag: "tag:yaml.org,2002:int",
      format: "HEX",
      test: /^0x[0-9a-fA-F]+$/,
      resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
      stringify: (node) => intStringify(node, 16, "0x")
    };
    exports.int = int;
    exports.intHex = intHex;
    exports.intOct = intOct;
  }
});

// node_modules/yaml/dist/schema/core/schema.js
var require_schema = __commonJS({
  "node_modules/yaml/dist/schema/core/schema.js"(exports) {
    "use strict";
    var map = require_map();
    var _null = require_null();
    var seq = require_seq();
    var string = require_string();
    var bool = require_bool();
    var float = require_float();
    var int = require_int();
    var schema = [
      map.map,
      seq.seq,
      string.string,
      _null.nullTag,
      bool.boolTag,
      int.intOct,
      int.int,
      int.intHex,
      float.floatNaN,
      float.floatExp,
      float.float
    ];
    exports.schema = schema;
  }
});

// node_modules/yaml/dist/schema/json/schema.js
var require_schema2 = __commonJS({
  "node_modules/yaml/dist/schema/json/schema.js"(exports) {
    "use strict";
    var Scalar = require_Scalar();
    var map = require_map();
    var seq = require_seq();
    function intIdentify(value) {
      return typeof value === "bigint" || Number.isInteger(value);
    }
    var stringifyJSON = ({ value }) => JSON.stringify(value);
    var jsonScalars = [
      {
        identify: (value) => typeof value === "string",
        default: true,
        tag: "tag:yaml.org,2002:str",
        resolve: (str) => str,
        stringify: stringifyJSON
      },
      {
        identify: (value) => value == null,
        createNode: () => new Scalar.Scalar(null),
        default: true,
        tag: "tag:yaml.org,2002:null",
        test: /^null$/,
        resolve: () => null,
        stringify: stringifyJSON
      },
      {
        identify: (value) => typeof value === "boolean",
        default: true,
        tag: "tag:yaml.org,2002:bool",
        test: /^true$|^false$/,
        resolve: (str) => str === "true",
        stringify: stringifyJSON
      },
      {
        identify: intIdentify,
        default: true,
        tag: "tag:yaml.org,2002:int",
        test: /^-?(?:0|[1-9][0-9]*)$/,
        resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
        stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
      },
      {
        identify: (value) => typeof value === "number",
        default: true,
        tag: "tag:yaml.org,2002:float",
        test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
        resolve: (str) => parseFloat(str),
        stringify: stringifyJSON
      }
    ];
    var jsonError2 = {
      default: true,
      tag: "",
      test: /^/,
      resolve(str, onError) {
        onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
        return str;
      }
    };
    var schema = [map.map, seq.seq].concat(jsonScalars, jsonError2);
    exports.schema = schema;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/binary.js
var require_binary = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/binary.js"(exports) {
    "use strict";
    var node_buffer = __require("buffer");
    var Scalar = require_Scalar();
    var stringifyString = require_stringifyString();
    var binary = {
      identify: (value) => value instanceof Uint8Array,
      // Buffer inherits from Uint8Array
      default: false,
      tag: "tag:yaml.org,2002:binary",
      /**
       * Returns a Buffer in node and an Uint8Array in browsers
       *
       * To use the resulting buffer as an image, you'll want to do something like:
       *
       *   const blob = new Blob([buffer], { type: 'image/jpeg' })
       *   document.querySelector('#photo').src = URL.createObjectURL(blob)
       */
      resolve(src, onError) {
        if (typeof node_buffer.Buffer === "function") {
          return node_buffer.Buffer.from(src, "base64");
        } else if (typeof atob === "function") {
          const str = atob(src.replace(/[\n\r]/g, ""));
          const buffer = new Uint8Array(str.length);
          for (let i = 0; i < str.length; ++i)
            buffer[i] = str.charCodeAt(i);
          return buffer;
        } else {
          onError("This environment does not support reading binary tags; either Buffer or atob is required");
          return src;
        }
      },
      stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
        if (!value)
          return "";
        const buf = value;
        let str;
        if (typeof node_buffer.Buffer === "function") {
          str = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64");
        } else if (typeof btoa === "function") {
          let s = "";
          for (let i = 0; i < buf.length; ++i)
            s += String.fromCharCode(buf[i]);
          str = btoa(s);
        } else {
          throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");
        }
        type ?? (type = Scalar.Scalar.BLOCK_LITERAL);
        if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
          const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
          const n = Math.ceil(str.length / lineWidth);
          const lines = new Array(n);
          for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
            lines[i] = str.substr(o, lineWidth);
          }
          str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? "\n" : " ");
        }
        return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
      }
    };
    exports.binary = binary;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/pairs.js
var require_pairs = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/pairs.js"(exports) {
    "use strict";
    var identity = require_identity();
    var Pair = require_Pair();
    var Scalar = require_Scalar();
    var YAMLSeq = require_YAMLSeq();
    function resolvePairs(seq, onError) {
      if (identity.isSeq(seq)) {
        for (let i = 0; i < seq.items.length; ++i) {
          let item = seq.items[i];
          if (identity.isPair(item))
            continue;
          else if (identity.isMap(item)) {
            if (item.items.length > 1)
              onError("Each pair must have its own sequence indicator");
            const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));
            if (item.commentBefore)
              pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore}
${pair.key.commentBefore}` : item.commentBefore;
            if (item.comment) {
              const cn = pair.value ?? pair.key;
              cn.comment = cn.comment ? `${item.comment}
${cn.comment}` : item.comment;
            }
            item = pair;
          }
          seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item);
        }
      } else
        onError("Expected a sequence for this tag");
      return seq;
    }
    function createPairs(schema, iterable, ctx) {
      const { replacer } = ctx;
      const pairs2 = new YAMLSeq.YAMLSeq(schema);
      pairs2.tag = "tag:yaml.org,2002:pairs";
      let i = 0;
      if (iterable && Symbol.iterator in Object(iterable))
        for (let it of iterable) {
          if (typeof replacer === "function")
            it = replacer.call(iterable, String(i++), it);
          let key, value;
          if (Array.isArray(it)) {
            if (it.length === 2) {
              key = it[0];
              value = it[1];
            } else
              throw new TypeError(`Expected [key, value] tuple: ${it}`);
          } else if (it && it instanceof Object) {
            const keys = Object.keys(it);
            if (keys.length === 1) {
              key = keys[0];
              value = it[key];
            } else {
              throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
            }
          } else {
            key = it;
          }
          pairs2.items.push(Pair.createPair(key, value, ctx));
        }
      return pairs2;
    }
    var pairs = {
      collection: "seq",
      default: false,
      tag: "tag:yaml.org,2002:pairs",
      resolve: resolvePairs,
      createNode: createPairs
    };
    exports.createPairs = createPairs;
    exports.pairs = pairs;
    exports.resolvePairs = resolvePairs;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/omap.js
var require_omap = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/omap.js"(exports) {
    "use strict";
    var identity = require_identity();
    var toJS = require_toJS();
    var YAMLMap = require_YAMLMap();
    var YAMLSeq = require_YAMLSeq();
    var pairs = require_pairs();
    var YAMLOMap = class _YAMLOMap extends YAMLSeq.YAMLSeq {
      constructor() {
        super();
        this.add = YAMLMap.YAMLMap.prototype.add.bind(this);
        this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);
        this.get = YAMLMap.YAMLMap.prototype.get.bind(this);
        this.has = YAMLMap.YAMLMap.prototype.has.bind(this);
        this.set = YAMLMap.YAMLMap.prototype.set.bind(this);
        this.tag = _YAMLOMap.tag;
      }
      /**
       * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,
       * but TypeScript won't allow widening the signature of a child method.
       */
      toJSON(_, ctx) {
        if (!ctx)
          return super.toJSON(_);
        const map = /* @__PURE__ */ new Map();
        if (ctx?.onCreate)
          ctx.onCreate(map);
        for (const pair of this.items) {
          let key, value;
          if (identity.isPair(pair)) {
            key = toJS.toJS(pair.key, "", ctx);
            value = toJS.toJS(pair.value, key, ctx);
          } else {
            key = toJS.toJS(pair, "", ctx);
          }
          if (map.has(key))
            throw new Error("Ordered maps must not include duplicate keys");
          map.set(key, value);
        }
        return map;
      }
      static from(schema, iterable, ctx) {
        const pairs$1 = pairs.createPairs(schema, iterable, ctx);
        const omap2 = new this();
        omap2.items = pairs$1.items;
        return omap2;
      }
    };
    YAMLOMap.tag = "tag:yaml.org,2002:omap";
    var omap = {
      collection: "seq",
      identify: (value) => value instanceof Map,
      nodeClass: YAMLOMap,
      default: false,
      tag: "tag:yaml.org,2002:omap",
      resolve(seq, onError) {
        const pairs$1 = pairs.resolvePairs(seq, onError);
        const seenKeys = [];
        for (const { key } of pairs$1.items) {
          if (identity.isScalar(key)) {
            if (seenKeys.includes(key.value)) {
              onError(`Ordered maps must not include duplicate keys: ${key.value}`);
            } else {
              seenKeys.push(key.value);
            }
          }
        }
        return Object.assign(new YAMLOMap(), pairs$1);
      },
      createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)
    };
    exports.YAMLOMap = YAMLOMap;
    exports.omap = omap;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/bool.js
var require_bool2 = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/bool.js"(exports) {
    "use strict";
    var Scalar = require_Scalar();
    function boolStringify({ value, source }, ctx) {
      const boolObj = value ? trueTag : falseTag;
      if (source && boolObj.test.test(source))
        return source;
      return value ? ctx.options.trueStr : ctx.options.falseStr;
    }
    var trueTag = {
      identify: (value) => value === true,
      default: true,
      tag: "tag:yaml.org,2002:bool",
      test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
      resolve: () => new Scalar.Scalar(true),
      stringify: boolStringify
    };
    var falseTag = {
      identify: (value) => value === false,
      default: true,
      tag: "tag:yaml.org,2002:bool",
      test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
      resolve: () => new Scalar.Scalar(false),
      stringify: boolStringify
    };
    exports.falseTag = falseTag;
    exports.trueTag = trueTag;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/float.js
var require_float2 = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/float.js"(exports) {
    "use strict";
    var Scalar = require_Scalar();
    var stringifyNumber = require_stringifyNumber();
    var floatNaN = {
      identify: (value) => typeof value === "number",
      default: true,
      tag: "tag:yaml.org,2002:float",
      test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
      resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
      stringify: stringifyNumber.stringifyNumber
    };
    var floatExp = {
      identify: (value) => typeof value === "number",
      default: true,
      tag: "tag:yaml.org,2002:float",
      format: "EXP",
      test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
      resolve: (str) => parseFloat(str.replace(/_/g, "")),
      stringify(node) {
        const num = Number(node.value);
        return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
      }
    };
    var float = {
      identify: (value) => typeof value === "number",
      default: true,
      tag: "tag:yaml.org,2002:float",
      test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
      resolve(str) {
        const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, "")));
        const dot = str.indexOf(".");
        if (dot !== -1) {
          const f = str.substring(dot + 1).replace(/_/g, "");
          if (f[f.length - 1] === "0")
            node.minFractionDigits = f.length;
        }
        return node;
      },
      stringify: stringifyNumber.stringifyNumber
    };
    exports.float = float;
    exports.floatExp = floatExp;
    exports.floatNaN = floatNaN;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/int.js
var require_int2 = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/int.js"(exports) {
    "use strict";
    var stringifyNumber = require_stringifyNumber();
    var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
    function intResolve(str, offset, radix, { intAsBigInt }) {
      const sign = str[0];
      if (sign === "-" || sign === "+")
        offset += 1;
      str = str.substring(offset).replace(/_/g, "");
      if (intAsBigInt) {
        switch (radix) {
          case 2:
            str = `0b${str}`;
            break;
          case 8:
            str = `0o${str}`;
            break;
          case 16:
            str = `0x${str}`;
            break;
        }
        const n2 = BigInt(str);
        return sign === "-" ? BigInt(-1) * n2 : n2;
      }
      const n = parseInt(str, radix);
      return sign === "-" ? -1 * n : n;
    }
    function intStringify(node, radix, prefix) {
      const { value } = node;
      if (intIdentify(value)) {
        const str = value.toString(radix);
        return value < 0 ? "-" + prefix + str.substr(1) : prefix + str;
      }
      return stringifyNumber.stringifyNumber(node);
    }
    var intBin = {
      identify: intIdentify,
      default: true,
      tag: "tag:yaml.org,2002:int",
      format: "BIN",
      test: /^[-+]?0b[0-1_]+$/,
      resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
      stringify: (node) => intStringify(node, 2, "0b")
    };
    var intOct = {
      identify: intIdentify,
      default: true,
      tag: "tag:yaml.org,2002:int",
      format: "OCT",
      test: /^[-+]?0[0-7_]+$/,
      resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
      stringify: (node) => intStringify(node, 8, "0")
    };
    var int = {
      identify: intIdentify,
      default: true,
      tag: "tag:yaml.org,2002:int",
      test: /^[-+]?[0-9][0-9_]*$/,
      resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
      stringify: stringifyNumber.stringifyNumber
    };
    var intHex = {
      identify: intIdentify,
      default: true,
      tag: "tag:yaml.org,2002:int",
      format: "HEX",
      test: /^[-+]?0x[0-9a-fA-F_]+$/,
      resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
      stringify: (node) => intStringify(node, 16, "0x")
    };
    exports.int = int;
    exports.intBin = intBin;
    exports.intHex = intHex;
    exports.intOct = intOct;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/set.js
var require_set = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/set.js"(exports) {
    "use strict";
    var identity = require_identity();
    var Pair = require_Pair();
    var YAMLMap = require_YAMLMap();
    var YAMLSet = class _YAMLSet extends YAMLMap.YAMLMap {
      constructor(schema) {
        super(schema);
        this.tag = _YAMLSet.tag;
      }
      add(key) {
        let pair;
        if (identity.isPair(key))
          pair = key;
        else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null)
          pair = new Pair.Pair(key.key, null);
        else
          pair = new Pair.Pair(key, null);
        const prev = YAMLMap.findPair(this.items, pair.key);
        if (!prev)
          this.items.push(pair);
      }
      /**
       * If `keepPair` is `true`, returns the Pair matching `key`.
       * Otherwise, returns the value of that Pair's key.
       */
      get(key, keepPair) {
        const pair = YAMLMap.findPair(this.items, key);
        return !keepPair && identity.isPair(pair) ? identity.isScalar(pair.key) ? pair.key.value : pair.key : pair;
      }
      set(key, value) {
        if (typeof value !== "boolean")
          throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
        const prev = YAMLMap.findPair(this.items, key);
        if (prev && !value) {
          this.items.splice(this.items.indexOf(prev), 1);
        } else if (!prev && value) {
          this.items.push(new Pair.Pair(key));
        }
      }
      toJSON(_, ctx) {
        return super.toJSON(_, ctx, Set);
      }
      toString(ctx, onComment, onChompKeep) {
        if (!ctx)
          return JSON.stringify(this);
        if (this.hasAllNullValues(true))
          return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
        else
          throw new Error("Set items must all have null values");
      }
      static from(schema, iterable, ctx) {
        const { replacer } = ctx;
        const set2 = new this(schema);
        if (iterable && Symbol.iterator in Object(iterable))
          for (let value of iterable) {
            if (typeof replacer === "function")
              value = replacer.call(iterable, value, value);
            set2.items.push(Pair.createPair(value, null, ctx));
          }
        return set2;
      }
    };
    YAMLSet.tag = "tag:yaml.org,2002:set";
    var set = {
      collection: "map",
      identify: (value) => value instanceof Set,
      nodeClass: YAMLSet,
      default: false,
      tag: "tag:yaml.org,2002:set",
      createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),
      resolve(map, onError) {
        if (identity.isMap(map)) {
          if (map.hasAllNullValues(true))
            return Object.assign(new YAMLSet(), map);
          else
            onError("Set items must all have null values");
        } else
          onError("Expected a mapping for this tag");
        return map;
      }
    };
    exports.YAMLSet = YAMLSet;
    exports.set = set;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/timestamp.js
var require_timestamp = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/timestamp.js"(exports) {
    "use strict";
    var stringifyNumber = require_stringifyNumber();
    function parseSexagesimal(str, asBigInt) {
      const sign = str[0];
      const parts = sign === "-" || sign === "+" ? str.substring(1) : str;
      const num = (n) => asBigInt ? BigInt(n) : Number(n);
      const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0));
      return sign === "-" ? num(-1) * res : res;
    }
    function stringifySexagesimal(node) {
      let { value } = node;
      let num = (n) => n;
      if (typeof value === "bigint")
        num = (n) => BigInt(n);
      else if (isNaN(value) || !isFinite(value))
        return stringifyNumber.stringifyNumber(node);
      let sign = "";
      if (value < 0) {
        sign = "-";
        value *= num(-1);
      }
      const _60 = num(60);
      const parts = [value % _60];
      if (value < 60) {
        parts.unshift(0);
      } else {
        value = (value - parts[0]) / _60;
        parts.unshift(value % _60);
        if (value >= 60) {
          value = (value - parts[0]) / _60;
          parts.unshift(value);
        }
      }
      return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, "");
    }
    var intTime = {
      identify: (value) => typeof value === "bigint" || Number.isInteger(value),
      default: true,
      tag: "tag:yaml.org,2002:int",
      format: "TIME",
      test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
      resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
      stringify: stringifySexagesimal
    };
    var floatTime = {
      identify: (value) => typeof value === "number",
      default: true,
      tag: "tag:yaml.org,2002:float",
      format: "TIME",
      test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
      resolve: (str) => parseSexagesimal(str, false),
      stringify: stringifySexagesimal
    };
    var timestamp = {
      identify: (value) => value instanceof Date,
      default: true,
      tag: "tag:yaml.org,2002:timestamp",
      // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
      // may be omitted altogether, resulting in a date format. In such a case, the time part is
      // assumed to be 00:00:00Z (start of day, UTC).
      test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),
      resolve(str) {
        const match = str.match(timestamp.test);
        if (!match)
          throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");
        const [, year, month, day, hour, minute, second] = match.map(Number);
        const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0;
        let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
        const tz = match[8];
        if (tz && tz !== "Z") {
          let d = parseSexagesimal(tz, false);
          if (Math.abs(d) < 30)
            d *= 60;
          date -= 6e4 * d;
        }
        return new Date(date);
      },
      stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? ""
    };
    exports.floatTime = floatTime;
    exports.intTime = intTime;
    exports.timestamp = timestamp;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/schema.js
var require_schema3 = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/schema.js"(exports) {
    "use strict";
    var map = require_map();
    var _null = require_null();
    var seq = require_seq();
    var string = require_string();
    var binary = require_binary();
    var bool = require_bool2();
    var float = require_float2();
    var int = require_int2();
    var merge = require_merge();
    var omap = require_omap();
    var pairs = require_pairs();
    var set = require_set();
    var timestamp = require_timestamp();
    var schema = [
      map.map,
      seq.seq,
      string.string,
      _null.nullTag,
      bool.trueTag,
      bool.falseTag,
      int.intBin,
      int.intOct,
      int.int,
      int.intHex,
      float.floatNaN,
      float.floatExp,
      float.float,
      binary.binary,
      merge.merge,
      omap.omap,
      pairs.pairs,
      set.set,
      timestamp.intTime,
      timestamp.floatTime,
      timestamp.timestamp
    ];
    exports.schema = schema;
  }
});

// node_modules/yaml/dist/schema/tags.js
var require_tags = __commonJS({
  "node_modules/yaml/dist/schema/tags.js"(exports) {
    "use strict";
    var map = require_map();
    var _null = require_null();
    var seq = require_seq();
    var string = require_string();
    var bool = require_bool();
    var float = require_float();
    var int = require_int();
    var schema = require_schema();
    var schema$1 = require_schema2();
    var binary = require_binary();
    var merge = require_merge();
    var omap = require_omap();
    var pairs = require_pairs();
    var schema$2 = require_schema3();
    var set = require_set();
    var timestamp = require_timestamp();
    var schemas = /* @__PURE__ */ new Map([
      ["core", schema.schema],
      ["failsafe", [map.map, seq.seq, string.string]],
      ["json", schema$1.schema],
      ["yaml11", schema$2.schema],
      ["yaml-1.1", schema$2.schema]
    ]);
    var tagsByName = {
      binary: binary.binary,
      bool: bool.boolTag,
      float: float.float,
      floatExp: float.floatExp,
      floatNaN: float.floatNaN,
      floatTime: timestamp.floatTime,
      int: int.int,
      intHex: int.intHex,
      intOct: int.intOct,
      intTime: timestamp.intTime,
      map: map.map,
      merge: merge.merge,
      null: _null.nullTag,
      omap: omap.omap,
      pairs: pairs.pairs,
      seq: seq.seq,
      set: set.set,
      timestamp: timestamp.timestamp
    };
    var coreKnownTags = {
      "tag:yaml.org,2002:binary": binary.binary,
      "tag:yaml.org,2002:merge": merge.merge,
      "tag:yaml.org,2002:omap": omap.omap,
      "tag:yaml.org,2002:pairs": pairs.pairs,
      "tag:yaml.org,2002:set": set.set,
      "tag:yaml.org,2002:timestamp": timestamp.timestamp
    };
    function getTags(customTags, schemaName, addMergeTag) {
      const schemaTags = schemas.get(schemaName);
      if (schemaTags && !customTags) {
        return addMergeTag && !schemaTags.includes(merge.merge) ? schemaTags.concat(merge.merge) : schemaTags.slice();
      }
      let tags = schemaTags;
      if (!tags) {
        if (Array.isArray(customTags))
          tags = [];
        else {
          const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", ");
          throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
        }
      }
      if (Array.isArray(customTags)) {
        for (const tag of customTags)
          tags = tags.concat(tag);
      } else if (typeof customTags === "function") {
        tags = customTags(tags.slice());
      }
      if (addMergeTag)
        tags = tags.concat(merge.merge);
      return tags.reduce((tags2, tag) => {
        const tagObj = typeof tag === "string" ? tagsByName[tag] : tag;
        if (!tagObj) {
          const tagName = JSON.stringify(tag);
          const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", ");
          throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);
        }
        if (!tags2.includes(tagObj))
          tags2.push(tagObj);
        return tags2;
      }, []);
    }
    exports.coreKnownTags = coreKnownTags;
    exports.getTags = getTags;
  }
});

// node_modules/yaml/dist/schema/Schema.js
var require_Schema = __commonJS({
  "node_modules/yaml/dist/schema/Schema.js"(exports) {
    "use strict";
    var identity = require_identity();
    var map = require_map();
    var seq = require_seq();
    var string = require_string();
    var tags = require_tags();
    var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
    var Schema = class _Schema {
      constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
        this.compat = Array.isArray(compat) ? tags.getTags(compat, "compat") : compat ? tags.getTags(null, compat) : null;
        this.name = typeof schema === "string" && schema || "core";
        this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};
        this.tags = tags.getTags(customTags, this.name, merge);
        this.toStringOptions = toStringDefaults ?? null;
        Object.defineProperty(this, identity.MAP, { value: map.map });
        Object.defineProperty(this, identity.SCALAR, { value: string.string });
        Object.defineProperty(this, identity.SEQ, { value: seq.seq });
        this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null;
      }
      clone() {
        const copy = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this));
        copy.tags = this.tags.slice();
        return copy;
      }
    };
    exports.Schema = Schema;
  }
});

// node_modules/yaml/dist/stringify/stringifyDocument.js
var require_stringifyDocument = __commonJS({
  "node_modules/yaml/dist/stringify/stringifyDocument.js"(exports) {
    "use strict";
    var identity = require_identity();
    var stringify = require_stringify();
    var stringifyComment = require_stringifyComment();
    function stringifyDocument(doc, options) {
      const lines = [];
      let hasDirectives = options.directives === true;
      if (options.directives !== false && doc.directives) {
        const dir = doc.directives.toString(doc);
        if (dir) {
          lines.push(dir);
          hasDirectives = true;
        } else if (doc.directives.docStart)
          hasDirectives = true;
      }
      if (hasDirectives)
        lines.push("---");
      const ctx = stringify.createStringifyContext(doc, options);
      const { commentString } = ctx.options;
      if (doc.commentBefore) {
        if (lines.length !== 1)
          lines.unshift("");
        const cs = commentString(doc.commentBefore);
        lines.unshift(stringifyComment.indentComment(cs, ""));
      }
      let chompKeep = false;
      let contentComment = null;
      if (doc.contents) {
        if (identity.isNode(doc.contents)) {
          if (doc.contents.spaceBefore && hasDirectives)
            lines.push("");
          if (doc.contents.commentBefore) {
            const cs = commentString(doc.contents.commentBefore);
            lines.push(stringifyComment.indentComment(cs, ""));
          }
          ctx.forceBlockIndent = !!doc.comment;
          contentComment = doc.contents.comment;
        }
        const onChompKeep = contentComment ? void 0 : () => chompKeep = true;
        let body = stringify.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep);
        if (contentComment)
          body += stringifyComment.lineComment(body, "", commentString(contentComment));
        if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") {
          lines[lines.length - 1] = `--- ${body}`;
        } else
          lines.push(body);
      } else {
        lines.push(stringify.stringify(doc.contents, ctx));
      }
      if (doc.directives?.docEnd) {
        if (doc.comment) {
          const cs = commentString(doc.comment);
          if (cs.includes("\n")) {
            lines.push("...");
            lines.push(stringifyComment.indentComment(cs, ""));
          } else {
            lines.push(`... ${cs}`);
          }
        } else {
          lines.push("...");
        }
      } else {
        let dc = doc.comment;
        if (dc && chompKeep)
          dc = dc.replace(/^\n+/, "");
        if (dc) {
          if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "")
            lines.push("");
          lines.push(stringifyComment.indentComment(commentString(dc), ""));
        }
      }
      return lines.join("\n") + "\n";
    }
    exports.stringifyDocument = stringifyDocument;
  }
});

// node_modules/yaml/dist/doc/Document.js
var require_Document = __commonJS({
  "node_modules/yaml/dist/doc/Document.js"(exports) {
    "use strict";
    var Alias = require_Alias();
    var Collection = require_Collection();
    var identity = require_identity();
    var Pair = require_Pair();
    var toJS = require_toJS();
    var Schema = require_Schema();
    var stringifyDocument = require_stringifyDocument();
    var anchors = require_anchors();
    var applyReviver = require_applyReviver();
    var createNode = require_createNode();
    var directives = require_directives();
    var Document = class _Document {
      constructor(value, replacer, options) {
        this.commentBefore = null;
        this.comment = null;
        this.errors = [];
        this.warnings = [];
        Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC });
        let _replacer = null;
        if (typeof replacer === "function" || Array.isArray(replacer)) {
          _replacer = replacer;
        } else if (options === void 0 && replacer) {
          options = replacer;
          replacer = void 0;
        }
        const opt = Object.assign({
          intAsBigInt: false,
          keepSourceTokens: false,
          logLevel: "warn",
          prettyErrors: true,
          strict: true,
          stringKeys: false,
          uniqueKeys: true,
          version: "1.2"
        }, options);
        this.options = opt;
        let { version } = opt;
        if (options?._directives) {
          this.directives = options._directives.atDocument();
          if (this.directives.yaml.explicit)
            version = this.directives.yaml.version;
        } else
          this.directives = new directives.Directives({ version });
        this.setSchema(version, options);
        this.contents = value === void 0 ? null : this.createNode(value, _replacer, options);
      }
      /**
       * Create a deep copy of this Document and its contents.
       *
       * Custom Node values that inherit from `Object` still refer to their original instances.
       */
      clone() {
        const copy = Object.create(_Document.prototype, {
          [identity.NODE_TYPE]: { value: identity.DOC }
        });
        copy.commentBefore = this.commentBefore;
        copy.comment = this.comment;
        copy.errors = this.errors.slice();
        copy.warnings = this.warnings.slice();
        copy.options = Object.assign({}, this.options);
        if (this.directives)
          copy.directives = this.directives.clone();
        copy.schema = this.schema.clone();
        copy.contents = identity.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents;
        if (this.range)
          copy.range = this.range.slice();
        return copy;
      }
      /** Adds a value to the document. */
      add(value) {
        if (assertCollection(this.contents))
          this.contents.add(value);
      }
      /** Adds a value to the document. */
      addIn(path4, value) {
        if (assertCollection(this.contents))
          this.contents.addIn(path4, value);
      }
      /**
       * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
       *
       * If `node` already has an anchor, `name` is ignored.
       * Otherwise, the `node.anchor` value will be set to `name`,
       * or if an anchor with that name is already present in the document,
       * `name` will be used as a prefix for a new unique anchor.
       * If `name` is undefined, the generated anchor will use 'a' as a prefix.
       */
      createAlias(node, name) {
        if (!node.anchor) {
          const prev = anchors.anchorNames(this);
          node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
          !name || prev.has(name) ? anchors.findNewAnchor(name || "a", prev) : name;
        }
        return new Alias.Alias(node.anchor);
      }
      createNode(value, replacer, options) {
        let _replacer = void 0;
        if (typeof replacer === "function") {
          value = replacer.call({ "": value }, "", value);
          _replacer = replacer;
        } else if (Array.isArray(replacer)) {
          const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number;
          const asStr = replacer.filter(keyToStr).map(String);
          if (asStr.length > 0)
            replacer = replacer.concat(asStr);
          _replacer = replacer;
        } else if (options === void 0 && replacer) {
          options = replacer;
          replacer = void 0;
        }
        const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
        const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(
          this,
          // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
          anchorPrefix || "a"
        );
        const ctx = {
          aliasDuplicateObjects: aliasDuplicateObjects ?? true,
          keepUndefined: keepUndefined ?? false,
          onAnchor,
          onTagObj,
          replacer: _replacer,
          schema: this.schema,
          sourceObjects
        };
        const node = createNode.createNode(value, tag, ctx);
        if (flow && identity.isCollection(node))
          node.flow = true;
        setAnchors();
        return node;
      }
      /**
       * Convert a key and a value into a `Pair` using the current schema,
       * recursively wrapping all values as `Scalar` or `Collection` nodes.
       */
      createPair(key, value, options = {}) {
        const k = this.createNode(key, null, options);
        const v = this.createNode(value, null, options);
        return new Pair.Pair(k, v);
      }
      /**
       * Removes a value from the document.
       * @returns `true` if the item was found and removed.
       */
      delete(key) {
        return assertCollection(this.contents) ? this.contents.delete(key) : false;
      }
      /**
       * Removes a value from the document.
       * @returns `true` if the item was found and removed.
       */
      deleteIn(path4) {
        if (Collection.isEmptyPath(path4)) {
          if (this.contents == null)
            return false;
          this.contents = null;
          return true;
        }
        return assertCollection(this.contents) ? this.contents.deleteIn(path4) : false;
      }
      /**
       * Returns item at `key`, or `undefined` if not found. By default unwraps
       * scalar values from their surrounding node; to disable set `keepScalar` to
       * `true` (collections are always returned intact).
       */
      get(key, keepScalar) {
        return identity.isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0;
      }
      /**
       * Returns item at `path`, or `undefined` if not found. By default unwraps
       * scalar values from their surrounding node; to disable set `keepScalar` to
       * `true` (collections are always returned intact).
       */
      getIn(path4, keepScalar) {
        if (Collection.isEmptyPath(path4))
          return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
        return identity.isCollection(this.contents) ? this.contents.getIn(path4, keepScalar) : void 0;
      }
      /**
       * Checks if the document includes a value with the key `key`.
       */
      has(key) {
        return identity.isCollection(this.contents) ? this.contents.has(key) : false;
      }
      /**
       * Checks if the document includes a value at `path`.
       */
      hasIn(path4) {
        if (Collection.isEmptyPath(path4))
          return this.contents !== void 0;
        return identity.isCollection(this.contents) ? this.contents.hasIn(path4) : false;
      }
      /**
       * Sets a value in this document. For `!!set`, `value` needs to be a
       * boolean to add/remove the item from the set.
       */
      set(key, value) {
        if (this.contents == null) {
          this.contents = Collection.collectionFromPath(this.schema, [key], value);
        } else if (assertCollection(this.contents)) {
          this.contents.set(key, value);
        }
      }
      /**
       * Sets a value in this document. For `!!set`, `value` needs to be a
       * boolean to add/remove the item from the set.
       */
      setIn(path4, value) {
        if (Collection.isEmptyPath(path4)) {
          this.contents = value;
        } else if (this.contents == null) {
          this.contents = Collection.collectionFromPath(this.schema, Array.from(path4), value);
        } else if (assertCollection(this.contents)) {
          this.contents.setIn(path4, value);
        }
      }
      /**
       * Change the YAML version and schema used by the document.
       * A `null` version disables support for directives, explicit tags, anchors, and aliases.
       * It also requires the `schema` option to be given as a `Schema` instance value.
       *
       * Overrides all previously set schema options.
       */
      setSchema(version, options = {}) {
        if (typeof version === "number")
          version = String(version);
        let opt;
        switch (version) {
          case "1.1":
            if (this.directives)
              this.directives.yaml.version = "1.1";
            else
              this.directives = new directives.Directives({ version: "1.1" });
            opt = { resolveKnownTags: false, schema: "yaml-1.1" };
            break;
          case "1.2":
          case "next":
            if (this.directives)
              this.directives.yaml.version = version;
            else
              this.directives = new directives.Directives({ version });
            opt = { resolveKnownTags: true, schema: "core" };
            break;
          case null:
            if (this.directives)
              delete this.directives;
            opt = null;
            break;
          default: {
            const sv = JSON.stringify(version);
            throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
          }
        }
        if (options.schema instanceof Object)
          this.schema = options.schema;
        else if (opt)
          this.schema = new Schema.Schema(Object.assign(opt, options));
        else
          throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
      }
      // json & jsonArg are only used from toJSON()
      toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
        const ctx = {
          anchors: /* @__PURE__ */ new Map(),
          doc: this,
          keep: !json,
          mapAsMap: mapAsMap === true,
          mapKeyWarned: false,
          maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
        };
        const res = toJS.toJS(this.contents, jsonArg ?? "", ctx);
        if (typeof onAnchor === "function")
          for (const { count, res: res2 } of ctx.anchors.values())
            onAnchor(res2, count);
        return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
      }
      /**
       * A JSON representation of the document `contents`.
       *
       * @param jsonArg Used by `JSON.stringify` to indicate the array index or
       *   property name.
       */
      toJSON(jsonArg, onAnchor) {
        return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
      }
      /** A YAML representation of the document. */
      toString(options = {}) {
        if (this.errors.length > 0)
          throw new Error("Document with errors cannot be stringified");
        if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
          const s = JSON.stringify(options.indent);
          throw new Error(`"indent" option must be a positive integer, not ${s}`);
        }
        return stringifyDocument.stringifyDocument(this, options);
      }
    };
    function assertCollection(contents) {
      if (identity.isCollection(contents))
        return true;
      throw new Error("Expected a YAML collection as document contents");
    }
    exports.Document = Document;
  }
});

// node_modules/yaml/dist/errors.js
var require_errors = __commonJS({
  "node_modules/yaml/dist/errors.js"(exports) {
    "use strict";
    var YAMLError = class extends Error {
      constructor(name, pos, code, message) {
        super();
        this.name = name;
        this.code = code;
        this.message = message;
        this.pos = pos;
      }
    };
    var YAMLParseError = class extends YAMLError {
      constructor(pos, code, message) {
        super("YAMLParseError", pos, code, message);
      }
    };
    var YAMLWarning = class extends YAMLError {
      constructor(pos, code, message) {
        super("YAMLWarning", pos, code, message);
      }
    };
    var prettifyError = (src, lc) => (error) => {
      if (error.pos[0] === -1)
        return;
      error.linePos = error.pos.map((pos) => lc.linePos(pos));
      const { line, col } = error.linePos[0];
      error.message += ` at line ${line}, column ${col}`;
      let ci = col - 1;
      let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, "");
      if (ci >= 60 && lineStr.length > 80) {
        const trimStart = Math.min(ci - 39, lineStr.length - 79);
        lineStr = "\u2026" + lineStr.substring(trimStart);
        ci -= trimStart - 1;
      }
      if (lineStr.length > 80)
        lineStr = lineStr.substring(0, 79) + "\u2026";
      if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
        let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
        if (prev.length > 80)
          prev = prev.substring(0, 79) + "\u2026\n";
        lineStr = prev + lineStr;
      }
      if (/[^ ]/.test(lineStr)) {
        let count = 1;
        const end = error.linePos[1];
        if (end?.line === line && end.col > col) {
          count = Math.max(1, Math.min(end.col - col, 80 - ci));
        }
        const pointer = " ".repeat(ci) + "^".repeat(count);
        error.message += `:

${lineStr}
${pointer}
`;
      }
    };
    exports.YAMLError = YAMLError;
    exports.YAMLParseError = YAMLParseError;
    exports.YAMLWarning = YAMLWarning;
    exports.prettifyError = prettifyError;
  }
});

// node_modules/yaml/dist/compose/resolve-props.js
var require_resolve_props = __commonJS({
  "node_modules/yaml/dist/compose/resolve-props.js"(exports) {
    "use strict";
    function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {
      let spaceBefore = false;
      let atNewline = startOnNewline;
      let hasSpace = startOnNewline;
      let comment = "";
      let commentSep = "";
      let hasNewline = false;
      let reqSpace = false;
      let tab = null;
      let anchor = null;
      let tag = null;
      let newlineAfterProp = null;
      let comma = null;
      let found = null;
      let start = null;
      for (const token of tokens) {
        if (reqSpace) {
          if (token.type !== "space" && token.type !== "newline" && token.type !== "comma")
            onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
          reqSpace = false;
        }
        if (tab) {
          if (atNewline && token.type !== "comment" && token.type !== "newline") {
            onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
          }
          tab = null;
        }
        switch (token.type) {
          case "space":
            if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes("	")) {
              tab = token;
            }
            hasSpace = true;
            break;
          case "comment": {
            if (!hasSpace)
              onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
            const cb = token.source.substring(1) || " ";
            if (!comment)
              comment = cb;
            else
              comment += commentSep + cb;
            commentSep = "";
            atNewline = false;
            break;
          }
          case "newline":
            if (atNewline) {
              if (comment)
                comment += token.source;
              else if (!found || indicator !== "seq-item-ind")
                spaceBefore = true;
            } else
              commentSep += token.source;
            atNewline = true;
            hasNewline = true;
            if (anchor || tag)
              newlineAfterProp = token;
            hasSpace = true;
            break;
          case "anchor":
            if (anchor)
              onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor");
            if (token.source.endsWith(":"))
              onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true);
            anchor = token;
            start ?? (start = token.offset);
            atNewline = false;
            hasSpace = false;
            reqSpace = true;
            break;
          case "tag": {
            if (tag)
              onError(token, "MULTIPLE_TAGS", "A node can have at most one tag");
            tag = token;
            start ?? (start = token.offset);
            atNewline = false;
            hasSpace = false;
            reqSpace = true;
            break;
          }
          case indicator:
            if (anchor || tag)
              onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`);
            if (found)
              onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`);
            found = token;
            atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind";
            hasSpace = false;
            break;
          case "comma":
            if (flow) {
              if (comma)
                onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`);
              comma = token;
              atNewline = false;
              hasSpace = false;
              break;
            }
          // else fallthrough
          default:
            onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`);
            atNewline = false;
            hasSpace = false;
        }
      }
      const last = tokens[tokens.length - 1];
      const end = last ? last.offset + last.source.length : offset;
      if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) {
        onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
      }
      if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq"))
        onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
      return {
        comma,
        found,
        spaceBefore,
        comment,
        hasNewline,
        anchor,
        tag,
        newlineAfterProp,
        end,
        start: start ?? end
      };
    }
    exports.resolveProps = resolveProps;
  }
});

// node_modules/yaml/dist/compose/util-contains-newline.js
var require_util_contains_newline = __commonJS({
  "node_modules/yaml/dist/compose/util-contains-newline.js"(exports) {
    "use strict";
    function containsNewline(key) {
      if (!key)
        return null;
      switch (key.type) {
        case "alias":
        case "scalar":
        case "double-quoted-scalar":
        case "single-quoted-scalar":
          if (key.source.includes("\n"))
            return true;
          if (key.end) {
            for (const st of key.end)
              if (st.type === "newline")
                return true;
          }
          return false;
        case "flow-collection":
          for (const it of key.items) {
            for (const st of it.start)
              if (st.type === "newline")
                return true;
            if (it.sep) {
              for (const st of it.sep)
                if (st.type === "newline")
                  return true;
            }
            if (containsNewline(it.key) || containsNewline(it.value))
              return true;
          }
          return false;
        default:
          return true;
      }
    }
    exports.containsNewline = containsNewline;
  }
});

// node_modules/yaml/dist/compose/util-flow-indent-check.js
var require_util_flow_indent_check = __commonJS({
  "node_modules/yaml/dist/compose/util-flow-indent-check.js"(exports) {
    "use strict";
    var utilContainsNewline = require_util_contains_newline();
    function flowIndentCheck(indent, fc, onError) {
      if (fc?.type === "flow-collection") {
        const end = fc.end[0];
        if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) {
          const msg = "Flow end indicator should be more indented than parent";
          onError(end, "BAD_INDENT", msg, true);
        }
      }
    }
    exports.flowIndentCheck = flowIndentCheck;
  }
});

// node_modules/yaml/dist/compose/util-map-includes.js
var require_util_map_includes = __commonJS({
  "node_modules/yaml/dist/compose/util-map-includes.js"(exports) {
    "use strict";
    var identity = require_identity();
    function mapIncludes(ctx, items, search) {
      const { uniqueKeys } = ctx.options;
      if (uniqueKeys === false)
        return false;
      const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || identity.isScalar(a) && identity.isScalar(b) && a.value === b.value;
      return items.some((pair) => isEqual(pair.key, search));
    }
    exports.mapIncludes = mapIncludes;
  }
});

// node_modules/yaml/dist/compose/resolve-block-map.js
var require_resolve_block_map = __commonJS({
  "node_modules/yaml/dist/compose/resolve-block-map.js"(exports) {
    "use strict";
    var Pair = require_Pair();
    var YAMLMap = require_YAMLMap();
    var resolveProps = require_resolve_props();
    var utilContainsNewline = require_util_contains_newline();
    var utilFlowIndentCheck = require_util_flow_indent_check();
    var utilMapIncludes = require_util_map_includes();
    var startColMsg = "All mapping items must start at the same column";
    function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {
      const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;
      const map = new NodeClass(ctx.schema);
      if (ctx.atRoot)
        ctx.atRoot = false;
      let offset = bm.offset;
      let commentEnd = null;
      for (const collItem of bm.items) {
        const { start, key, sep, value } = collItem;
        const keyProps = resolveProps.resolveProps(start, {
          indicator: "explicit-key-ind",
          next: key ?? sep?.[0],
          offset,
          onError,
          parentIndent: bm.indent,
          startOnNewline: true
        });
        const implicitKey = !keyProps.found;
        if (implicitKey) {
          if (key) {
            if (key.type === "block-seq")
              onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key");
            else if ("indent" in key && key.indent !== bm.indent)
              onError(offset, "BAD_INDENT", startColMsg);
          }
          if (!keyProps.anchor && !keyProps.tag && !sep) {
            commentEnd = keyProps.end;
            if (keyProps.comment) {
              if (map.comment)
                map.comment += "\n" + keyProps.comment;
              else
                map.comment = keyProps.comment;
            }
            continue;
          }
          if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) {
            onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line");
          }
        } else if (keyProps.found?.indent !== bm.indent) {
          onError(offset, "BAD_INDENT", startColMsg);
        }
        ctx.atKey = true;
        const keyStart = keyProps.end;
        const keyNode = key ? composeNode(ctx, key, keyProps, onError) : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);
        if (ctx.schema.compat)
          utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError);
        ctx.atKey = false;
        if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
          onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
        const valueProps = resolveProps.resolveProps(sep ?? [], {
          indicator: "map-value-ind",
          next: value,
          offset: keyNode.range[2],
          onError,
          parentIndent: bm.indent,
          startOnNewline: !key || key.type === "block-scalar"
        });
        offset = valueProps.end;
        if (valueProps.found) {
          if (implicitKey) {
            if (value?.type === "block-map" && !valueProps.hasNewline)
              onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings");
            if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
              onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
          }
          const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);
          if (ctx.schema.compat)
            utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);
          offset = valueNode.range[2];
          const pair = new Pair.Pair(keyNode, valueNode);
          if (ctx.options.keepSourceTokens)
            pair.srcToken = collItem;
          map.items.push(pair);
        } else {
          if (implicitKey)
            onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values");
          if (valueProps.comment) {
            if (keyNode.comment)
              keyNode.comment += "\n" + valueProps.comment;
            else
              keyNode.comment = valueProps.comment;
          }
          const pair = new Pair.Pair(keyNode);
          if (ctx.options.keepSourceTokens)
            pair.srcToken = collItem;
          map.items.push(pair);
        }
      }
      if (commentEnd && commentEnd < offset)
        onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content");
      map.range = [bm.offset, offset, commentEnd ?? offset];
      return map;
    }
    exports.resolveBlockMap = resolveBlockMap;
  }
});

// node_modules/yaml/dist/compose/resolve-block-seq.js
var require_resolve_block_seq = __commonJS({
  "node_modules/yaml/dist/compose/resolve-block-seq.js"(exports) {
    "use strict";
    var YAMLSeq = require_YAMLSeq();
    var resolveProps = require_resolve_props();
    var utilFlowIndentCheck = require_util_flow_indent_check();
    function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {
      const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;
      const seq = new NodeClass(ctx.schema);
      if (ctx.atRoot)
        ctx.atRoot = false;
      if (ctx.atKey)
        ctx.atKey = false;
      let offset = bs.offset;
      let commentEnd = null;
      for (const { start, value } of bs.items) {
        const props = resolveProps.resolveProps(start, {
          indicator: "seq-item-ind",
          next: value,
          offset,
          onError,
          parentIndent: bs.indent,
          startOnNewline: true
        });
        if (!props.found) {
          if (props.anchor || props.tag || value) {
            if (value?.type === "block-seq")
              onError(props.end, "BAD_INDENT", "All sequence items must start at the same column");
            else
              onError(offset, "MISSING_CHAR", "Sequence item without - indicator");
          } else {
            commentEnd = props.end;
            if (props.comment)
              seq.comment = props.comment;
            continue;
          }
        }
        const node = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError);
        if (ctx.schema.compat)
          utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError);
        offset = node.range[2];
        seq.items.push(node);
      }
      seq.range = [bs.offset, offset, commentEnd ?? offset];
      return seq;
    }
    exports.resolveBlockSeq = resolveBlockSeq;
  }
});

// node_modules/yaml/dist/compose/resolve-end.js
var require_resolve_end = __commonJS({
  "node_modules/yaml/dist/compose/resolve-end.js"(exports) {
    "use strict";
    function resolveEnd(end, offset, reqSpace, onError) {
      let comment = "";
      if (end) {
        let hasSpace = false;
        let sep = "";
        for (const token of end) {
          const { source, type } = token;
          switch (type) {
            case "space":
              hasSpace = true;
              break;
            case "comment": {
              if (reqSpace && !hasSpace)
                onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
              const cb = source.substring(1) || " ";
              if (!comment)
                comment = cb;
              else
                comment += sep + cb;
              sep = "";
              break;
            }
            case "newline":
              if (comment)
                sep += source;
              hasSpace = true;
              break;
            default:
              onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`);
          }
          offset += source.length;
        }
      }
      return { comment, offset };
    }
    exports.resolveEnd = resolveEnd;
  }
});

// node_modules/yaml/dist/compose/resolve-flow-collection.js
var require_resolve_flow_collection = __commonJS({
  "node_modules/yaml/dist/compose/resolve-flow-collection.js"(exports) {
    "use strict";
    var identity = require_identity();
    var Pair = require_Pair();
    var YAMLMap = require_YAMLMap();
    var YAMLSeq = require_YAMLSeq();
    var resolveEnd = require_resolve_end();
    var resolveProps = require_resolve_props();
    var utilContainsNewline = require_util_contains_newline();
    var utilMapIncludes = require_util_map_includes();
    var blockMsg = "Block collections are not allowed within flow collections";
    var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq");
    function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {
      const isMap = fc.start.source === "{";
      const fcName = isMap ? "flow map" : "flow sequence";
      const NodeClass = tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq);
      const coll = new NodeClass(ctx.schema);
      coll.flow = true;
      const atRoot = ctx.atRoot;
      if (atRoot)
        ctx.atRoot = false;
      if (ctx.atKey)
        ctx.atKey = false;
      let offset = fc.offset + fc.start.source.length;
      for (let i = 0; i < fc.items.length; ++i) {
        const collItem = fc.items[i];
        const { start, key, sep, value } = collItem;
        const props = resolveProps.resolveProps(start, {
          flow: fcName,
          indicator: "explicit-key-ind",
          next: key ?? sep?.[0],
          offset,
          onError,
          parentIndent: fc.indent,
          startOnNewline: false
        });
        if (!props.found) {
          if (!props.anchor && !props.tag && !sep && !value) {
            if (i === 0 && props.comma)
              onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
            else if (i < fc.items.length - 1)
              onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`);
            if (props.comment) {
              if (coll.comment)
                coll.comment += "\n" + props.comment;
              else
                coll.comment = props.comment;
            }
            offset = props.end;
            continue;
          }
          if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))
            onError(
              key,
              // checked by containsNewline()
              "MULTILINE_IMPLICIT_KEY",
              "Implicit keys of flow sequence pairs need to be on a single line"
            );
        }
        if (i === 0) {
          if (props.comma)
            onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
        } else {
          if (!props.comma)
            onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`);
          if (props.comment) {
            let prevItemComment = "";
            loop: for (const st of start) {
              switch (st.type) {
                case "comma":
                case "space":
                  break;
                case "comment":
                  prevItemComment = st.source.substring(1);
                  break loop;
                default:
                  break loop;
              }
            }
            if (prevItemComment) {
              let prev = coll.items[coll.items.length - 1];
              if (identity.isPair(prev))
                prev = prev.value ?? prev.key;
              if (prev.comment)
                prev.comment += "\n" + prevItemComment;
              else
                prev.comment = prevItemComment;
              props.comment = props.comment.substring(prevItemComment.length + 1);
            }
          }
        }
        if (!isMap && !sep && !props.found) {
          const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep, null, props, onError);
          coll.items.push(valueNode);
          offset = valueNode.range[2];
          if (isBlock(value))
            onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
        } else {
          ctx.atKey = true;
          const keyStart = props.end;
          const keyNode = key ? composeNode(ctx, key, props, onError) : composeEmptyNode(ctx, keyStart, start, null, props, onError);
          if (isBlock(key))
            onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
          ctx.atKey = false;
          const valueProps = resolveProps.resolveProps(sep ?? [], {
            flow: fcName,
            indicator: "map-value-ind",
            next: value,
            offset: keyNode.range[2],
            onError,
            parentIndent: fc.indent,
            startOnNewline: false
          });
          if (valueProps.found) {
            if (!isMap && !props.found && ctx.options.strict) {
              if (sep)
                for (const st of sep) {
                  if (st === valueProps.found)
                    break;
                  if (st.type === "newline") {
                    onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
                    break;
                  }
                }
              if (props.start < valueProps.found.offset - 1024)
                onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key");
            }
          } else if (value) {
            if ("source" in value && value.source?.[0] === ":")
              onError(value, "MISSING_CHAR", `Missing space after : in ${fcName}`);
            else
              onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
          }
          const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError) : null;
          if (valueNode) {
            if (isBlock(value))
              onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
          } else if (valueProps.comment) {
            if (keyNode.comment)
              keyNode.comment += "\n" + valueProps.comment;
            else
              keyNode.comment = valueProps.comment;
          }
          const pair = new Pair.Pair(keyNode, valueNode);
          if (ctx.options.keepSourceTokens)
            pair.srcToken = collItem;
          if (isMap) {
            const map = coll;
            if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
              onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
            map.items.push(pair);
          } else {
            const map = new YAMLMap.YAMLMap(ctx.schema);
            map.flow = true;
            map.items.push(pair);
            const endRange = (valueNode ?? keyNode).range;
            map.range = [keyNode.range[0], endRange[1], endRange[2]];
            coll.items.push(map);
          }
          offset = valueNode ? valueNode.range[2] : valueProps.end;
        }
      }
      const expectedEnd = isMap ? "}" : "]";
      const [ce, ...ee] = fc.end;
      let cePos = offset;
      if (ce?.source === expectedEnd)
        cePos = ce.offset + ce.source.length;
      else {
        const name = fcName[0].toUpperCase() + fcName.substring(1);
        const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
        onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg);
        if (ce && ce.source.length !== 1)
          ee.unshift(ce);
      }
      if (ee.length > 0) {
        const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);
        if (end.comment) {
          if (coll.comment)
            coll.comment += "\n" + end.comment;
          else
            coll.comment = end.comment;
        }
        coll.range = [fc.offset, cePos, end.offset];
      } else {
        coll.range = [fc.offset, cePos, cePos];
      }
      return coll;
    }
    exports.resolveFlowCollection = resolveFlowCollection;
  }
});

// node_modules/yaml/dist/compose/compose-collection.js
var require_compose_collection = __commonJS({
  "node_modules/yaml/dist/compose/compose-collection.js"(exports) {
    "use strict";
    var identity = require_identity();
    var Scalar = require_Scalar();
    var YAMLMap = require_YAMLMap();
    var YAMLSeq = require_YAMLSeq();
    var resolveBlockMap = require_resolve_block_map();
    var resolveBlockSeq = require_resolve_block_seq();
    var resolveFlowCollection = require_resolve_flow_collection();
    function resolveCollection(CN, ctx, token, onError, tagName, tag) {
      const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);
      const Coll = coll.constructor;
      if (tagName === "!" || tagName === Coll.tagName) {
        coll.tag = Coll.tagName;
        return coll;
      }
      if (tagName)
        coll.tag = tagName;
      return coll;
    }
    function composeCollection(CN, ctx, token, props, onError) {
      const tagToken = props.tag;
      const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg));
      if (token.type === "block-seq") {
        const { anchor, newlineAfterProp: nl } = props;
        const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken;
        if (lastProp && (!nl || nl.offset < lastProp.offset)) {
          const message = "Missing newline after block sequence props";
          onError(lastProp, "MISSING_CHAR", message);
        }
      }
      const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq";
      if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") {
        return resolveCollection(CN, ctx, token, onError, tagName);
      }
      let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType);
      if (!tag) {
        const kt = ctx.schema.knownTags[tagName];
        if (kt?.collection === expType) {
          ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
          tag = kt;
        } else {
          if (kt) {
            onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true);
          } else {
            onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true);
          }
          return resolveCollection(CN, ctx, token, onError, tagName);
        }
      }
      const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);
      const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll;
      const node = identity.isNode(res) ? res : new Scalar.Scalar(res);
      node.range = coll.range;
      node.tag = tagName;
      if (tag?.format)
        node.format = tag.format;
      return node;
    }
    exports.composeCollection = composeCollection;
  }
});

// node_modules/yaml/dist/compose/resolve-block-scalar.js
var require_resolve_block_scalar = __commonJS({
  "node_modules/yaml/dist/compose/resolve-block-scalar.js"(exports) {
    "use strict";
    var Scalar = require_Scalar();
    function resolveBlockScalar(ctx, scalar, onError) {
      const start = scalar.offset;
      const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);
      if (!header)
        return { value: "", type: null, comment: "", range: [start, start, start] };
      const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;
      const lines = scalar.source ? splitLines(scalar.source) : [];
      let chompStart = lines.length;
      for (let i = lines.length - 1; i >= 0; --i) {
        const content = lines[i][1];
        if (content === "" || content === "\r")
          chompStart = i;
        else
          break;
      }
      if (chompStart === 0) {
        const value2 = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : "";
        let end2 = start + header.length;
        if (scalar.source)
          end2 += scalar.source.length;
        return { value: value2, type, comment: header.comment, range: [start, end2, end2] };
      }
      let trimIndent = scalar.indent + header.indent;
      let offset = scalar.offset + header.length;
      let contentStart = 0;
      for (let i = 0; i < chompStart; ++i) {
        const [indent, content] = lines[i];
        if (content === "" || content === "\r") {
          if (header.indent === 0 && indent.length > trimIndent)
            trimIndent = indent.length;
        } else {
          if (indent.length < trimIndent) {
            const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator";
            onError(offset + indent.length, "MISSING_CHAR", message);
          }
          if (header.indent === 0)
            trimIndent = indent.length;
          contentStart = i;
          if (trimIndent === 0 && !ctx.atRoot) {
            const message = "Block scalar values in collections must be indented";
            onError(offset, "BAD_INDENT", message);
          }
          break;
        }
        offset += indent.length + content.length + 1;
      }
      for (let i = lines.length - 1; i >= chompStart; --i) {
        if (lines[i][0].length > trimIndent)
          chompStart = i + 1;
      }
      let value = "";
      let sep = "";
      let prevMoreIndented = false;
      for (let i = 0; i < contentStart; ++i)
        value += lines[i][0].slice(trimIndent) + "\n";
      for (let i = contentStart; i < chompStart; ++i) {
        let [indent, content] = lines[i];
        offset += indent.length + content.length + 1;
        const crlf = content[content.length - 1] === "\r";
        if (crlf)
          content = content.slice(0, -1);
        if (content && indent.length < trimIndent) {
          const src = header.indent ? "explicit indentation indicator" : "first line";
          const message = `Block scalar lines must not be less indented than their ${src}`;
          onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message);
          indent = "";
        }
        if (type === Scalar.Scalar.BLOCK_LITERAL) {
          value += sep + indent.slice(trimIndent) + content;
          sep = "\n";
        } else if (indent.length > trimIndent || content[0] === "	") {
          if (sep === " ")
            sep = "\n";
          else if (!prevMoreIndented && sep === "\n")
            sep = "\n\n";
          value += sep + indent.slice(trimIndent) + content;
          sep = "\n";
          prevMoreIndented = true;
        } else if (content === "") {
          if (sep === "\n")
            value += "\n";
          else
            sep = "\n";
        } else {
          value += sep + content;
          sep = " ";
          prevMoreIndented = false;
        }
      }
      switch (header.chomp) {
        case "-":
          break;
        case "+":
          for (let i = chompStart; i < lines.length; ++i)
            value += "\n" + lines[i][0].slice(trimIndent);
          if (value[value.length - 1] !== "\n")
            value += "\n";
          break;
        default:
          value += "\n";
      }
      const end = start + header.length + scalar.source.length;
      return { value, type, comment: header.comment, range: [start, end, end] };
    }
    function parseBlockScalarHeader({ offset, props }, strict, onError) {
      if (props[0].type !== "block-scalar-header") {
        onError(props[0], "IMPOSSIBLE", "Block scalar header not found");
        return null;
      }
      const { source } = props[0];
      const mode = source[0];
      let indent = 0;
      let chomp = "";
      let error = -1;
      for (let i = 1; i < source.length; ++i) {
        const ch = source[i];
        if (!chomp && (ch === "-" || ch === "+"))
          chomp = ch;
        else {
          const n = Number(ch);
          if (!indent && n)
            indent = n;
          else if (error === -1)
            error = offset + i;
        }
      }
      if (error !== -1)
        onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`);
      let hasSpace = false;
      let comment = "";
      let length = source.length;
      for (let i = 1; i < props.length; ++i) {
        const token = props[i];
        switch (token.type) {
          case "space":
            hasSpace = true;
          // fallthrough
          case "newline":
            length += token.source.length;
            break;
          case "comment":
            if (strict && !hasSpace) {
              const message = "Comments must be separated from other tokens by white space characters";
              onError(token, "MISSING_CHAR", message);
            }
            length += token.source.length;
            comment = token.source.substring(1);
            break;
          case "error":
            onError(token, "UNEXPECTED_TOKEN", token.message);
            length += token.source.length;
            break;
          /* istanbul ignore next should not happen */
          default: {
            const message = `Unexpected token in block scalar header: ${token.type}`;
            onError(token, "UNEXPECTED_TOKEN", message);
            const ts = token.source;
            if (ts && typeof ts === "string")
              length += ts.length;
          }
        }
      }
      return { mode, indent, chomp, comment, length };
    }
    function splitLines(source) {
      const split = source.split(/\n( *)/);
      const first = split[0];
      const m = first.match(/^( *)/);
      const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first];
      const lines = [line0];
      for (let i = 1; i < split.length; i += 2)
        lines.push([split[i], split[i + 1]]);
      return lines;
    }
    exports.resolveBlockScalar = resolveBlockScalar;
  }
});

// node_modules/yaml/dist/compose/resolve-flow-scalar.js
var require_resolve_flow_scalar = __commonJS({
  "node_modules/yaml/dist/compose/resolve-flow-scalar.js"(exports) {
    "use strict";
    var Scalar = require_Scalar();
    var resolveEnd = require_resolve_end();
    function resolveFlowScalar(scalar, strict, onError) {
      const { offset, type, source, end } = scalar;
      let _type;
      let value;
      const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
      switch (type) {
        case "scalar":
          _type = Scalar.Scalar.PLAIN;
          value = plainValue(source, _onError);
          break;
        case "single-quoted-scalar":
          _type = Scalar.Scalar.QUOTE_SINGLE;
          value = singleQuotedValue(source, _onError);
          break;
        case "double-quoted-scalar":
          _type = Scalar.Scalar.QUOTE_DOUBLE;
          value = doubleQuotedValue(source, _onError);
          break;
        /* istanbul ignore next should not happen */
        default:
          onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`);
          return {
            value: "",
            type: null,
            comment: "",
            range: [offset, offset + source.length, offset + source.length]
          };
      }
      const valueEnd = offset + source.length;
      const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError);
      return {
        value,
        type: _type,
        comment: re.comment,
        range: [offset, valueEnd, re.offset]
      };
    }
    function plainValue(source, onError) {
      let badChar = "";
      switch (source[0]) {
        /* istanbul ignore next should not happen */
        case "	":
          badChar = "a tab character";
          break;
        case ",":
          badChar = "flow indicator character ,";
          break;
        case "%":
          badChar = "directive indicator character %";
          break;
        case "|":
        case ">": {
          badChar = `block scalar indicator ${source[0]}`;
          break;
        }
        case "@":
        case "`": {
          badChar = `reserved character ${source[0]}`;
          break;
        }
      }
      if (badChar)
        onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`);
      return foldLines(source);
    }
    function singleQuotedValue(source, onError) {
      if (source[source.length - 1] !== "'" || source.length === 1)
        onError(source.length, "MISSING_CHAR", "Missing closing 'quote");
      return foldLines(source.slice(1, -1)).replace(/''/g, "'");
    }
    function foldLines(source) {
      let first, line;
      try {
        first = new RegExp("(.*?)(?<![ 	])[ 	]*\r?\n", "sy");
        line = new RegExp("[ 	]*(.*?)(?:(?<![ 	])[ 	]*)?\r?\n", "sy");
      } catch {
        first = /(.*?)[ \t]*\r?\n/sy;
        line = /[ \t]*(.*?)[ \t]*\r?\n/sy;
      }
      let match = first.exec(source);
      if (!match)
        return source;
      let res = match[1];
      let sep = " ";
      let pos = first.lastIndex;
      line.lastIndex = pos;
      while (match = line.exec(source)) {
        if (match[1] === "") {
          if (sep === "\n")
            res += sep;
          else
            sep = "\n";
        } else {
          res += sep + match[1];
          sep = " ";
        }
        pos = line.lastIndex;
      }
      const last = /[ \t]*(.*)/sy;
      last.lastIndex = pos;
      match = last.exec(source);
      return res + sep + (match?.[1] ?? "");
    }
    function doubleQuotedValue(source, onError) {
      let res = "";
      for (let i = 1; i < source.length - 1; ++i) {
        const ch = source[i];
        if (ch === "\r" && source[i + 1] === "\n")
          continue;
        if (ch === "\n") {
          const { fold, offset } = foldNewline(source, i);
          res += fold;
          i = offset;
        } else if (ch === "\\") {
          let next = source[++i];
          const cc = escapeCodes[next];
          if (cc)
            res += cc;
          else if (next === "\n") {
            next = source[i + 1];
            while (next === " " || next === "	")
              next = source[++i + 1];
          } else if (next === "\r" && source[i + 1] === "\n") {
            next = source[++i + 1];
            while (next === " " || next === "	")
              next = source[++i + 1];
          } else if (next === "x" || next === "u" || next === "U") {
            const length = { x: 2, u: 4, U: 8 }[next];
            res += parseCharCode(source, i + 1, length, onError);
            i += length;
          } else {
            const raw = source.substr(i - 1, 2);
            onError(i - 1, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
            res += raw;
          }
        } else if (ch === " " || ch === "	") {
          const wsStart = i;
          let next = source[i + 1];
          while (next === " " || next === "	")
            next = source[++i + 1];
          if (next !== "\n" && !(next === "\r" && source[i + 2] === "\n"))
            res += i > wsStart ? source.slice(wsStart, i + 1) : ch;
        } else {
          res += ch;
        }
      }
      if (source[source.length - 1] !== '"' || source.length === 1)
        onError(source.length, "MISSING_CHAR", 'Missing closing "quote');
      return res;
    }
    function foldNewline(source, offset) {
      let fold = "";
      let ch = source[offset + 1];
      while (ch === " " || ch === "	" || ch === "\n" || ch === "\r") {
        if (ch === "\r" && source[offset + 2] !== "\n")
          break;
        if (ch === "\n")
          fold += "\n";
        offset += 1;
        ch = source[offset + 1];
      }
      if (!fold)
        fold = " ";
      return { fold, offset };
    }
    var escapeCodes = {
      "0": "\0",
      // null character
      a: "\x07",
      // bell character
      b: "\b",
      // backspace
      e: "\x1B",
      // escape character
      f: "\f",
      // form feed
      n: "\n",
      // line feed
      r: "\r",
      // carriage return
      t: "	",
      // horizontal tab
      v: "\v",
      // vertical tab
      N: "\x85",
      // Unicode next line
      _: "\xA0",
      // Unicode non-breaking space
      L: "\u2028",
      // Unicode line separator
      P: "\u2029",
      // Unicode paragraph separator
      " ": " ",
      '"': '"',
      "/": "/",
      "\\": "\\",
      "	": "	"
    };
    function parseCharCode(source, offset, length, onError) {
      const cc = source.substr(offset, length);
      const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
      const code = ok ? parseInt(cc, 16) : NaN;
      if (isNaN(code)) {
        const raw = source.substr(offset - 2, length + 2);
        onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
        return raw;
      }
      return String.fromCodePoint(code);
    }
    exports.resolveFlowScalar = resolveFlowScalar;
  }
});

// node_modules/yaml/dist/compose/compose-scalar.js
var require_compose_scalar = __commonJS({
  "node_modules/yaml/dist/compose/compose-scalar.js"(exports) {
    "use strict";
    var identity = require_identity();
    var Scalar = require_Scalar();
    var resolveBlockScalar = require_resolve_block_scalar();
    var resolveFlowScalar = require_resolve_flow_scalar();
    function composeScalar(ctx, token, tagToken, onError) {
      const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError) : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);
      const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null;
      let tag;
      if (ctx.options.stringKeys && ctx.atKey) {
        tag = ctx.schema[identity.SCALAR];
      } else if (tagName)
        tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);
      else if (token.type === "scalar")
        tag = findScalarTagByTest(ctx, value, token, onError);
      else
        tag = ctx.schema[identity.SCALAR];
      let scalar;
      try {
        const res = tag.resolve(value, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options);
        scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res);
      } catch (error) {
        const msg = error instanceof Error ? error.message : String(error);
        onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg);
        scalar = new Scalar.Scalar(value);
      }
      scalar.range = range;
      scalar.source = value;
      if (type)
        scalar.type = type;
      if (tagName)
        scalar.tag = tagName;
      if (tag.format)
        scalar.format = tag.format;
      if (comment)
        scalar.comment = comment;
      return scalar;
    }
    function findScalarTagByName(schema, value, tagName, tagToken, onError) {
      if (tagName === "!")
        return schema[identity.SCALAR];
      const matchWithTest = [];
      for (const tag of schema.tags) {
        if (!tag.collection && tag.tag === tagName) {
          if (tag.default && tag.test)
            matchWithTest.push(tag);
          else
            return tag;
        }
      }
      for (const tag of matchWithTest)
        if (tag.test?.test(value))
          return tag;
      const kt = schema.knownTags[tagName];
      if (kt && !kt.collection) {
        schema.tags.push(Object.assign({}, kt, { default: false, test: void 0 }));
        return kt;
      }
      onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str");
      return schema[identity.SCALAR];
    }
    function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {
      const tag = schema.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value)) || schema[identity.SCALAR];
      if (schema.compat) {
        const compat = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema[identity.SCALAR];
        if (tag.tag !== compat.tag) {
          const ts = directives.tagString(tag.tag);
          const cs = directives.tagString(compat.tag);
          const msg = `Value may be parsed as either ${ts} or ${cs}`;
          onError(token, "TAG_RESOLVE_FAILED", msg, true);
        }
      }
      return tag;
    }
    exports.composeScalar = composeScalar;
  }
});

// node_modules/yaml/dist/compose/util-empty-scalar-position.js
var require_util_empty_scalar_position = __commonJS({
  "node_modules/yaml/dist/compose/util-empty-scalar-position.js"(exports) {
    "use strict";
    function emptyScalarPosition(offset, before, pos) {
      if (before) {
        pos ?? (pos = before.length);
        for (let i = pos - 1; i >= 0; --i) {
          let st = before[i];
          switch (st.type) {
            case "space":
            case "comment":
            case "newline":
              offset -= st.source.length;
              continue;
          }
          st = before[++i];
          while (st?.type === "space") {
            offset += st.source.length;
            st = before[++i];
          }
          break;
        }
      }
      return offset;
    }
    exports.emptyScalarPosition = emptyScalarPosition;
  }
});

// node_modules/yaml/dist/compose/compose-node.js
var require_compose_node = __commonJS({
  "node_modules/yaml/dist/compose/compose-node.js"(exports) {
    "use strict";
    var Alias = require_Alias();
    var identity = require_identity();
    var composeCollection = require_compose_collection();
    var composeScalar = require_compose_scalar();
    var resolveEnd = require_resolve_end();
    var utilEmptyScalarPosition = require_util_empty_scalar_position();
    var CN = { composeNode, composeEmptyNode };
    function composeNode(ctx, token, props, onError) {
      const atKey = ctx.atKey;
      const { spaceBefore, comment, anchor, tag } = props;
      let node;
      let isSrcToken = true;
      switch (token.type) {
        case "alias":
          node = composeAlias(ctx, token, onError);
          if (anchor || tag)
            onError(token, "ALIAS_PROPS", "An alias node must not specify any properties");
          break;
        case "scalar":
        case "single-quoted-scalar":
        case "double-quoted-scalar":
        case "block-scalar":
          node = composeScalar.composeScalar(ctx, token, tag, onError);
          if (anchor)
            node.anchor = anchor.source.substring(1);
          break;
        case "block-map":
        case "block-seq":
        case "flow-collection":
          try {
            node = composeCollection.composeCollection(CN, ctx, token, props, onError);
            if (anchor)
              node.anchor = anchor.source.substring(1);
          } catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            onError(token, "RESOURCE_EXHAUSTION", message);
          }
          break;
        default: {
          const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`;
          onError(token, "UNEXPECTED_TOKEN", message);
          isSrcToken = false;
        }
      }
      node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError));
      if (anchor && node.anchor === "")
        onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
      if (atKey && ctx.options.stringKeys && (!identity.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) {
        const msg = "With stringKeys, all keys must be strings";
        onError(tag ?? token, "NON_STRING_KEY", msg);
      }
      if (spaceBefore)
        node.spaceBefore = true;
      if (comment) {
        if (token.type === "scalar" && token.source === "")
          node.comment = comment;
        else
          node.commentBefore = comment;
      }
      if (ctx.options.keepSourceTokens && isSrcToken)
        node.srcToken = token;
      return node;
    }
    function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {
      const token = {
        type: "scalar",
        offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),
        indent: -1,
        source: ""
      };
      const node = composeScalar.composeScalar(ctx, token, tag, onError);
      if (anchor) {
        node.anchor = anchor.source.substring(1);
        if (node.anchor === "")
          onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
      }
      if (spaceBefore)
        node.spaceBefore = true;
      if (comment) {
        node.comment = comment;
        node.range[2] = end;
      }
      return node;
    }
    function composeAlias({ options }, { offset, source, end }, onError) {
      const alias = new Alias.Alias(source.substring(1));
      if (alias.source === "")
        onError(offset, "BAD_ALIAS", "Alias cannot be an empty string");
      if (alias.source.endsWith(":"))
        onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true);
      const valueEnd = offset + source.length;
      const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError);
      alias.range = [offset, valueEnd, re.offset];
      if (re.comment)
        alias.comment = re.comment;
      return alias;
    }
    exports.composeEmptyNode = composeEmptyNode;
    exports.composeNode = composeNode;
  }
});

// node_modules/yaml/dist/compose/compose-doc.js
var require_compose_doc = __commonJS({
  "node_modules/yaml/dist/compose/compose-doc.js"(exports) {
    "use strict";
    var Document = require_Document();
    var composeNode = require_compose_node();
    var resolveEnd = require_resolve_end();
    var resolveProps = require_resolve_props();
    function composeDoc(options, directives, { offset, start, value, end }, onError) {
      const opts = Object.assign({ _directives: directives }, options);
      const doc = new Document.Document(void 0, opts);
      const ctx = {
        atKey: false,
        atRoot: true,
        directives: doc.directives,
        options: doc.options,
        schema: doc.schema
      };
      const props = resolveProps.resolveProps(start, {
        indicator: "doc-start",
        next: value ?? end?.[0],
        offset,
        onError,
        parentIndent: 0,
        startOnNewline: true
      });
      if (props.found) {
        doc.directives.docStart = true;
        if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline)
          onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker");
      }
      doc.contents = value ? composeNode.composeNode(ctx, value, props, onError) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);
      const contentEnd = doc.contents.range[2];
      const re = resolveEnd.resolveEnd(end, contentEnd, false, onError);
      if (re.comment)
        doc.comment = re.comment;
      doc.range = [offset, contentEnd, re.offset];
      return doc;
    }
    exports.composeDoc = composeDoc;
  }
});

// node_modules/yaml/dist/compose/composer.js
var require_composer = __commonJS({
  "node_modules/yaml/dist/compose/composer.js"(exports) {
    "use strict";
    var node_process = __require("process");
    var directives = require_directives();
    var Document = require_Document();
    var errors = require_errors();
    var identity = require_identity();
    var composeDoc = require_compose_doc();
    var resolveEnd = require_resolve_end();
    function getErrorPos(src) {
      if (typeof src === "number")
        return [src, src + 1];
      if (Array.isArray(src))
        return src.length === 2 ? src : [src[0], src[1]];
      const { offset, source } = src;
      return [offset, offset + (typeof source === "string" ? source.length : 1)];
    }
    function parsePrelude(prelude) {
      let comment = "";
      let atComment = false;
      let afterEmptyLine = false;
      for (let i = 0; i < prelude.length; ++i) {
        const source = prelude[i];
        switch (source[0]) {
          case "#":
            comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " ");
            atComment = true;
            afterEmptyLine = false;
            break;
          case "%":
            if (prelude[i + 1]?.[0] !== "#")
              i += 1;
            atComment = false;
            break;
          default:
            if (!atComment)
              afterEmptyLine = true;
            atComment = false;
        }
      }
      return { comment, afterEmptyLine };
    }
    var Composer = class {
      constructor(options = {}) {
        this.doc = null;
        this.atDirectives = false;
        this.prelude = [];
        this.errors = [];
        this.warnings = [];
        this.onError = (source, code, message, warning) => {
          const pos = getErrorPos(source);
          if (warning)
            this.warnings.push(new errors.YAMLWarning(pos, code, message));
          else
            this.errors.push(new errors.YAMLParseError(pos, code, message));
        };
        this.directives = new directives.Directives({ version: options.version || "1.2" });
        this.options = options;
      }
      decorate(doc, afterDoc) {
        const { comment, afterEmptyLine } = parsePrelude(this.prelude);
        if (comment) {
          const dc = doc.contents;
          if (afterDoc) {
            doc.comment = doc.comment ? `${doc.comment}
${comment}` : comment;
          } else if (afterEmptyLine || doc.directives.docStart || !dc) {
            doc.commentBefore = comment;
          } else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) {
            let it = dc.items[0];
            if (identity.isPair(it))
              it = it.key;
            const cb = it.commentBefore;
            it.commentBefore = cb ? `${comment}
${cb}` : comment;
          } else {
            const cb = dc.commentBefore;
            dc.commentBefore = cb ? `${comment}
${cb}` : comment;
          }
        }
        if (afterDoc) {
          Array.prototype.push.apply(doc.errors, this.errors);
          Array.prototype.push.apply(doc.warnings, this.warnings);
        } else {
          doc.errors = this.errors;
          doc.warnings = this.warnings;
        }
        this.prelude = [];
        this.errors = [];
        this.warnings = [];
      }
      /**
       * Current stream status information.
       *
       * Mostly useful at the end of input for an empty stream.
       */
      streamInfo() {
        return {
          comment: parsePrelude(this.prelude).comment,
          directives: this.directives,
          errors: this.errors,
          warnings: this.warnings
        };
      }
      /**
       * Compose tokens into documents.
       *
       * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
       * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
       */
      *compose(tokens, forceDoc = false, endOffset = -1) {
        for (const token of tokens)
          yield* this.next(token);
        yield* this.end(forceDoc, endOffset);
      }
      /** Advance the composer by one CST token. */
      *next(token) {
        if (node_process.env.LOG_STREAM)
          console.dir(token, { depth: null });
        switch (token.type) {
          case "directive":
            this.directives.add(token.source, (offset, message, warning) => {
              const pos = getErrorPos(token);
              pos[0] += offset;
              this.onError(pos, "BAD_DIRECTIVE", message, warning);
            });
            this.prelude.push(token.source);
            this.atDirectives = true;
            break;
          case "document": {
            const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError);
            if (this.atDirectives && !doc.directives.docStart)
              this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line");
            this.decorate(doc, false);
            if (this.doc)
              yield this.doc;
            this.doc = doc;
            this.atDirectives = false;
            break;
          }
          case "byte-order-mark":
          case "space":
            break;
          case "comment":
          case "newline":
            this.prelude.push(token.source);
            break;
          case "error": {
            const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message;
            const error = new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg);
            if (this.atDirectives || !this.doc)
              this.errors.push(error);
            else
              this.doc.errors.push(error);
            break;
          }
          case "doc-end": {
            if (!this.doc) {
              const msg = "Unexpected doc-end without preceding document";
              this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg));
              break;
            }
            this.doc.directives.docEnd = true;
            const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
            this.decorate(this.doc, true);
            if (end.comment) {
              const dc = this.doc.comment;
              this.doc.comment = dc ? `${dc}
${end.comment}` : end.comment;
            }
            this.doc.range[2] = end.offset;
            break;
          }
          default:
            this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`));
        }
      }
      /**
       * Call at end of input to yield any remaining document.
       *
       * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
       * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
       */
      *end(forceDoc = false, endOffset = -1) {
        if (this.doc) {
          this.decorate(this.doc, true);
          yield this.doc;
          this.doc = null;
        } else if (forceDoc) {
          const opts = Object.assign({ _directives: this.directives }, this.options);
          const doc = new Document.Document(void 0, opts);
          if (this.atDirectives)
            this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line");
          doc.range = [0, endOffset, endOffset];
          this.decorate(doc, false);
          yield doc;
        }
      }
    };
    exports.Composer = Composer;
  }
});

// node_modules/yaml/dist/parse/cst-scalar.js
var require_cst_scalar = __commonJS({
  "node_modules/yaml/dist/parse/cst-scalar.js"(exports) {
    "use strict";
    var resolveBlockScalar = require_resolve_block_scalar();
    var resolveFlowScalar = require_resolve_flow_scalar();
    var errors = require_errors();
    var stringifyString = require_stringifyString();
    function resolveAsScalar(token, strict = true, onError) {
      if (token) {
        const _onError = (pos, code, message) => {
          const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
          if (onError)
            onError(offset, code, message);
          else
            throw new errors.YAMLParseError([offset, offset + 1], code, message);
        };
        switch (token.type) {
          case "scalar":
          case "single-quoted-scalar":
          case "double-quoted-scalar":
            return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);
          case "block-scalar":
            return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);
        }
      }
      return null;
    }
    function createScalarToken(value, context) {
      const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context;
      const source = stringifyString.stringifyString({ type, value }, {
        implicitKey,
        indent: indent > 0 ? " ".repeat(indent) : "",
        inFlow,
        options: { blockQuote: true, lineWidth: -1 }
      });
      const end = context.end ?? [
        { type: "newline", offset: -1, indent, source: "\n" }
      ];
      switch (source[0]) {
        case "|":
        case ">": {
          const he = source.indexOf("\n");
          const head = source.substring(0, he);
          const body = source.substring(he + 1) + "\n";
          const props = [
            { type: "block-scalar-header", offset, indent, source: head }
          ];
          if (!addEndtoBlockProps(props, end))
            props.push({ type: "newline", offset: -1, indent, source: "\n" });
          return { type: "block-scalar", offset, indent, props, source: body };
        }
        case '"':
          return { type: "double-quoted-scalar", offset, indent, source, end };
        case "'":
          return { type: "single-quoted-scalar", offset, indent, source, end };
        default:
          return { type: "scalar", offset, indent, source, end };
      }
    }
    function setScalarValue(token, value, context = {}) {
      let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
      let indent = "indent" in token ? token.indent : null;
      if (afterKey && typeof indent === "number")
        indent += 2;
      if (!type)
        switch (token.type) {
          case "single-quoted-scalar":
            type = "QUOTE_SINGLE";
            break;
          case "double-quoted-scalar":
            type = "QUOTE_DOUBLE";
            break;
          case "block-scalar": {
            const header = token.props[0];
            if (header.type !== "block-scalar-header")
              throw new Error("Invalid block scalar header");
            type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL";
            break;
          }
          default:
            type = "PLAIN";
        }
      const source = stringifyString.stringifyString({ type, value }, {
        implicitKey: implicitKey || indent === null,
        indent: indent !== null && indent > 0 ? " ".repeat(indent) : "",
        inFlow,
        options: { blockQuote: true, lineWidth: -1 }
      });
      switch (source[0]) {
        case "|":
        case ">":
          setBlockScalarValue(token, source);
          break;
        case '"':
          setFlowScalarValue(token, source, "double-quoted-scalar");
          break;
        case "'":
          setFlowScalarValue(token, source, "single-quoted-scalar");
          break;
        default:
          setFlowScalarValue(token, source, "scalar");
      }
    }
    function setBlockScalarValue(token, source) {
      const he = source.indexOf("\n");
      const head = source.substring(0, he);
      const body = source.substring(he + 1) + "\n";
      if (token.type === "block-scalar") {
        const header = token.props[0];
        if (header.type !== "block-scalar-header")
          throw new Error("Invalid block scalar header");
        header.source = head;
        token.source = body;
      } else {
        const { offset } = token;
        const indent = "indent" in token ? token.indent : -1;
        const props = [
          { type: "block-scalar-header", offset, indent, source: head }
        ];
        if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0))
          props.push({ type: "newline", offset: -1, indent, source: "\n" });
        for (const key of Object.keys(token))
          if (key !== "type" && key !== "offset")
            delete token[key];
        Object.assign(token, { type: "block-scalar", indent, props, source: body });
      }
    }
    function addEndtoBlockProps(props, end) {
      if (end)
        for (const st of end)
          switch (st.type) {
            case "space":
            case "comment":
              props.push(st);
              break;
            case "newline":
              props.push(st);
              return true;
          }
      return false;
    }
    function setFlowScalarValue(token, source, type) {
      switch (token.type) {
        case "scalar":
        case "double-quoted-scalar":
        case "single-quoted-scalar":
          token.type = type;
          token.source = source;
          break;
        case "block-scalar": {
          const end = token.props.slice(1);
          let oa = source.length;
          if (token.props[0].type === "block-scalar-header")
            oa -= token.props[0].source.length;
          for (const tok of end)
            tok.offset += oa;
          delete token.props;
          Object.assign(token, { type, source, end });
          break;
        }
        case "block-map":
        case "block-seq": {
          const offset = token.offset + source.length;
          const nl = { type: "newline", offset, indent: token.indent, source: "\n" };
          delete token.items;
          Object.assign(token, { type, source, end: [nl] });
          break;
        }
        default: {
          const indent = "indent" in token ? token.indent : -1;
          const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : [];
          for (const key of Object.keys(token))
            if (key !== "type" && key !== "offset")
              delete token[key];
          Object.assign(token, { type, indent, source, end });
        }
      }
    }
    exports.createScalarToken = createScalarToken;
    exports.resolveAsScalar = resolveAsScalar;
    exports.setScalarValue = setScalarValue;
  }
});

// node_modules/yaml/dist/parse/cst-stringify.js
var require_cst_stringify = __commonJS({
  "node_modules/yaml/dist/parse/cst-stringify.js"(exports) {
    "use strict";
    var stringify = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst);
    function stringifyToken(token) {
      switch (token.type) {
        case "block-scalar": {
          let res = "";
          for (const tok of token.props)
            res += stringifyToken(tok);
          return res + token.source;
        }
        case "block-map":
        case "block-seq": {
          let res = "";
          for (const item of token.items)
            res += stringifyItem(item);
          return res;
        }
        case "flow-collection": {
          let res = token.start.source;
          for (const item of token.items)
            res += stringifyItem(item);
          for (const st of token.end)
            res += st.source;
          return res;
        }
        case "document": {
          let res = stringifyItem(token);
          if (token.end)
            for (const st of token.end)
              res += st.source;
          return res;
        }
        default: {
          let res = token.source;
          if ("end" in token && token.end)
            for (const st of token.end)
              res += st.source;
          return res;
        }
      }
    }
    function stringifyItem({ start, key, sep, value }) {
      let res = "";
      for (const st of start)
        res += st.source;
      if (key)
        res += stringifyToken(key);
      if (sep)
        for (const st of sep)
          res += st.source;
      if (value)
        res += stringifyToken(value);
      return res;
    }
    exports.stringify = stringify;
  }
});

// node_modules/yaml/dist/parse/cst-visit.js
var require_cst_visit = __commonJS({
  "node_modules/yaml/dist/parse/cst-visit.js"(exports) {
    "use strict";
    var BREAK = /* @__PURE__ */ Symbol("break visit");
    var SKIP = /* @__PURE__ */ Symbol("skip children");
    var REMOVE = /* @__PURE__ */ Symbol("remove item");
    function visit(cst, visitor) {
      if ("type" in cst && cst.type === "document")
        cst = { start: cst.start, value: cst.value };
      _visit(Object.freeze([]), cst, visitor);
    }
    visit.BREAK = BREAK;
    visit.SKIP = SKIP;
    visit.REMOVE = REMOVE;
    visit.itemAtPath = (cst, path4) => {
      let item = cst;
      for (const [field, index] of path4) {
        const tok = item?.[field];
        if (tok && "items" in tok) {
          item = tok.items[index];
        } else
          return void 0;
      }
      return item;
    };
    visit.parentCollection = (cst, path4) => {
      const parent = visit.itemAtPath(cst, path4.slice(0, -1));
      const field = path4[path4.length - 1][0];
      const coll = parent?.[field];
      if (coll && "items" in coll)
        return coll;
      throw new Error("Parent collection not found");
    };
    function _visit(path4, item, visitor) {
      let ctrl = visitor(item, path4);
      if (typeof ctrl === "symbol")
        return ctrl;
      for (const field of ["key", "value"]) {
        const token = item[field];
        if (token && "items" in token) {
          for (let i = 0; i < token.items.length; ++i) {
            const ci = _visit(Object.freeze(path4.concat([[field, i]])), token.items[i], visitor);
            if (typeof ci === "number")
              i = ci - 1;
            else if (ci === BREAK)
              return BREAK;
            else if (ci === REMOVE) {
              token.items.splice(i, 1);
              i -= 1;
            }
          }
          if (typeof ctrl === "function" && field === "key")
            ctrl = ctrl(item, path4);
        }
      }
      return typeof ctrl === "function" ? ctrl(item, path4) : ctrl;
    }
    exports.visit = visit;
  }
});

// node_modules/yaml/dist/parse/cst.js
var require_cst = __commonJS({
  "node_modules/yaml/dist/parse/cst.js"(exports) {
    "use strict";
    var cstScalar = require_cst_scalar();
    var cstStringify = require_cst_stringify();
    var cstVisit = require_cst_visit();
    var BOM = "\uFEFF";
    var DOCUMENT = "";
    var FLOW_END = "";
    var SCALAR = "";
    var isCollection = (token) => !!token && "items" in token;
    var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar");
    function prettyToken(token) {
      switch (token) {
        case BOM:
          return "<BOM>";
        case DOCUMENT:
          return "<DOC>";
        case FLOW_END:
          return "<FLOW_END>";
        case SCALAR:
          return "<SCALAR>";
        default:
          return JSON.stringify(token);
      }
    }
    function tokenType(source) {
      switch (source) {
        case BOM:
          return "byte-order-mark";
        case DOCUMENT:
          return "doc-mode";
        case FLOW_END:
          return "flow-error-end";
        case SCALAR:
          return "scalar";
        case "---":
          return "doc-start";
        case "...":
          return "doc-end";
        case "":
        case "\n":
        case "\r\n":
          return "newline";
        case "-":
          return "seq-item-ind";
        case "?":
          return "explicit-key-ind";
        case ":":
          return "map-value-ind";
        case "{":
          return "flow-map-start";
        case "}":
          return "flow-map-end";
        case "[":
          return "flow-seq-start";
        case "]":
          return "flow-seq-end";
        case ",":
          return "comma";
      }
      switch (source[0]) {
        case " ":
        case "	":
          return "space";
        case "#":
          return "comment";
        case "%":
          return "directive-line";
        case "*":
          return "alias";
        case "&":
          return "anchor";
        case "!":
          return "tag";
        case "'":
          return "single-quoted-scalar";
        case '"':
          return "double-quoted-scalar";
        case "|":
        case ">":
          return "block-scalar-header";
      }
      return null;
    }
    exports.createScalarToken = cstScalar.createScalarToken;
    exports.resolveAsScalar = cstScalar.resolveAsScalar;
    exports.setScalarValue = cstScalar.setScalarValue;
    exports.stringify = cstStringify.stringify;
    exports.visit = cstVisit.visit;
    exports.BOM = BOM;
    exports.DOCUMENT = DOCUMENT;
    exports.FLOW_END = FLOW_END;
    exports.SCALAR = SCALAR;
    exports.isCollection = isCollection;
    exports.isScalar = isScalar;
    exports.prettyToken = prettyToken;
    exports.tokenType = tokenType;
  }
});

// node_modules/yaml/dist/parse/lexer.js
var require_lexer = __commonJS({
  "node_modules/yaml/dist/parse/lexer.js"(exports) {
    "use strict";
    var cst = require_cst();
    function isEmpty(ch) {
      switch (ch) {
        case void 0:
        case " ":
        case "\n":
        case "\r":
        case "	":
          return true;
        default:
          return false;
      }
    }
    var hexDigits = new Set("0123456789ABCDEFabcdef");
    var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
    var flowIndicatorChars = new Set(",[]{}");
    var invalidAnchorChars = new Set(" ,[]{}\n\r	");
    var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);
    var Lexer = class {
      constructor() {
        this.atEnd = false;
        this.blockScalarIndent = -1;
        this.blockScalarKeep = false;
        this.buffer = "";
        this.flowKey = false;
        this.flowLevel = 0;
        this.indentNext = 0;
        this.indentValue = 0;
        this.lineEndPos = null;
        this.next = null;
        this.pos = 0;
      }
      /**
       * Generate YAML tokens from the `source` string. If `incomplete`,
       * a part of the last line may be left as a buffer for the next call.
       *
       * @returns A generator of lexical tokens
       */
      *lex(source, incomplete = false) {
        if (source) {
          if (typeof source !== "string")
            throw TypeError("source is not a string");
          this.buffer = this.buffer ? this.buffer + source : source;
          this.lineEndPos = null;
        }
        this.atEnd = !incomplete;
        let next = this.next ?? "stream";
        while (next && (incomplete || this.hasChars(1)))
          next = yield* this.parseNext(next);
      }
      atLineEnd() {
        let i = this.pos;
        let ch = this.buffer[i];
        while (ch === " " || ch === "	")
          ch = this.buffer[++i];
        if (!ch || ch === "#" || ch === "\n")
          return true;
        if (ch === "\r")
          return this.buffer[i + 1] === "\n";
        return false;
      }
      charAt(n) {
        return this.buffer[this.pos + n];
      }
      continueScalar(offset) {
        let ch = this.buffer[offset];
        if (this.indentNext > 0) {
          let indent = 0;
          while (ch === " ")
            ch = this.buffer[++indent + offset];
          if (ch === "\r") {
            const next = this.buffer[indent + offset + 1];
            if (next === "\n" || !next && !this.atEnd)
              return offset + indent + 1;
          }
          return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1;
        }
        if (ch === "-" || ch === ".") {
          const dt = this.buffer.substr(offset, 3);
          if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3]))
            return -1;
        }
        return offset;
      }
      getLine() {
        let end = this.lineEndPos;
        if (typeof end !== "number" || end !== -1 && end < this.pos) {
          end = this.buffer.indexOf("\n", this.pos);
          this.lineEndPos = end;
        }
        if (end === -1)
          return this.atEnd ? this.buffer.substring(this.pos) : null;
        if (this.buffer[end - 1] === "\r")
          end -= 1;
        return this.buffer.substring(this.pos, end);
      }
      hasChars(n) {
        return this.pos + n <= this.buffer.length;
      }
      setNext(state) {
        this.buffer = this.buffer.substring(this.pos);
        this.pos = 0;
        this.lineEndPos = null;
        this.next = state;
        return null;
      }
      peek(n) {
        return this.buffer.substr(this.pos, n);
      }
      *parseNext(next) {
        switch (next) {
          case "stream":
            return yield* this.parseStream();
          case "line-start":
            return yield* this.parseLineStart();
          case "block-start":
            return yield* this.parseBlockStart();
          case "doc":
            return yield* this.parseDocument();
          case "flow":
            return yield* this.parseFlowCollection();
          case "quoted-scalar":
            return yield* this.parseQuotedScalar();
          case "block-scalar":
            return yield* this.parseBlockScalar();
          case "plain-scalar":
            return yield* this.parsePlainScalar();
        }
      }
      *parseStream() {
        let line = this.getLine();
        if (line === null)
          return this.setNext("stream");
        if (line[0] === cst.BOM) {
          yield* this.pushCount(1);
          line = line.substring(1);
        }
        if (line[0] === "%") {
          let dirEnd = line.length;
          let cs = line.indexOf("#");
          while (cs !== -1) {
            const ch = line[cs - 1];
            if (ch === " " || ch === "	") {
              dirEnd = cs - 1;
              break;
            } else {
              cs = line.indexOf("#", cs + 1);
            }
          }
          while (true) {
            const ch = line[dirEnd - 1];
            if (ch === " " || ch === "	")
              dirEnd -= 1;
            else
              break;
          }
          const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
          yield* this.pushCount(line.length - n);
          this.pushNewline();
          return "stream";
        }
        if (this.atLineEnd()) {
          const sp = yield* this.pushSpaces(true);
          yield* this.pushCount(line.length - sp);
          yield* this.pushNewline();
          return "stream";
        }
        yield cst.DOCUMENT;
        return yield* this.parseLineStart();
      }
      *parseLineStart() {
        const ch = this.charAt(0);
        if (!ch && !this.atEnd)
          return this.setNext("line-start");
        if (ch === "-" || ch === ".") {
          if (!this.atEnd && !this.hasChars(4))
            return this.setNext("line-start");
          const s = this.peek(3);
          if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) {
            yield* this.pushCount(3);
            this.indentValue = 0;
            this.indentNext = 0;
            return s === "---" ? "doc" : "stream";
          }
        }
        this.indentValue = yield* this.pushSpaces(false);
        if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
          this.indentNext = this.indentValue;
        return yield* this.parseBlockStart();
      }
      *parseBlockStart() {
        const [ch0, ch1] = this.peek(2);
        if (!ch1 && !this.atEnd)
          return this.setNext("block-start");
        if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) {
          const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
          this.indentNext = this.indentValue + 1;
          this.indentValue += n;
          return yield* this.parseBlockStart();
        }
        return "doc";
      }
      *parseDocument() {
        yield* this.pushSpaces(true);
        const line = this.getLine();
        if (line === null)
          return this.setNext("doc");
        let n = yield* this.pushIndicators();
        switch (line[n]) {
          case "#":
            yield* this.pushCount(line.length - n);
          // fallthrough
          case void 0:
            yield* this.pushNewline();
            return yield* this.parseLineStart();
          case "{":
          case "[":
            yield* this.pushCount(1);
            this.flowKey = false;
            this.flowLevel = 1;
            return "flow";
          case "}":
          case "]":
            yield* this.pushCount(1);
            return "doc";
          case "*":
            yield* this.pushUntil(isNotAnchorChar);
            return "doc";
          case '"':
          case "'":
            return yield* this.parseQuotedScalar();
          case "|":
          case ">":
            n += yield* this.parseBlockScalarHeader();
            n += yield* this.pushSpaces(true);
            yield* this.pushCount(line.length - n);
            yield* this.pushNewline();
            return yield* this.parseBlockScalar();
          default:
            return yield* this.parsePlainScalar();
        }
      }
      *parseFlowCollection() {
        let nl, sp;
        let indent = -1;
        do {
          nl = yield* this.pushNewline();
          if (nl > 0) {
            sp = yield* this.pushSpaces(false);
            this.indentValue = indent = sp;
          } else {
            sp = 0;
          }
          sp += yield* this.pushSpaces(true);
        } while (nl + sp > 0);
        const line = this.getLine();
        if (line === null)
          return this.setNext("flow");
        if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) {
          const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}");
          if (!atFlowEndMarker) {
            this.flowLevel = 0;
            yield cst.FLOW_END;
            return yield* this.parseLineStart();
          }
        }
        let n = 0;
        while (line[n] === ",") {
          n += yield* this.pushCount(1);
          n += yield* this.pushSpaces(true);
          this.flowKey = false;
        }
        n += yield* this.pushIndicators();
        switch (line[n]) {
          case void 0:
            return "flow";
          case "#":
            yield* this.pushCount(line.length - n);
            return "flow";
          case "{":
          case "[":
            yield* this.pushCount(1);
            this.flowKey = false;
            this.flowLevel += 1;
            return "flow";
          case "}":
          case "]":
            yield* this.pushCount(1);
            this.flowKey = true;
            this.flowLevel -= 1;
            return this.flowLevel ? "flow" : "doc";
          case "*":
            yield* this.pushUntil(isNotAnchorChar);
            return "flow";
          case '"':
          case "'":
            this.flowKey = true;
            return yield* this.parseQuotedScalar();
          case ":": {
            const next = this.charAt(1);
            if (this.flowKey || isEmpty(next) || next === ",") {
              this.flowKey = false;
              yield* this.pushCount(1);
              yield* this.pushSpaces(true);
              return "flow";
            }
          }
          // fallthrough
          default:
            this.flowKey = false;
            return yield* this.parsePlainScalar();
        }
      }
      *parseQuotedScalar() {
        const quote = this.charAt(0);
        let end = this.buffer.indexOf(quote, this.pos + 1);
        if (quote === "'") {
          while (end !== -1 && this.buffer[end + 1] === "'")
            end = this.buffer.indexOf("'", end + 2);
        } else {
          while (end !== -1) {
            let n = 0;
            while (this.buffer[end - 1 - n] === "\\")
              n += 1;
            if (n % 2 === 0)
              break;
            end = this.buffer.indexOf('"', end + 1);
          }
        }
        const qb = this.buffer.substring(0, end);
        let nl = qb.indexOf("\n", this.pos);
        if (nl !== -1) {
          while (nl !== -1) {
            const cs = this.continueScalar(nl + 1);
            if (cs === -1)
              break;
            nl = qb.indexOf("\n", cs);
          }
          if (nl !== -1) {
            end = nl - (qb[nl - 1] === "\r" ? 2 : 1);
          }
        }
        if (end === -1) {
          if (!this.atEnd)
            return this.setNext("quoted-scalar");
          end = this.buffer.length;
        }
        yield* this.pushToIndex(end + 1, false);
        return this.flowLevel ? "flow" : "doc";
      }
      *parseBlockScalarHeader() {
        this.blockScalarIndent = -1;
        this.blockScalarKeep = false;
        let i = this.pos;
        while (true) {
          const ch = this.buffer[++i];
          if (ch === "+")
            this.blockScalarKeep = true;
          else if (ch > "0" && ch <= "9")
            this.blockScalarIndent = Number(ch) - 1;
          else if (ch !== "-")
            break;
        }
        return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#");
      }
      *parseBlockScalar() {
        let nl = this.pos - 1;
        let indent = 0;
        let ch;
        loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) {
          switch (ch) {
            case " ":
              indent += 1;
              break;
            case "\n":
              nl = i2;
              indent = 0;
              break;
            case "\r": {
              const next = this.buffer[i2 + 1];
              if (!next && !this.atEnd)
                return this.setNext("block-scalar");
              if (next === "\n")
                break;
            }
            // fallthrough
            default:
              break loop;
          }
        }
        if (!ch && !this.atEnd)
          return this.setNext("block-scalar");
        if (indent >= this.indentNext) {
          if (this.blockScalarIndent === -1)
            this.indentNext = indent;
          else {
            this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);
          }
          do {
            const cs = this.continueScalar(nl + 1);
            if (cs === -1)
              break;
            nl = this.buffer.indexOf("\n", cs);
          } while (nl !== -1);
          if (nl === -1) {
            if (!this.atEnd)
              return this.setNext("block-scalar");
            nl = this.buffer.length;
          }
        }
        let i = nl + 1;
        ch = this.buffer[i];
        while (ch === " ")
          ch = this.buffer[++i];
        if (ch === "	") {
          while (ch === "	" || ch === " " || ch === "\r" || ch === "\n")
            ch = this.buffer[++i];
          nl = i - 1;
        } else if (!this.blockScalarKeep) {
          do {
            let i2 = nl - 1;
            let ch2 = this.buffer[i2];
            if (ch2 === "\r")
              ch2 = this.buffer[--i2];
            const lastChar = i2;
            while (ch2 === " ")
              ch2 = this.buffer[--i2];
            if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar)
              nl = i2;
            else
              break;
          } while (true);
        }
        yield cst.SCALAR;
        yield* this.pushToIndex(nl + 1, true);
        return yield* this.parseLineStart();
      }
      *parsePlainScalar() {
        const inFlow = this.flowLevel > 0;
        let end = this.pos - 1;
        let i = this.pos - 1;
        let ch;
        while (ch = this.buffer[++i]) {
          if (ch === ":") {
            const next = this.buffer[i + 1];
            if (isEmpty(next) || inFlow && flowIndicatorChars.has(next))
              break;
            end = i;
          } else if (isEmpty(ch)) {
            let next = this.buffer[i + 1];
            if (ch === "\r") {
              if (next === "\n") {
                i += 1;
                ch = "\n";
                next = this.buffer[i + 1];
              } else
                end = i;
            }
            if (next === "#" || inFlow && flowIndicatorChars.has(next))
              break;
            if (ch === "\n") {
              const cs = this.continueScalar(i + 1);
              if (cs === -1)
                break;
              i = Math.max(i, cs - 2);
            }
          } else {
            if (inFlow && flowIndicatorChars.has(ch))
              break;
            end = i;
          }
        }
        if (!ch && !this.atEnd)
          return this.setNext("plain-scalar");
        yield cst.SCALAR;
        yield* this.pushToIndex(end + 1, true);
        return inFlow ? "flow" : "doc";
      }
      *pushCount(n) {
        if (n > 0) {
          yield this.buffer.substr(this.pos, n);
          this.pos += n;
          return n;
        }
        return 0;
      }
      *pushToIndex(i, allowEmpty) {
        const s = this.buffer.slice(this.pos, i);
        if (s) {
          yield s;
          this.pos += s.length;
          return s.length;
        } else if (allowEmpty)
          yield "";
        return 0;
      }
      *pushIndicators() {
        switch (this.charAt(0)) {
          case "!":
            return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
          case "&":
            return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
          case "-":
          // this is an error
          case "?":
          // this is an error outside flow collections
          case ":": {
            const inFlow = this.flowLevel > 0;
            const ch1 = this.charAt(1);
            if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) {
              if (!inFlow)
                this.indentNext = this.indentValue + 1;
              else if (this.flowKey)
                this.flowKey = false;
              return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
            }
          }
        }
        return 0;
      }
      *pushTag() {
        if (this.charAt(1) === "<") {
          let i = this.pos + 2;
          let ch = this.buffer[i];
          while (!isEmpty(ch) && ch !== ">")
            ch = this.buffer[++i];
          return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false);
        } else {
          let i = this.pos + 1;
          let ch = this.buffer[i];
          while (ch) {
            if (tagChars.has(ch))
              ch = this.buffer[++i];
            else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) {
              ch = this.buffer[i += 3];
            } else
              break;
          }
          return yield* this.pushToIndex(i, false);
        }
      }
      *pushNewline() {
        const ch = this.buffer[this.pos];
        if (ch === "\n")
          return yield* this.pushCount(1);
        else if (ch === "\r" && this.charAt(1) === "\n")
          return yield* this.pushCount(2);
        else
          return 0;
      }
      *pushSpaces(allowTabs) {
        let i = this.pos - 1;
        let ch;
        do {
          ch = this.buffer[++i];
        } while (ch === " " || allowTabs && ch === "	");
        const n = i - this.pos;
        if (n > 0) {
          yield this.buffer.substr(this.pos, n);
          this.pos = i;
        }
        return n;
      }
      *pushUntil(test) {
        let i = this.pos;
        let ch = this.buffer[i];
        while (!test(ch))
          ch = this.buffer[++i];
        return yield* this.pushToIndex(i, false);
      }
    };
    exports.Lexer = Lexer;
  }
});

// node_modules/yaml/dist/parse/line-counter.js
var require_line_counter = __commonJS({
  "node_modules/yaml/dist/parse/line-counter.js"(exports) {
    "use strict";
    var LineCounter = class {
      constructor() {
        this.lineStarts = [];
        this.addNewLine = (offset) => this.lineStarts.push(offset);
        this.linePos = (offset) => {
          let low = 0;
          let high = this.lineStarts.length;
          while (low < high) {
            const mid = low + high >> 1;
            if (this.lineStarts[mid] < offset)
              low = mid + 1;
            else
              high = mid;
          }
          if (this.lineStarts[low] === offset)
            return { line: low + 1, col: 1 };
          if (low === 0)
            return { line: 0, col: offset };
          const start = this.lineStarts[low - 1];
          return { line: low, col: offset - start + 1 };
        };
      }
    };
    exports.LineCounter = LineCounter;
  }
});

// node_modules/yaml/dist/parse/parser.js
var require_parser = __commonJS({
  "node_modules/yaml/dist/parse/parser.js"(exports) {
    "use strict";
    var node_process = __require("process");
    var cst = require_cst();
    var lexer = require_lexer();
    function includesToken(list, type) {
      for (let i = 0; i < list.length; ++i)
        if (list[i].type === type)
          return true;
      return false;
    }
    function findNonEmptyIndex(list) {
      for (let i = 0; i < list.length; ++i) {
        switch (list[i].type) {
          case "space":
          case "comment":
          case "newline":
            break;
          default:
            return i;
        }
      }
      return -1;
    }
    function isFlowToken(token) {
      switch (token?.type) {
        case "alias":
        case "scalar":
        case "single-quoted-scalar":
        case "double-quoted-scalar":
        case "flow-collection":
          return true;
        default:
          return false;
      }
    }
    function getPrevProps(parent) {
      switch (parent.type) {
        case "document":
          return parent.start;
        case "block-map": {
          const it = parent.items[parent.items.length - 1];
          return it.sep ?? it.start;
        }
        case "block-seq":
          return parent.items[parent.items.length - 1].start;
        /* istanbul ignore next should not happen */
        default:
          return [];
      }
    }
    function getFirstKeyStartProps(prev) {
      if (prev.length === 0)
        return [];
      let i = prev.length;
      loop: while (--i >= 0) {
        switch (prev[i].type) {
          case "doc-start":
          case "explicit-key-ind":
          case "map-value-ind":
          case "seq-item-ind":
          case "newline":
            break loop;
        }
      }
      while (prev[++i]?.type === "space") {
      }
      return prev.splice(i, prev.length);
    }
    function fixFlowSeqItems(fc) {
      if (fc.start.type === "flow-seq-start") {
        for (const it of fc.items) {
          if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) {
            if (it.key)
              it.value = it.key;
            delete it.key;
            if (isFlowToken(it.value)) {
              if (it.value.end)
                Array.prototype.push.apply(it.value.end, it.sep);
              else
                it.value.end = it.sep;
            } else
              Array.prototype.push.apply(it.start, it.sep);
            delete it.sep;
          }
        }
      }
    }
    var Parser = class {
      /**
       * @param onNewLine - If defined, called separately with the start position of
       *   each new line (in `parse()`, including the start of input).
       */
      constructor(onNewLine) {
        this.atNewLine = true;
        this.atScalar = false;
        this.indent = 0;
        this.offset = 0;
        this.onKeyLine = false;
        this.stack = [];
        this.source = "";
        this.type = "";
        this.lexer = new lexer.Lexer();
        this.onNewLine = onNewLine;
      }
      /**
       * Parse `source` as a YAML stream.
       * If `incomplete`, a part of the last line may be left as a buffer for the next call.
       *
       * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.
       *
       * @returns A generator of tokens representing each directive, document, and other structure.
       */
      *parse(source, incomplete = false) {
        if (this.onNewLine && this.offset === 0)
          this.onNewLine(0);
        for (const lexeme of this.lexer.lex(source, incomplete))
          yield* this.next(lexeme);
        if (!incomplete)
          yield* this.end();
      }
      /**
       * Advance the parser by the `source` of one lexical token.
       */
      *next(source) {
        this.source = source;
        if (node_process.env.LOG_TOKENS)
          console.log("|", cst.prettyToken(source));
        if (this.atScalar) {
          this.atScalar = false;
          yield* this.step();
          this.offset += source.length;
          return;
        }
        const type = cst.tokenType(source);
        if (!type) {
          const message = `Not a YAML token: ${source}`;
          yield* this.pop({ type: "error", offset: this.offset, message, source });
          this.offset += source.length;
        } else if (type === "scalar") {
          this.atNewLine = false;
          this.atScalar = true;
          this.type = "scalar";
        } else {
          this.type = type;
          yield* this.step();
          switch (type) {
            case "newline":
              this.atNewLine = true;
              this.indent = 0;
              if (this.onNewLine)
                this.onNewLine(this.offset + source.length);
              break;
            case "space":
              if (this.atNewLine && source[0] === " ")
                this.indent += source.length;
              break;
            case "explicit-key-ind":
            case "map-value-ind":
            case "seq-item-ind":
              if (this.atNewLine)
                this.indent += source.length;
              break;
            case "doc-mode":
            case "flow-error-end":
              return;
            default:
              this.atNewLine = false;
          }
          this.offset += source.length;
        }
      }
      /** Call at end of input to push out any remaining constructions */
      *end() {
        while (this.stack.length > 0)
          yield* this.pop();
      }
      get sourceToken() {
        const st = {
          type: this.type,
          offset: this.offset,
          indent: this.indent,
          source: this.source
        };
        return st;
      }
      *step() {
        const top = this.peek(1);
        if (this.type === "doc-end" && top?.type !== "doc-end") {
          while (this.stack.length > 0)
            yield* this.pop();
          this.stack.push({
            type: "doc-end",
            offset: this.offset,
            source: this.source
          });
          return;
        }
        if (!top)
          return yield* this.stream();
        switch (top.type) {
          case "document":
            return yield* this.document(top);
          case "alias":
          case "scalar":
          case "single-quoted-scalar":
          case "double-quoted-scalar":
            return yield* this.scalar(top);
          case "block-scalar":
            return yield* this.blockScalar(top);
          case "block-map":
            return yield* this.blockMap(top);
          case "block-seq":
            return yield* this.blockSequence(top);
          case "flow-collection":
            return yield* this.flowCollection(top);
          case "doc-end":
            return yield* this.documentEnd(top);
        }
        yield* this.pop();
      }
      peek(n) {
        return this.stack[this.stack.length - n];
      }
      *pop(error) {
        const token = error ?? this.stack.pop();
        if (!token) {
          const message = "Tried to pop an empty stack";
          yield { type: "error", offset: this.offset, source: "", message };
        } else if (this.stack.length === 0) {
          yield token;
        } else {
          const top = this.peek(1);
          if (token.type === "block-scalar") {
            token.indent = "indent" in top ? top.indent : 0;
          } else if (token.type === "flow-collection" && top.type === "document") {
            token.indent = 0;
          }
          if (token.type === "flow-collection")
            fixFlowSeqItems(token);
          switch (top.type) {
            case "document":
              top.value = token;
              break;
            case "block-scalar":
              top.props.push(token);
              break;
            case "block-map": {
              const it = top.items[top.items.length - 1];
              if (it.value) {
                top.items.push({ start: [], key: token, sep: [] });
                this.onKeyLine = true;
                return;
              } else if (it.sep) {
                it.value = token;
              } else {
                Object.assign(it, { key: token, sep: [] });
                this.onKeyLine = !it.explicitKey;
                return;
              }
              break;
            }
            case "block-seq": {
              const it = top.items[top.items.length - 1];
              if (it.value)
                top.items.push({ start: [], value: token });
              else
                it.value = token;
              break;
            }
            case "flow-collection": {
              const it = top.items[top.items.length - 1];
              if (!it || it.value)
                top.items.push({ start: [], key: token, sep: [] });
              else if (it.sep)
                it.value = token;
              else
                Object.assign(it, { key: token, sep: [] });
              return;
            }
            /* istanbul ignore next should not happen */
            default:
              yield* this.pop();
              yield* this.pop(token);
          }
          if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) {
            const last = token.items[token.items.length - 1];
            if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) {
              if (top.type === "document")
                top.end = last.start;
              else
                top.items.push({ start: last.start });
              token.items.splice(-1, 1);
            }
          }
        }
      }
      *stream() {
        switch (this.type) {
          case "directive-line":
            yield { type: "directive", offset: this.offset, source: this.source };
            return;
          case "byte-order-mark":
          case "space":
          case "comment":
          case "newline":
            yield this.sourceToken;
            return;
          case "doc-mode":
          case "doc-start": {
            const doc = {
              type: "document",
              offset: this.offset,
              start: []
            };
            if (this.type === "doc-start")
              doc.start.push(this.sourceToken);
            this.stack.push(doc);
            return;
          }
        }
        yield {
          type: "error",
          offset: this.offset,
          message: `Unexpected ${this.type} token in YAML stream`,
          source: this.source
        };
      }
      *document(doc) {
        if (doc.value)
          return yield* this.lineEnd(doc);
        switch (this.type) {
          case "doc-start": {
            if (findNonEmptyIndex(doc.start) !== -1) {
              yield* this.pop();
              yield* this.step();
            } else
              doc.start.push(this.sourceToken);
            return;
          }
          case "anchor":
          case "tag":
          case "space":
          case "comment":
          case "newline":
            doc.start.push(this.sourceToken);
            return;
        }
        const bv = this.startBlockValue(doc);
        if (bv)
          this.stack.push(bv);
        else {
          yield {
            type: "error",
            offset: this.offset,
            message: `Unexpected ${this.type} token in YAML document`,
            source: this.source
          };
        }
      }
      *scalar(scalar) {
        if (this.type === "map-value-ind") {
          const prev = getPrevProps(this.peek(2));
          const start = getFirstKeyStartProps(prev);
          let sep;
          if (scalar.end) {
            sep = scalar.end;
            sep.push(this.sourceToken);
            delete scalar.end;
          } else
            sep = [this.sourceToken];
          const map = {
            type: "block-map",
            offset: scalar.offset,
            indent: scalar.indent,
            items: [{ start, key: scalar, sep }]
          };
          this.onKeyLine = true;
          this.stack[this.stack.length - 1] = map;
        } else
          yield* this.lineEnd(scalar);
      }
      *blockScalar(scalar) {
        switch (this.type) {
          case "space":
          case "comment":
          case "newline":
            scalar.props.push(this.sourceToken);
            return;
          case "scalar":
            scalar.source = this.source;
            this.atNewLine = true;
            this.indent = 0;
            if (this.onNewLine) {
              let nl = this.source.indexOf("\n") + 1;
              while (nl !== 0) {
                this.onNewLine(this.offset + nl);
                nl = this.source.indexOf("\n", nl) + 1;
              }
            }
            yield* this.pop();
            break;
          /* istanbul ignore next should not happen */
          default:
            yield* this.pop();
            yield* this.step();
        }
      }
      *blockMap(map) {
        const it = map.items[map.items.length - 1];
        switch (this.type) {
          case "newline":
            this.onKeyLine = false;
            if (it.value) {
              const end = "end" in it.value ? it.value.end : void 0;
              const last = Array.isArray(end) ? end[end.length - 1] : void 0;
              if (last?.type === "comment")
                end?.push(this.sourceToken);
              else
                map.items.push({ start: [this.sourceToken] });
            } else if (it.sep) {
              it.sep.push(this.sourceToken);
            } else {
              it.start.push(this.sourceToken);
            }
            return;
          case "space":
          case "comment":
            if (it.value) {
              map.items.push({ start: [this.sourceToken] });
            } else if (it.sep) {
              it.sep.push(this.sourceToken);
            } else {
              if (this.atIndentedComment(it.start, map.indent)) {
                const prev = map.items[map.items.length - 2];
                const end = prev?.value?.end;
                if (Array.isArray(end)) {
                  Array.prototype.push.apply(end, it.start);
                  end.push(this.sourceToken);
                  map.items.pop();
                  return;
                }
              }
              it.start.push(this.sourceToken);
            }
            return;
        }
        if (this.indent >= map.indent) {
          const atMapIndent = !this.onKeyLine && this.indent === map.indent;
          const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind";
          let start = [];
          if (atNextItem && it.sep && !it.value) {
            const nl = [];
            for (let i = 0; i < it.sep.length; ++i) {
              const st = it.sep[i];
              switch (st.type) {
                case "newline":
                  nl.push(i);
                  break;
                case "space":
                  break;
                case "comment":
                  if (st.indent > map.indent)
                    nl.length = 0;
                  break;
                default:
                  nl.length = 0;
              }
            }
            if (nl.length >= 2)
              start = it.sep.splice(nl[1]);
          }
          switch (this.type) {
            case "anchor":
            case "tag":
              if (atNextItem || it.value) {
                start.push(this.sourceToken);
                map.items.push({ start });
                this.onKeyLine = true;
              } else if (it.sep) {
                it.sep.push(this.sourceToken);
              } else {
                it.start.push(this.sourceToken);
              }
              return;
            case "explicit-key-ind":
              if (!it.sep && !it.explicitKey) {
                it.start.push(this.sourceToken);
                it.explicitKey = true;
              } else if (atNextItem || it.value) {
                start.push(this.sourceToken);
                map.items.push({ start, explicitKey: true });
              } else {
                this.stack.push({
                  type: "block-map",
                  offset: this.offset,
                  indent: this.indent,
                  items: [{ start: [this.sourceToken], explicitKey: true }]
                });
              }
              this.onKeyLine = true;
              return;
            case "map-value-ind":
              if (it.explicitKey) {
                if (!it.sep) {
                  if (includesToken(it.start, "newline")) {
                    Object.assign(it, { key: null, sep: [this.sourceToken] });
                  } else {
                    const start2 = getFirstKeyStartProps(it.start);
                    this.stack.push({
                      type: "block-map",
                      offset: this.offset,
                      indent: this.indent,
                      items: [{ start: start2, key: null, sep: [this.sourceToken] }]
                    });
                  }
                } else if (it.value) {
                  map.items.push({ start: [], key: null, sep: [this.sourceToken] });
                } else if (includesToken(it.sep, "map-value-ind")) {
                  this.stack.push({
                    type: "block-map",
                    offset: this.offset,
                    indent: this.indent,
                    items: [{ start, key: null, sep: [this.sourceToken] }]
                  });
                } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
                  const start2 = getFirstKeyStartProps(it.start);
                  const key = it.key;
                  const sep = it.sep;
                  sep.push(this.sourceToken);
                  delete it.key;
                  delete it.sep;
                  this.stack.push({
                    type: "block-map",
                    offset: this.offset,
                    indent: this.indent,
                    items: [{ start: start2, key, sep }]
                  });
                } else if (start.length > 0) {
                  it.sep = it.sep.concat(start, this.sourceToken);
                } else {
                  it.sep.push(this.sourceToken);
                }
              } else {
                if (!it.sep) {
                  Object.assign(it, { key: null, sep: [this.sourceToken] });
                } else if (it.value || atNextItem) {
                  map.items.push({ start, key: null, sep: [this.sourceToken] });
                } else if (includesToken(it.sep, "map-value-ind")) {
                  this.stack.push({
                    type: "block-map",
                    offset: this.offset,
                    indent: this.indent,
                    items: [{ start: [], key: null, sep: [this.sourceToken] }]
                  });
                } else {
                  it.sep.push(this.sourceToken);
                }
              }
              this.onKeyLine = true;
              return;
            case "alias":
            case "scalar":
            case "single-quoted-scalar":
            case "double-quoted-scalar": {
              const fs3 = this.flowScalar(this.type);
              if (atNextItem || it.value) {
                map.items.push({ start, key: fs3, sep: [] });
                this.onKeyLine = true;
              } else if (it.sep) {
                this.stack.push(fs3);
              } else {
                Object.assign(it, { key: fs3, sep: [] });
                this.onKeyLine = true;
              }
              return;
            }
            default: {
              const bv = this.startBlockValue(map);
              if (bv) {
                if (bv.type === "block-seq") {
                  if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) {
                    yield* this.pop({
                      type: "error",
                      offset: this.offset,
                      message: "Unexpected block-seq-ind on same line with key",
                      source: this.source
                    });
                    return;
                  }
                } else if (atMapIndent) {
                  map.items.push({ start });
                }
                this.stack.push(bv);
                return;
              }
            }
          }
        }
        yield* this.pop();
        yield* this.step();
      }
      *blockSequence(seq) {
        const it = seq.items[seq.items.length - 1];
        switch (this.type) {
          case "newline":
            if (it.value) {
              const end = "end" in it.value ? it.value.end : void 0;
              const last = Array.isArray(end) ? end[end.length - 1] : void 0;
              if (last?.type === "comment")
                end?.push(this.sourceToken);
              else
                seq.items.push({ start: [this.sourceToken] });
            } else
              it.start.push(this.sourceToken);
            return;
          case "space":
          case "comment":
            if (it.value)
              seq.items.push({ start: [this.sourceToken] });
            else {
              if (this.atIndentedComment(it.start, seq.indent)) {
                const prev = seq.items[seq.items.length - 2];
                const end = prev?.value?.end;
                if (Array.isArray(end)) {
                  Array.prototype.push.apply(end, it.start);
                  end.push(this.sourceToken);
                  seq.items.pop();
                  return;
                }
              }
              it.start.push(this.sourceToken);
            }
            return;
          case "anchor":
          case "tag":
            if (it.value || this.indent <= seq.indent)
              break;
            it.start.push(this.sourceToken);
            return;
          case "seq-item-ind":
            if (this.indent !== seq.indent)
              break;
            if (it.value || includesToken(it.start, "seq-item-ind"))
              seq.items.push({ start: [this.sourceToken] });
            else
              it.start.push(this.sourceToken);
            return;
        }
        if (this.indent > seq.indent) {
          const bv = this.startBlockValue(seq);
          if (bv) {
            this.stack.push(bv);
            return;
          }
        }
        yield* this.pop();
        yield* this.step();
      }
      *flowCollection(fc) {
        const it = fc.items[fc.items.length - 1];
        if (this.type === "flow-error-end") {
          let top;
          do {
            yield* this.pop();
            top = this.peek(1);
          } while (top?.type === "flow-collection");
        } else if (fc.end.length === 0) {
          switch (this.type) {
            case "comma":
            case "explicit-key-ind":
              if (!it || it.sep)
                fc.items.push({ start: [this.sourceToken] });
              else
                it.start.push(this.sourceToken);
              return;
            case "map-value-ind":
              if (!it || it.value)
                fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
              else if (it.sep)
                it.sep.push(this.sourceToken);
              else
                Object.assign(it, { key: null, sep: [this.sourceToken] });
              return;
            case "space":
            case "comment":
            case "newline":
            case "anchor":
            case "tag":
              if (!it || it.value)
                fc.items.push({ start: [this.sourceToken] });
              else if (it.sep)
                it.sep.push(this.sourceToken);
              else
                it.start.push(this.sourceToken);
              return;
            case "alias":
            case "scalar":
            case "single-quoted-scalar":
            case "double-quoted-scalar": {
              const fs3 = this.flowScalar(this.type);
              if (!it || it.value)
                fc.items.push({ start: [], key: fs3, sep: [] });
              else if (it.sep)
                this.stack.push(fs3);
              else
                Object.assign(it, { key: fs3, sep: [] });
              return;
            }
            case "flow-map-end":
            case "flow-seq-end":
              fc.end.push(this.sourceToken);
              return;
          }
          const bv = this.startBlockValue(fc);
          if (bv)
            this.stack.push(bv);
          else {
            yield* this.pop();
            yield* this.step();
          }
        } else {
          const parent = this.peek(2);
          if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) {
            yield* this.pop();
            yield* this.step();
          } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") {
            const prev = getPrevProps(parent);
            const start = getFirstKeyStartProps(prev);
            fixFlowSeqItems(fc);
            const sep = fc.end.splice(1, fc.end.length);
            sep.push(this.sourceToken);
            const map = {
              type: "block-map",
              offset: fc.offset,
              indent: fc.indent,
              items: [{ start, key: fc, sep }]
            };
            this.onKeyLine = true;
            this.stack[this.stack.length - 1] = map;
          } else {
            yield* this.lineEnd(fc);
          }
        }
      }
      flowScalar(type) {
        if (this.onNewLine) {
          let nl = this.source.indexOf("\n") + 1;
          while (nl !== 0) {
            this.onNewLine(this.offset + nl);
            nl = this.source.indexOf("\n", nl) + 1;
          }
        }
        return {
          type,
          offset: this.offset,
          indent: this.indent,
          source: this.source
        };
      }
      startBlockValue(parent) {
        switch (this.type) {
          case "alias":
          case "scalar":
          case "single-quoted-scalar":
          case "double-quoted-scalar":
            return this.flowScalar(this.type);
          case "block-scalar-header":
            return {
              type: "block-scalar",
              offset: this.offset,
              indent: this.indent,
              props: [this.sourceToken],
              source: ""
            };
          case "flow-map-start":
          case "flow-seq-start":
            return {
              type: "flow-collection",
              offset: this.offset,
              indent: this.indent,
              start: this.sourceToken,
              items: [],
              end: []
            };
          case "seq-item-ind":
            return {
              type: "block-seq",
              offset: this.offset,
              indent: this.indent,
              items: [{ start: [this.sourceToken] }]
            };
          case "explicit-key-ind": {
            this.onKeyLine = true;
            const prev = getPrevProps(parent);
            const start = getFirstKeyStartProps(prev);
            start.push(this.sourceToken);
            return {
              type: "block-map",
              offset: this.offset,
              indent: this.indent,
              items: [{ start, explicitKey: true }]
            };
          }
          case "map-value-ind": {
            this.onKeyLine = true;
            const prev = getPrevProps(parent);
            const start = getFirstKeyStartProps(prev);
            return {
              type: "block-map",
              offset: this.offset,
              indent: this.indent,
              items: [{ start, key: null, sep: [this.sourceToken] }]
            };
          }
        }
        return null;
      }
      atIndentedComment(start, indent) {
        if (this.type !== "comment")
          return false;
        if (this.indent <= indent)
          return false;
        return start.every((st) => st.type === "newline" || st.type === "space");
      }
      *documentEnd(docEnd) {
        if (this.type !== "doc-mode") {
          if (docEnd.end)
            docEnd.end.push(this.sourceToken);
          else
            docEnd.end = [this.sourceToken];
          if (this.type === "newline")
            yield* this.pop();
        }
      }
      *lineEnd(token) {
        switch (this.type) {
          case "comma":
          case "doc-start":
          case "doc-end":
          case "flow-seq-end":
          case "flow-map-end":
          case "map-value-ind":
            yield* this.pop();
            yield* this.step();
            break;
          case "newline":
            this.onKeyLine = false;
          // fallthrough
          case "space":
          case "comment":
          default:
            if (token.end)
              token.end.push(this.sourceToken);
            else
              token.end = [this.sourceToken];
            if (this.type === "newline")
              yield* this.pop();
        }
      }
    };
    exports.Parser = Parser;
  }
});

// node_modules/yaml/dist/public-api.js
var require_public_api = __commonJS({
  "node_modules/yaml/dist/public-api.js"(exports) {
    "use strict";
    var composer = require_composer();
    var Document = require_Document();
    var errors = require_errors();
    var log = require_log();
    var identity = require_identity();
    var lineCounter = require_line_counter();
    var parser = require_parser();
    function parseOptions(options) {
      const prettyErrors = options.prettyErrors !== false;
      const lineCounter$1 = options.lineCounter || prettyErrors && new lineCounter.LineCounter() || null;
      return { lineCounter: lineCounter$1, prettyErrors };
    }
    function parseAllDocuments(source, options = {}) {
      const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
      const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
      const composer$1 = new composer.Composer(options);
      const docs = Array.from(composer$1.compose(parser$1.parse(source)));
      if (prettyErrors && lineCounter2)
        for (const doc of docs) {
          doc.errors.forEach(errors.prettifyError(source, lineCounter2));
          doc.warnings.forEach(errors.prettifyError(source, lineCounter2));
        }
      if (docs.length > 0)
        return docs;
      return Object.assign([], { empty: true }, composer$1.streamInfo());
    }
    function parseDocument(source, options = {}) {
      const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
      const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
      const composer$1 = new composer.Composer(options);
      let doc = null;
      for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {
        if (!doc)
          doc = _doc;
        else if (doc.options.logLevel !== "silent") {
          doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()"));
          break;
        }
      }
      if (prettyErrors && lineCounter2) {
        doc.errors.forEach(errors.prettifyError(source, lineCounter2));
        doc.warnings.forEach(errors.prettifyError(source, lineCounter2));
      }
      return doc;
    }
    function parse(src, reviver, options) {
      let _reviver = void 0;
      if (typeof reviver === "function") {
        _reviver = reviver;
      } else if (options === void 0 && reviver && typeof reviver === "object") {
        options = reviver;
      }
      const doc = parseDocument(src, options);
      if (!doc)
        return null;
      doc.warnings.forEach((warning) => log.warn(doc.options.logLevel, warning));
      if (doc.errors.length > 0) {
        if (doc.options.logLevel !== "silent")
          throw doc.errors[0];
        else
          doc.errors = [];
      }
      return doc.toJS(Object.assign({ reviver: _reviver }, options));
    }
    function stringify(value, replacer, options) {
      let _replacer = null;
      if (typeof replacer === "function" || Array.isArray(replacer)) {
        _replacer = replacer;
      } else if (options === void 0 && replacer) {
        options = replacer;
      }
      if (typeof options === "string")
        options = options.length;
      if (typeof options === "number") {
        const indent = Math.round(options);
        options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent };
      }
      if (value === void 0) {
        const { keepUndefined } = options ?? replacer ?? {};
        if (!keepUndefined)
          return void 0;
      }
      if (identity.isDocument(value) && !_replacer)
        return value.toString(options);
      return new Document.Document(value, _replacer, options).toString(options);
    }
    exports.parse = parse;
    exports.parseAllDocuments = parseAllDocuments;
    exports.parseDocument = parseDocument;
    exports.stringify = stringify;
  }
});

// node_modules/yaml/dist/index.js
var require_dist = __commonJS({
  "node_modules/yaml/dist/index.js"(exports) {
    "use strict";
    var composer = require_composer();
    var Document = require_Document();
    var Schema = require_Schema();
    var errors = require_errors();
    var Alias = require_Alias();
    var identity = require_identity();
    var Pair = require_Pair();
    var Scalar = require_Scalar();
    var YAMLMap = require_YAMLMap();
    var YAMLSeq = require_YAMLSeq();
    var cst = require_cst();
    var lexer = require_lexer();
    var lineCounter = require_line_counter();
    var parser = require_parser();
    var publicApi = require_public_api();
    var visit = require_visit();
    exports.Composer = composer.Composer;
    exports.Document = Document.Document;
    exports.Schema = Schema.Schema;
    exports.YAMLError = errors.YAMLError;
    exports.YAMLParseError = errors.YAMLParseError;
    exports.YAMLWarning = errors.YAMLWarning;
    exports.Alias = Alias.Alias;
    exports.isAlias = identity.isAlias;
    exports.isCollection = identity.isCollection;
    exports.isDocument = identity.isDocument;
    exports.isMap = identity.isMap;
    exports.isNode = identity.isNode;
    exports.isPair = identity.isPair;
    exports.isScalar = identity.isScalar;
    exports.isSeq = identity.isSeq;
    exports.Pair = Pair.Pair;
    exports.Scalar = Scalar.Scalar;
    exports.YAMLMap = YAMLMap.YAMLMap;
    exports.YAMLSeq = YAMLSeq.YAMLSeq;
    exports.CST = cst;
    exports.Lexer = lexer.Lexer;
    exports.LineCounter = lineCounter.LineCounter;
    exports.Parser = parser.Parser;
    exports.parse = publicApi.parse;
    exports.parseAllDocuments = publicApi.parseAllDocuments;
    exports.parseDocument = publicApi.parseDocument;
    exports.stringify = publicApi.stringify;
    exports.visit = visit.visit;
    exports.visitAsync = visit.visitAsync;
  }
});

// src/store/migrations.ts
function runMigrations(db, logger) {
  const log = logger ?? { warn: (msg) => console.warn(`[migrations] ${msg}`) };
  try {
    db.exec(`
      CREATE TABLE IF NOT EXISTS _schema_migrations (
        version INTEGER PRIMARY KEY,
        applied_at INTEGER NOT NULL
      )
    `);
  } catch (e) {
    log.warn(`failed to create migrations table: ${e.message}`);
    return;
  }
  const applied = new Set(
    db.prepare("SELECT version FROM _schema_migrations").all().map((r) => r.version)
  );
  const migrations = [
    {
      version: 1,
      up: (db2) => {
        db2.exec(`
          CREATE TABLE IF NOT EXISTS workflows (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            description TEXT NOT NULL DEFAULT '',
            state TEXT NOT NULL DEFAULT 'idle',
            current_steps TEXT NOT NULL DEFAULT '[]',
            created_at INTEGER NOT NULL,
            updated_at INTEGER NOT NULL,
            metadata TEXT NOT NULL DEFAULT '{}'
          );

          CREATE TABLE IF NOT EXISTS workflow_steps (
            workflow_id TEXT NOT NULL,
            step_id TEXT NOT NULL,
            name TEXT NOT NULL,
            discipline TEXT NOT NULL,
            dependencies TEXT NOT NULL DEFAULT '[]',
            config TEXT NOT NULL DEFAULT '{}',
            state TEXT NOT NULL DEFAULT 'pending',
            result TEXT,
            error TEXT,
            started_at INTEGER,
            completed_at INTEGER,
            PRIMARY KEY (workflow_id, step_id),
            FOREIGN KEY (workflow_id) REFERENCES workflows(id) ON DELETE CASCADE
          );

          CREATE TABLE IF NOT EXISTS dag_edges (
            workflow_id TEXT NOT NULL,
            edge_from TEXT NOT NULL,
            edge_to TEXT NOT NULL,
            PRIMARY KEY (workflow_id, edge_from, edge_to),
            FOREIGN KEY (workflow_id) REFERENCES workflows(id) ON DELETE CASCADE
          );

          CREATE TABLE IF NOT EXISTS dag_layers (
            workflow_id TEXT NOT NULL,
            layer_index INTEGER NOT NULL,
            step_id TEXT NOT NULL,
            PRIMARY KEY (workflow_id, layer_index, step_id),
            FOREIGN KEY (workflow_id) REFERENCES workflows(id) ON DELETE CASCADE
          );

          CREATE TABLE IF NOT EXISTS episodic_memory (
            id TEXT PRIMARY KEY,
            namespace TEXT NOT NULL DEFAULT 'default',
            workflow_id TEXT NOT NULL,
            workflow_name TEXT NOT NULL,
            final_state TEXT NOT NULL,
            duration_ms INTEGER NOT NULL DEFAULT 0,
            step_summary TEXT NOT NULL DEFAULT '[]',
            compressed INTEGER NOT NULL DEFAULT 0,
            raw_data TEXT,
            source TEXT NOT NULL DEFAULT 'workflow_execution',
            tags TEXT NOT NULL DEFAULT '[]',
            created_at INTEGER NOT NULL,
            updated_at INTEGER NOT NULL
          );

          CREATE TABLE IF NOT EXISTS evolved_templates (
            id TEXT PRIMARY KEY,
            type TEXT NOT NULL CHECK(type IN ('workflow', 'skill')),
            name TEXT NOT NULL,
            description TEXT NOT NULL DEFAULT '',
            steps TEXT,
            pattern TEXT,
            sources TEXT NOT NULL DEFAULT '[]',
            use_count INTEGER NOT NULL DEFAULT 0,
            success_count INTEGER NOT NULL DEFAULT 0,
            fail_count INTEGER NOT NULL DEFAULT 0,
            last_used_at INTEGER,
            last_iterated_at INTEGER,
            quality_score REAL NOT NULL DEFAULT 0.5,
            version INTEGER NOT NULL DEFAULT 1,
            tags TEXT NOT NULL DEFAULT '[]',
            created_at INTEGER NOT NULL,
            updated_at INTEGER NOT NULL
          );
          CREATE INDEX IF NOT EXISTS idx_evolved_type ON evolved_templates(type);
          CREATE INDEX IF NOT EXISTS idx_evolved_quality ON evolved_templates(quality_score);
        `);
        db2.prepare("INSERT OR IGNORE INTO _schema_migrations (version, applied_at) VALUES (?, ?)").run(1, Date.now());
      }
    },
    {
      version: 2,
      up: (db2) => {
        const columns = [
          ["triggers", "TEXT NOT NULL DEFAULT '[]'"],
          ["scope", "TEXT NOT NULL DEFAULT 'general'"],
          ["prerequisites", "TEXT NOT NULL DEFAULT '[]'"],
          ["tools_required", "TEXT NOT NULL DEFAULT '[]'"],
          ["tools_optional", "TEXT NOT NULL DEFAULT '[]'"],
          ["disciplines_used", "TEXT NOT NULL DEFAULT '[]'"],
          ["estimated_steps", "INTEGER NOT NULL DEFAULT 0"],
          ["estimated_duration", "TEXT NOT NULL DEFAULT ''"],
          ["examples", "TEXT NOT NULL DEFAULT '[]'"]
        ];
        for (const [col, def] of columns) {
          try {
            db2.exec(`ALTER TABLE evolved_templates ADD COLUMN ${col} ${def}`);
          } catch (e) {
            if (!e.message?.includes("duplicate column name")) {
              log.warn(`migration v2: failed to add column ${col}: ${e.message}`);
            }
          }
        }
        db2.prepare("INSERT OR IGNORE INTO _schema_migrations (version, applied_at) VALUES (?, ?)").run(2, Date.now());
      }
    },
    {
      version: 3,
      up: (db2) => {
        db2.exec(`
          CREATE TABLE IF NOT EXISTS skills_inventory (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            description TEXT NOT NULL DEFAULT '',
            location TEXT NOT NULL,
            triggers TEXT NOT NULL DEFAULT '[]',
            tools TEXT NOT NULL DEFAULT '[]',
            examples TEXT NOT NULL DEFAULT '[]',
            tags TEXT NOT NULL DEFAULT '[]',
            last_scanned_at INTEGER NOT NULL,
            version TEXT NOT NULL DEFAULT '1.0.0',
            installed_at INTEGER NOT NULL,
            updated_at INTEGER NOT NULL
          );
          CREATE TABLE IF NOT EXISTS skill_usage (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            skill_id TEXT NOT NULL,
            tool_name TEXT NOT NULL,
            success INTEGER NOT NULL DEFAULT 1,
            duration_ms INTEGER,
            called_at INTEGER NOT NULL
          );
          CREATE INDEX IF NOT EXISTS idx_skill_usage_skill ON skill_usage(skill_id);
          CREATE INDEX IF NOT EXISTS idx_skill_usage_time ON skill_usage(called_at);
        `);
        db2.prepare("INSERT OR IGNORE INTO _schema_migrations (version, applied_at) VALUES (?, ?)").run(3, Date.now());
      }
    },
    {
      version: 4,
      up: (db2) => {
        db2.exec(`
          CREATE TABLE IF NOT EXISTS skill_insights (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            type TEXT NOT NULL,
            skill_a TEXT,
            skill_b TEXT,
            confidence REAL NOT NULL DEFAULT 0.5,
            description TEXT NOT NULL DEFAULT '',
            recommendation TEXT NOT NULL DEFAULT '',
            discovered_at INTEGER NOT NULL
          );
        `);
        db2.prepare("INSERT OR IGNORE INTO _schema_migrations (version, applied_at) VALUES (?, ?)").run(4, Date.now());
      }
    },
    {
      version: 5,
      up: (db2) => {
        db2.exec(`
          CREATE TABLE IF NOT EXISTS mcp_servers (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            description TEXT NOT NULL DEFAULT '',
            location TEXT NOT NULL,
            tools TEXT NOT NULL DEFAULT '[]',
            enabled INTEGER NOT NULL DEFAULT 1,
            last_seen_at INTEGER NOT NULL,
            discovered_at INTEGER NOT NULL
          );
          CREATE TABLE IF NOT EXISTS mcp_usage (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            server_id TEXT NOT NULL,
            tool_name TEXT NOT NULL,
            success INTEGER NOT NULL DEFAULT 1,
            duration_ms INTEGER,
            called_at INTEGER NOT NULL
          );
          CREATE INDEX IF NOT EXISTS idx_mcp_usage_server ON mcp_usage(server_id);
          CREATE INDEX IF NOT EXISTS idx_mcp_usage_time ON mcp_usage(called_at);
        `);
        db2.prepare("INSERT OR IGNORE INTO _schema_migrations (version, applied_at) VALUES (?, ?)").run(5, Date.now());
      }
    },
    {
      version: 6,
      up: (db2) => {
        try {
          db2.exec("ALTER TABLE episodic_memory ADD COLUMN condensed_results TEXT");
        } catch (e) {
          if (!e.message?.includes("duplicate column name")) {
            log.warn(`migration v6: add column failed: ${e.message}`);
          }
        }
        try {
          db2.exec(`
            CREATE VIRTUAL TABLE IF NOT EXISTS episodic_fts USING fts5(
              content,
              tokenize='unicode61'
            );
          `);
        } catch (e) {
          log.warn(`migration v6 FTS5 failed (may not be supported): ${e.message}`);
        }
        db2.prepare("INSERT OR IGNORE INTO _schema_migrations (version, applied_at) VALUES (?, ?)").run(6, Date.now());
      }
    },
    {
      version: 7,
      up: (db2) => {
        try {
          db2.exec(`
            CREATE TABLE IF NOT EXISTS r3mem_documents (
              id TEXT PRIMARY KEY,
              source_type TEXT NOT NULL,
              content TEXT NOT NULL,
              created_at INTEGER NOT NULL,
              compressed INTEGER DEFAULT 0
            )
          `);
          db2.exec(`
            CREATE TABLE IF NOT EXISTS r3mem_paragraphs (
              id TEXT PRIMARY KEY,
              document_id TEXT NOT NULL REFERENCES r3mem_documents(id),
              para_index INTEGER NOT NULL,
              content TEXT NOT NULL,
              created_at INTEGER NOT NULL,
              UNIQUE(document_id, para_index)
            )
          `);
          db2.exec(`
            CREATE TABLE IF NOT EXISTS r3mem_entities (
              id INTEGER PRIMARY KEY AUTOINCREMENT,
              text TEXT NOT NULL,
              type TEXT NOT NULL,
              confidence REAL NOT NULL,
              source_paragraph_id TEXT,
              source_document_id TEXT,
              first_seen_at INTEGER NOT NULL,
              last_seen_at INTEGER NOT NULL,
              occurrence_count INTEGER DEFAULT 1,
              UNIQUE(text, type)
            )
          `);
          db2.exec(`CREATE INDEX IF NOT EXISTS idx_r3mem_para_doc ON r3mem_paragraphs(document_id)`);
          db2.exec(`CREATE INDEX IF NOT EXISTS idx_r3mem_entity_type ON r3mem_entities(type)`);
          db2.exec(`CREATE INDEX IF NOT EXISTS idx_r3mem_entity_text ON r3mem_entities(text)`);
          db2.exec(`CREATE INDEX IF NOT EXISTS idx_r3mem_entity_doc ON r3mem_entities(source_document_id)`);
        } catch (e) {
          log.warn(`migration v7: ${e.message}`);
        }
        db2.prepare("INSERT OR IGNORE INTO _schema_migrations (version, applied_at) VALUES (?, ?)").run(7, Date.now());
      }
    }
  ];
  for (const m of migrations) {
    if (!applied.has(m.version)) {
      try {
        m.up(db);
      } catch (e) {
        log.warn(`migration v${m.version} failed: ${e.message}`);
      }
    }
  }
}
var init_migrations = __esm({
  "src/store/migrations.ts"() {
    "use strict";
  }
});

// src/store/sqlite-store.ts
var sqlite_store_exports = {};
__export(sqlite_store_exports, {
  SqliteStore: () => SqliteStore
});
import Database from "better-sqlite3";
import path from "node:path";
import fs from "node:fs";
var SqliteStore;
var init_sqlite_store = __esm({
  "src/store/sqlite-store.ts"() {
    "use strict";
    init_migrations();
    SqliteStore = class {
      db;
      cache = /* @__PURE__ */ new Map();
      constructor(dataDir) {
        fs.mkdirSync(dataDir, { recursive: true });
        const dbPath = path.join(dataDir, "workflows.db");
        this.db = new Database(dbPath);
        this.db.pragma("journal_mode = WAL");
        this.db.pragma("synchronous = NORMAL");
        runMigrations(this.db);
      }
      /** Load all workflows from SQLite into memory cache */
      loadAll() {
        const rows = this.db.prepare("SELECT * FROM workflows").all();
        for (const row of rows) {
          const wf = this.rowToWorkflow(row);
          this.cache.set(wf.id, wf);
        }
      }
      rowToWorkflow(row) {
        const stepRows = this.db.prepare("SELECT * FROM workflow_steps WHERE workflow_id = ?").all(row.id);
        const steps = /* @__PURE__ */ new Map();
        for (const sr of stepRows) {
          steps.set(sr.step_id, {
            id: sr.step_id,
            name: sr.name,
            discipline: sr.discipline,
            dependencies: JSON.parse(sr.dependencies),
            config: JSON.parse(sr.config),
            state: sr.state,
            result: sr.result !== null ? JSON.parse(sr.result) : void 0,
            error: sr.error ?? void 0,
            startedAt: sr.started_at ?? void 0,
            completedAt: sr.completed_at ?? void 0
          });
        }
        const edgeRows = this.db.prepare("SELECT * FROM dag_edges WHERE workflow_id = ?").all(row.id);
        const edges = edgeRows.map((er) => ({ from: er.edge_from, to: er.edge_to }));
        const layerRows = this.db.prepare("SELECT * FROM dag_layers WHERE workflow_id = ? ORDER BY layer_index, step_id").all(row.id);
        const layers = [];
        let currentLayer = [];
        let currentLayerIndex = -1;
        for (const lr of layerRows) {
          if (lr.layer_index !== currentLayerIndex) {
            if (currentLayer.length > 0) layers.push(currentLayer);
            currentLayer = [];
            currentLayerIndex = lr.layer_index;
          }
          currentLayer.push(lr.step_id);
        }
        if (currentLayer.length > 0) layers.push(currentLayer);
        const nodes = /* @__PURE__ */ new Map();
        for (const [id, step2] of steps) {
          nodes.set(id, {
            id,
            dependencies: step2.dependencies,
            discipline: step2.discipline,
            action: step2.config["prompt"] ?? step2.name
          });
        }
        const dag = { nodes, edges, layers };
        return {
          id: row.id,
          name: row.name,
          description: row.description,
          steps,
          dag,
          state: row.state,
          currentSteps: JSON.parse(row.current_steps),
          createdAt: row.created_at,
          updatedAt: row.updated_at,
          metadata: JSON.parse(row.metadata)
        };
      }
      get(id) {
        return this.cache.get(id);
      }
      set(id, workflow) {
        this.cache.set(id, workflow);
        this.persist(workflow);
      }
      delete(id) {
        this.cache.delete(id);
        this.db.prepare("DELETE FROM workflows WHERE id = ?").run(id);
        return true;
      }
      has(id) {
        return this.cache.has(id);
      }
      values() {
        return this.cache.values();
      }
      get size() {
        return this.cache.size;
      }
      [Symbol.iterator]() {
        return this.cache[Symbol.iterator]();
      }
      persist(wf) {
        const existing = this.db.prepare("SELECT id FROM workflows WHERE id = ?").get(wf.id);
        if (existing) {
          this.db.prepare(`
        UPDATE workflows SET name = ?, description = ?, state = ?, current_steps = ?,
        created_at = ?, updated_at = ?, metadata = ? WHERE id = ?
      `).run(
            wf.name,
            wf.description,
            wf.state,
            JSON.stringify(wf.currentSteps),
            wf.createdAt,
            wf.updatedAt,
            JSON.stringify(wf.metadata),
            wf.id
          );
          this.db.prepare("DELETE FROM workflow_steps WHERE workflow_id = ?").run(wf.id);
          this.db.prepare("DELETE FROM dag_edges WHERE workflow_id = ?").run(wf.id);
          this.db.prepare("DELETE FROM dag_layers WHERE workflow_id = ?").run(wf.id);
        } else {
          this.db.prepare(`
        INSERT INTO workflows (id, name, description, state, current_steps, created_at, updated_at, metadata)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
      `).run(
            wf.id,
            wf.name,
            wf.description,
            wf.state,
            JSON.stringify(wf.currentSteps),
            wf.createdAt,
            wf.updatedAt,
            JSON.stringify(wf.metadata)
          );
        }
        const insertStep = this.db.prepare(`
      INSERT INTO workflow_steps (workflow_id, step_id, name, discipline, dependencies, config, state, result, error, started_at, completed_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `);
        for (const step2 of wf.steps.values()) {
          insertStep.run(
            wf.id,
            step2.id,
            step2.name,
            step2.discipline,
            JSON.stringify(step2.dependencies),
            JSON.stringify(step2.config),
            step2.state,
            step2.result !== void 0 ? JSON.stringify(step2.result) : null,
            step2.error ?? null,
            step2.startedAt ?? null,
            step2.completedAt ?? null
          );
        }
        const insertEdge = this.db.prepare("INSERT INTO dag_edges (workflow_id, edge_from, edge_to) VALUES (?, ?, ?)");
        for (const edge of wf.dag.edges) {
          insertEdge.run(wf.id, edge.from, edge.to);
        }
        const insertLayer = this.db.prepare("INSERT INTO dag_layers (workflow_id, layer_index, step_id) VALUES (?, ?, ?)");
        wf.dag.layers.forEach((layer, idx) => {
          for (const stepId of layer) {
            insertLayer.run(wf.id, idx, stepId);
          }
        });
      }
      /** Store an episodic entry */
      storeEpisodicEntry(entry) {
        this.db.prepare(`
      INSERT OR REPLACE INTO episodic_memory
      (id, namespace, workflow_id, workflow_name, final_state, duration_ms,
       step_summary, compressed, raw_data, source, tags, created_at, updated_at,
       condensed_results)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `).run(
          entry.id,
          entry.namespace,
          entry.workflowId,
          entry.workflowName,
          entry.finalState,
          entry.durationMs,
          JSON.stringify(entry.stepSummary),
          entry.compressed ? 1 : 0,
          entry.rawData !== void 0 ? JSON.stringify(entry.rawData) : null,
          entry.source,
          JSON.stringify(entry.tags),
          entry.createdAt,
          entry.updatedAt,
          entry.condensedResults ?? null
        );
        try {
          const text = this.episodicEntryToText(entry);
          this.db.prepare("INSERT OR REPLACE INTO episodic_fts(rowid, content) VALUES (?, ?)").run(entry.id, text);
        } catch (e) {
          console.warn(`FTS5 may not be available: ${e}`);
        }
      }
      /** Delete all episodic entries for a workflow */
      deleteEpisodicByWorkflow(workflowId) {
        this.db.prepare("DELETE FROM episodic_memory WHERE workflow_id = ?").run(workflowId);
      }
      /** Load all episodic entries (for restoring on startup) */
      loadEpisodicEntries() {
        const rows = this.db.prepare("SELECT * FROM episodic_memory ORDER BY created_at DESC").all();
        return rows.map((row) => ({
          id: row.id,
          namespace: row.namespace,
          workflowId: row.workflow_id,
          workflowName: row.workflow_name,
          finalState: row.final_state,
          durationMs: row.duration_ms,
          stepSummary: JSON.parse(row.step_summary),
          compressed: row.compressed === 1,
          rawData: row.raw_data ? JSON.parse(row.raw_data) : void 0,
          source: row.source,
          tags: JSON.parse(row.tags),
          createdAt: row.created_at,
          updatedAt: row.updated_at,
          condensedResults: row.condensed_results ?? void 0
        }));
      }
      /** Escape SQLite FTS special characters in user query to prevent injection or syntax errors. */
      escapeFTSQuery(query) {
        return query.replace(/[\\"()]/g, " ").replace(/\b(AND|OR|NOT)\b/gi, " ").replace(/[*]/g, " ").replace(/\s+/g, " ").trim() || "";
      }
      /** Search episodic memory via FTS5 full-text search. Returns entry IDs. */
      searchEpisodicFTS(query, limit = 20) {
        try {
          const escaped = this.escapeFTSQuery(query);
          if (!escaped) return [];
          return this.db.prepare(
            "SELECT rowid FROM episodic_fts WHERE episodic_fts MATCH ? ORDER BY rank LIMIT ?"
          ).all(escaped, limit).map((r) => r.rowid);
        } catch (e) {
          console.warn(`error: ${e}`);
          return [];
        }
      }
      /** Remove an episodic entry from FTS index */
      removeEpisodicFTS(id) {
        try {
          this.db.prepare("DELETE FROM episodic_fts WHERE rowid = ?").run(id);
        } catch (e) {
          console.warn(`non-critical: ${e}`);
        }
      }
      episodicEntryToText(entry) {
        const parts = [
          entry.workflowName,
          entry.finalState,
          ...entry.tags ?? [],
          ...(entry.stepSummary ?? []).map((s) => `${s.name} ${s.discipline} ${s.success ? "success" : "failure"}`)
        ];
        if (entry.condensedResults) parts.push(entry.condensedResults);
        return parts.join(" ").toLowerCase();
      }
      /** Get the raw database connection (for sharing with other stores) */
      get database() {
        return this.db;
      }
      close() {
        this.db.close();
      }
    };
  }
});

// src/evolution/evolution-store.ts
var evolution_store_exports = {};
__export(evolution_store_exports, {
  EvolutionStore: () => EvolutionStore
});
var EvolutionStore;
var init_evolution_store = __esm({
  "src/evolution/evolution-store.ts"() {
    "use strict";
    EvolutionStore = class {
      db;
      // better-sqlite3 Database
      constructor(db) {
        this.db = db;
      }
      safeParse(raw, fallback) {
        if (!raw) return fallback;
        try {
          return JSON.parse(raw);
        } catch {
          return fallback;
        }
      }
      rowToTemplate(row) {
        return {
          id: row.id,
          type: row.type,
          name: row.name,
          description: row.description,
          triggers: this.safeParse(row.triggers, []),
          scope: row.scope ?? "general",
          prerequisites: this.safeParse(row.prerequisites, []),
          tools_required: this.safeParse(row.tools_required, []),
          tools_optional: this.safeParse(row.tools_optional, []),
          disciplines_used: this.safeParse(row.disciplines_used, []),
          estimated_steps: row.estimated_steps ?? 0,
          estimated_duration: row.estimated_duration ?? "",
          examples: this.safeParse(row.examples, []),
          steps: this.safeParse(row.steps, void 0),
          pattern: row.pattern ?? void 0,
          sources: this.safeParse(row.sources, []),
          useCount: row.use_count,
          successCount: row.success_count,
          failCount: row.fail_count,
          lastUsedAt: row.last_used_at,
          lastIteratedAt: row.last_iterated_at,
          qualityScore: row.quality_score,
          version: row.version,
          tags: this.safeParse(row.tags, []),
          createdAt: row.created_at,
          updatedAt: row.updated_at
        };
      }
      save(template) {
        const now2 = Date.now();
        this.db.prepare(`
      INSERT OR REPLACE INTO evolved_templates
      (id, type, name, description, steps, pattern, sources,
       use_count, success_count, fail_count, last_used_at, last_iterated_at,
       quality_score, version, tags, created_at, updated_at,
       triggers, scope, prerequisites, tools_required, tools_optional,
       disciplines_used, estimated_steps, estimated_duration, examples)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
              ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `).run(
          template.id,
          template.type,
          template.name,
          template.description,
          template.steps ? JSON.stringify(template.steps) : null,
          template.pattern ?? null,
          JSON.stringify(template.sources),
          template.useCount,
          template.successCount,
          template.failCount,
          template.lastUsedAt,
          template.lastIteratedAt,
          template.qualityScore,
          template.version,
          JSON.stringify(template.tags),
          template.createdAt,
          now2,
          JSON.stringify(template.triggers),
          template.scope,
          JSON.stringify(template.prerequisites),
          JSON.stringify(template.tools_required),
          JSON.stringify(template.tools_optional),
          JSON.stringify(template.disciplines_used),
          template.estimated_steps,
          template.estimated_duration,
          JSON.stringify(template.examples)
        );
      }
      getById(id) {
        try {
          const row = this.db.prepare("SELECT * FROM evolved_templates WHERE id = ?").get(id);
          return row ? this.rowToTemplate(row) : null;
        } catch (e) {
          console.warn(`error: ${e}`);
          return null;
        }
      }
      getAll(type) {
        try {
          const rows = type ? this.db.prepare("SELECT * FROM evolved_templates WHERE type = ? ORDER BY quality_score DESC, created_at DESC").all(type) : this.db.prepare("SELECT * FROM evolved_templates ORDER BY quality_score DESC, created_at DESC").all();
          return rows.map((r) => this.rowToTemplate(r));
        } catch (e) {
          console.warn(`error: ${e}`);
          return [];
        }
      }
      search(query, type, limit = 20) {
        try {
          const pattern = `%${query}%`;
          let sql = "SELECT * FROM evolved_templates WHERE (name LIKE ? OR description LIKE ? OR tags LIKE ? OR triggers LIKE ? OR scope LIKE ?)";
          const params = [pattern, pattern, pattern, pattern, pattern];
          if (type) {
            sql += " AND type = ?";
            params.push(type);
          }
          sql += " ORDER BY quality_score DESC, created_at DESC LIMIT ?";
          params.push(limit);
          return this.db.prepare(sql).all(...params).map((r) => this.rowToTemplate(r));
        } catch (e) {
          console.warn(`error: ${e}`);
          return [];
        }
      }
      recordUsage(id, success) {
        try {
          const t = this.getById(id);
          if (!t) return;
          const now2 = Date.now();
          const useCount = t.useCount + 1;
          const successCount = t.successCount + (success ? 1 : 0);
          const failCount = t.failCount + (success ? 0 : 1);
          const initialQuality = t.qualityScore ?? 0.5;
          const successRate = useCount > 0 ? successCount / useCount : 0;
          const usageFactor = Math.log(1 + useCount) / Math.log(1 + 10);
          const qualityScore = 0.3 * initialQuality + 0.5 * successRate + 0.2 * usageFactor;
          this.db.prepare(`
        UPDATE evolved_templates SET
          use_count = ?, success_count = ?, fail_count = ?,
          last_used_at = ?, quality_score = ?, updated_at = ?
        WHERE id = ?
      `).run(useCount, successCount, failCount, now2, qualityScore, now2, id);
        } catch (e) {
          console.warn(`error: ${e}`);
        }
      }
      delete(id) {
        try {
          this.db.prepare("DELETE FROM evolved_templates WHERE id = ?").run(id);
        } catch (e) {
          console.warn(`error: ${e}`);
        }
      }
      bumpVersion(id, updated) {
        try {
          const t = this.getById(id);
          if (!t) return;
          const now2 = Date.now();
          const newVersion = (t.version ?? 1) + 1;
          const mergedTriggers = [.../* @__PURE__ */ new Set([...t.triggers, ...updated.triggers ?? []])];
          const existingInputs = new Set(t.examples.map((e) => e.input));
          const mergedExamples = [...t.examples];
          for (const ex of updated.examples ?? []) {
            if (!existingInputs.has(ex.input)) {
              mergedExamples.push(ex);
              existingInputs.add(ex.input);
            }
          }
          this.db.prepare(`
        UPDATE evolved_templates SET
          version = ?, description = ?, pattern = ?, quality_score = ?,
          steps = ?, tags = ?, updated_at = ?,
          triggers = ?, scope = ?, prerequisites = ?,
          tools_required = ?, tools_optional = ?, disciplines_used = ?,
          estimated_steps = ?, estimated_duration = ?, examples = ?
        WHERE id = ?
      `).run(
            newVersion,
            updated.description ?? t.description,
            updated.pattern ?? t.pattern ?? null,
            Math.max(t.qualityScore ?? 0.5, updated.qualityScore ?? 0.5),
            updated.steps ? JSON.stringify(updated.steps) : t.steps ? JSON.stringify(t.steps) : null,
            updated.tags ? JSON.stringify(updated.tags) : t.tags ? JSON.stringify(t.tags) : null,
            now2,
            JSON.stringify(mergedTriggers),
            updated.scope ?? t.scope,
            JSON.stringify([.../* @__PURE__ */ new Set([...t.prerequisites, ...updated.prerequisites ?? []])]),
            JSON.stringify([.../* @__PURE__ */ new Set([...t.tools_required, ...updated.tools_required ?? []])]),
            JSON.stringify([.../* @__PURE__ */ new Set([...t.tools_optional, ...updated.tools_optional ?? []])]),
            JSON.stringify([.../* @__PURE__ */ new Set([...t.disciplines_used, ...updated.disciplines_used ?? []])]),
            updated.estimated_steps ?? t.estimated_steps,
            updated.estimated_duration ?? t.estimated_duration,
            JSON.stringify(mergedExamples),
            id
          );
        } catch (e) {
          console.warn(`error: ${e}`);
        }
      }
      count(type) {
        try {
          const row = type ? this.db.prepare("SELECT COUNT(*) as cnt FROM evolved_templates WHERE type = ?").get(type) : this.db.prepare("SELECT COUNT(*) as cnt FROM evolved_templates").get();
          return row.cnt;
        } catch (e) {
          console.warn(`error: ${e}`);
          return 0;
        }
      }
    };
  }
});

// src/evolution/analyzer.ts
var analyzer_exports = {};
__export(analyzer_exports, {
  EvolutionAnalyzer: () => EvolutionAnalyzer
});
import { randomUUID } from "node:crypto";
function calculateOverlap(a, b) {
  if (a.length === 0 && b.length === 0) return 0;
  const setA = new Set(a.map((s) => s.toLowerCase()));
  const setB = new Set(b.map((s) => s.toLowerCase()));
  let intersection = 0;
  for (const item of setA) {
    if (setB.has(item)) intersection++;
  }
  const union = (/* @__PURE__ */ new Set([...setA, ...setB])).size;
  return union === 0 ? 0 : intersection / union;
}
function editDistanceRatio(a, b) {
  if (!a || !b) return 1;
  const la = a.toLowerCase();
  const lb = b.toLowerCase();
  const matrix = Array.from(
    { length: la.length + 1 },
    (_, i) => Array.from(
      { length: lb.length + 1 },
      (_2, j) => i === 0 ? j : j === 0 ? i : 0
    )
  );
  for (let j = 1; j <= lb.length; j++) {
    for (let i = 1; i <= la.length; i++) {
      const mI = matrix[i];
      const mI1 = matrix[i - 1];
      const cost = la[i - 1] === lb[j - 1] ? 0 : 1;
      mI[j] = Math.min(
        mI1[j] + 1,
        mI[j - 1] + 1,
        mI1[j - 1] + cost
      );
    }
  }
  return matrix[la.length][lb.length] / Math.max(la.length, lb.length);
}
function extractKeyPhrase(description) {
  if (!description) return null;
  const sentence = description.split(/[.!?\n]/)[0] ?? "";
  const words = sentence.split(/\s+/).filter((w) => w.length > 3).slice(0, 3);
  return words.length > 0 ? words.join(" ") : null;
}
var EvolutionAnalyzer;
var init_analyzer = __esm({
  "src/evolution/analyzer.ts"() {
    "use strict";
    EvolutionAnalyzer = class _EvolutionAnalyzer {
      api;
      memorySystem;
      evolutionStore;
      onTemplateFound;
      constructor(config) {
        this.api = config.api;
        this.memorySystem = config.memorySystem;
        this.evolutionStore = config.evolutionStore;
        this.onTemplateFound = config.onTemplateFound;
      }
      async analyze(filterType) {
        const episodicEntries = [];
        try {
          const all = this.memorySystem.episodic.all();
          for (const e of all) {
            episodicEntries.push({
              workflowId: e.workflowId,
              workflowName: e.workflowName,
              finalState: e.finalState,
              stepSummary: e.stepSummary,
              durationMs: e.durationMs,
              tags: e.tags,
              createdAt: e.createdAt
            });
          }
        } catch (e) {
          console.warn(`error: ${e}`);
        }
        const conversationEntries = [];
        try {
          const recent = this.readRecentMemoryFiles(30);
          for (const entry of recent) {
            conversationEntries.push({
              date: entry.date,
              content: entry.summary,
              rawSnippets: entry.snippets
            });
          }
        } catch (e) {
          console.warn(`error reading conversation history: ${e}`);
        }
        const existingTemplates = [];
        try {
          const all = this.evolutionStore.getAll();
          for (const t of all) {
            existingTemplates.push({ id: t.id, name: t.name, type: t.type, triggers: t.triggers, tools_required: t.tools_required });
          }
        } catch (e) {
          console.warn(`error: ${e}`);
        }
        if (episodicEntries.length === 0) {
          return { templates: 0, skills: 0 };
        }
        const prompt = `You are a workflow pattern analyst. Analyze the following data and extract reusable patterns.

## Past Workflow Executions (Episodic Memory)
${JSON.stringify(episodicEntries.slice(0, 50), null, 2)}

## Recent Conversation History (from memory files \u2014 last 7 days)
${JSON.stringify(conversationEntries.slice(0, 30), null, 2)}

## Existing Templates (do NOT duplicate these)
${JSON.stringify(existingTemplates, null, 2)}

## Task
Identify patterns that appear more than once or represent a complete useful workflow:

1. **From Conversation History** (recent memory files \u2014 look for recurring user requests, repeated tasks, workflows the user asks for repeatedly):
Analyze the conversation entries for patterns like:
- Same user request appearing multiple times
- Complex tasks broken into predictable steps
- Workflows triggered by specific keywords or situations
For each pattern found, note: user_trigger, typical_request_text, implied_steps

2. **Workflow Templates**: Multi-step processes that could be reused. For each, provide:
   - name (concise), description (what it does)
   - triggers (array of natural language scenarios, e.g. ["when user asks for X", "when Y needs analysis"])
   - scope (one of: "general", "code-review", "content-creation", "data-analysis", "research", "automation", "communication")
   - prerequisites (array of preconditions, e.g. ["needs internet access"])
   - tools_required (array of tool names used, e.g. ["web_search", "weather"])
   - tools_optional (array of optional tools)
   - disciplines_used (array from: "deep", "quick", "visual", "ultrabrain")
   - estimated_duration (one of: "<1min", "1-5min", "5-15min", "15-60min", ">1h")
   - examples (array of {input, expected_output} showing typical use cases, 1-3 examples)
   - steps array with: id, name, discipline (deep|quick|visual|ultrabrain), action (the prompt text), dependencies (array of step ids)
   - tags

2. **Skill Patterns**: Single-step reusable operations. For each, provide:
   - name, description, pattern (the reusable prompt/action text)
   - triggers, scope, prerequisites, tools_required, tools_optional, disciplines_used, estimated_duration
   - examples (array of {input, expected_output})
   - tags

Only extract patterns that are genuinely reusable. Skip one-off workflows unless they represent a common archetype.

Output ONLY valid JSON (no markdown, no explanation):
{"workflows": [...], "skills": [...]}`;
        const responseText = await this.callLLMWithFallback(prompt);
        if (!responseText) {
          return { templates: 0, skills: 0 };
        }
        const result = await this.parseAndSave(responseText, filterType);
        this.cleanupLowQualityTemplates();
        return result;
      }
      /**
       * Direct HTTP call to LLM API.
       * Reads config from openclaw.json to get baseUrl + apiKey.
       */
      async callLLM(prompt, provider, timeoutMs) {
        const baseUrl = provider?.baseUrl ?? this.getBaseUrl();
        const apiKey = provider?.apiKey ?? this.getApiKey();
        const model = provider?.model ?? this.getModel();
        if (!baseUrl || !apiKey) {
          return null;
        }
        try {
          const response = await fetch(`${baseUrl}/chat/completions`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              "Authorization": `Bearer ${apiKey}`
            },
            body: JSON.stringify({
              model,
              messages: [
                {
                  role: "system",
                  content: "You are a workflow pattern analyst. Always respond with valid JSON only. No markdown, no explanation."
                },
                { role: "user", content: prompt }
              ],
              temperature: 0.3,
              max_tokens: 4096
            }),
            signal: AbortSignal.timeout(timeoutMs ?? 12e4)
          });
          if (!response.ok) {
            const body = await response.text().catch(() => "");
            throw new Error(`LLM API ${response.status}: ${body.slice(0, 200)}`);
          }
          const data = await response.json();
          return data.choices?.[0]?.message?.content ?? null;
        } catch (e) {
          const msg = e instanceof Error ? e.message : String(e);
          this.api.logger.warn(`evolution LLM call failed: ${msg}`);
          return null;
        }
      }
      /** Cached provider config (read once from disk) */
      static providerConfig = null;
      getProviderConfig() {
        if (_EvolutionAnalyzer.providerConfig) return _EvolutionAnalyzer.providerConfig;
        try {
          const fs3 = __require("node:fs");
          const path4 = __require("node:path");
          const os3 = __require("node:os");
          const configPath = path4.join(os3.homedir(), ".openclaw", "openclaw.json");
          const raw = fs3.readFileSync(configPath, "utf-8");
          let config;
          try {
            config = JSON.parse(raw);
          } catch (e) {
            const msg = e instanceof Error ? e.message : String(e);
            console.warn(`EvolutionAnalyzer: failed to parse ${configPath}: ${msg}`);
            config = {};
          }
          if (typeof config !== "object" || config === null) config = {};
          _EvolutionAnalyzer.providerConfig = config.models?.providers ?? {};
        } catch (e) {
          console.warn(`error: ${e}`);
          _EvolutionAnalyzer.providerConfig = {};
        }
        return _EvolutionAnalyzer.providerConfig;
      }
      getBaseUrl() {
        const providers = this.getProviderConfig();
        const zai = providers["zai"];
        if (zai?.baseUrl) return zai.baseUrl;
        for (const p of Object.values(providers)) {
          if (p.baseUrl) return p.baseUrl;
        }
        return "";
      }
      getApiKey() {
        const providers = this.getProviderConfig();
        const zai = providers["zai"];
        if (zai?.apiKey) return zai.apiKey;
        for (const p of Object.values(providers)) {
          if (p.apiKey) return p.apiKey;
        }
        return "";
      }
      getModel() {
        const providers = this.getProviderConfig();
        const zai = providers["zai"];
        if (zai?.models?.[0]?.id) return zai.models[0].id;
        return "glm-5";
      }
      async parseAndSave(responseText, filterType) {
        let jsonStr = responseText.trim();
        const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);
        if (jsonMatch && jsonMatch[1]) {
          jsonStr = jsonMatch[1].trim();
        }
        const braceStart = jsonStr.indexOf("{");
        const braceEnd = jsonStr.lastIndexOf("}");
        if (braceStart === -1 || braceEnd === -1) {
          return { templates: 0, skills: 0 };
        }
        jsonStr = jsonStr.slice(braceStart, braceEnd + 1);
        let parsed;
        try {
          parsed = JSON.parse(jsonStr);
        } catch (e) {
          console.warn(`error: ${e}`);
          return { templates: 0, skills: 0 };
        }
        let wfCount = 0;
        let skCount = 0;
        const wfNames = [];
        const skNames = [];
        const now2 = Date.now();
        if (parsed.workflows && Array.isArray(parsed.workflows) && filterType !== "skill") {
          for (const wf of parsed.workflows) {
            if (!wf.name) continue;
            const quality = this.evaluateTemplateQuality(wf, "workflow");
            if (!quality.pass) {
              this.api.logger.info(`evolution: skipping low-quality workflow template "${wf.name}" (score=${quality.score.toFixed(2)})`);
              continue;
            }
            const template = this.buildTemplate("workflow", wf, now2);
            if (!template) continue;
            const { merged } = this.smartMerge(template);
            if (!merged) {
              try {
                await this.onTemplateFound(template);
              } catch (e) {
                console.warn(`non-critical: ${e}`);
              }
            }
            wfCount++;
            wfNames.push(wf.name);
          }
        }
        if (parsed.skills && Array.isArray(parsed.skills) && filterType !== "workflow") {
          for (const sk of parsed.skills) {
            if (!sk.name) continue;
            const quality = this.evaluateTemplateQuality(sk, "skill");
            if (!quality.pass) {
              this.api.logger.info(`evolution: skipping low-quality skill pattern "${sk.name}" (score=${quality.score.toFixed(2)})`);
              continue;
            }
            const template = this.buildTemplate("skill", sk, now2);
            if (!template) continue;
            const { merged } = this.smartMerge(template);
            if (!merged) {
              try {
                await this.onTemplateFound(template);
              } catch (e) {
                console.warn(`non-critical: ${e}`);
              }
            }
            skCount++;
            skNames.push(sk.name);
          }
        }
        return {
          templates: wfCount,
          skills: skCount,
          templateNames: wfNames,
          skillNames: skNames,
          analyzed: this.evolutionStore.count("workflow") + this.evolutionStore.count("skill"),
          summary: `Found ${wfCount} workflow templates (${wfNames.join(", ") || "none"}) and ${skCount} skill patterns (${skNames.join(", ") || "none"}).`
        };
      }
      /** Build an EvolvedTemplate from LLM output with graceful defaults */
      buildTemplate(type, raw, now2) {
        const prefix = type === "workflow" ? "wf_evo" : "sk_evo";
        const template = {
          id: `${prefix}_${now2.toString(36)}_${randomUUID()}`,
          type,
          name: raw.name,
          description: raw.description ?? "",
          triggers: Array.isArray(raw.triggers) ? raw.triggers : [],
          scope: typeof raw.scope === "string" ? raw.scope : "general",
          prerequisites: Array.isArray(raw.prerequisites) ? raw.prerequisites : [],
          tools_required: Array.isArray(raw.tools_required) ? raw.tools_required : [],
          tools_optional: Array.isArray(raw.tools_optional) ? raw.tools_optional : [],
          disciplines_used: Array.isArray(raw.disciplines_used) ? raw.disciplines_used : [],
          estimated_steps: type === "workflow" ? raw.steps?.length ?? 0 : 0,
          estimated_duration: typeof raw.estimated_duration === "string" ? raw.estimated_duration : "",
          examples: Array.isArray(raw.examples) ? raw.examples.filter((e) => e.input) : [],
          sources: Array.isArray(raw.sources) ? raw.sources : [],
          useCount: 0,
          successCount: 0,
          failCount: 0,
          lastUsedAt: null,
          lastIteratedAt: null,
          qualityScore: this.evaluateTemplateQuality(raw, type).score,
          version: 1,
          tags: Array.isArray(raw.tags) ? raw.tags : [],
          createdAt: now2,
          updatedAt: now2
        };
        if (type === "workflow" && raw.steps) {
          template.steps = raw.steps.map((s, i) => ({
            id: s.id ?? `step_${i + 1}`,
            name: s.name ?? `Step ${i + 1}`,
            discipline: s.discipline ?? "quick",
            action: s.action ?? s.name ?? "",
            dependencies: s.dependencies ?? []
          }));
        }
        if (type === "skill") {
          template.pattern = raw.pattern ?? "";
        }
        return template;
      }
      /** Smart merge: check for semantic overlap with existing templates */
      smartMerge(template) {
        try {
          const existing = this.evolutionStore.search(template.name, template.type, 20);
          for (const ex of existing) {
            const triggerOverlap = calculateOverlap(template.triggers, ex.triggers);
            const toolsOverlap = calculateOverlap(template.tools_required, ex.tools_required);
            const nameSimilarity = 1 - editDistanceRatio(template.name, ex.name);
            const combinedScore = 0.4 * triggerOverlap + 0.3 * toolsOverlap + 0.3 * nameSimilarity;
            if (combinedScore >= 0.8) {
              this.evolutionStore.bumpVersion(ex.id, template);
              return { merged: true };
            } else if (combinedScore >= 0.6 && ex.name === template.name) {
              this.evolutionStore.bumpVersion(ex.id, template);
              return { merged: true };
            } else if (ex.name === template.name && combinedScore < 0.6) {
              const suffix = extractKeyPhrase(template.description) || template.scope;
              template.name = `${template.name} (${suffix})`;
              return { merged: false };
            }
          }
        } catch (e) {
          console.warn(`error: ${e}`);
        }
        return { merged: false };
      }
      cleanupLowQualityTemplates() {
        try {
          const all = this.evolutionStore.getAll();
          const now2 = Date.now();
          const sevenDays = 7 * 24 * 60 * 60 * 1e3;
          let archived = 0;
          let downgraded = 0;
          for (const t of all) {
            const age = now2 - (t.createdAt ?? now2);
            const quality = t.qualityScore ?? 0.5;
            const successRate = t.useCount > 0 ? (t.successCount ?? 0) / t.useCount : 0;
            if (age > sevenDays && t.useCount === 0 && quality < 0.4) {
              this.evolutionStore.delete(t.id);
              archived++;
              continue;
            }
            if (t.useCount >= 3 && successRate < 0.3 && quality > 0.2) {
              this.evolutionStore.bumpVersion(t.id, {
                qualityScore: Math.max(0.1, 0.3 * quality + 0.7 * successRate)
              });
              downgraded++;
              continue;
            }
            if (quality < 0.3 && t.useCount >= 10) {
              this.evolutionStore.delete(t.id);
              archived++;
            }
          }
          if (archived > 0 || downgraded > 0) {
            this.api.logger.info(`evolution cleanup: archived ${archived}, downgraded ${downgraded} template(s)`);
          }
        } catch (e) {
          console.warn(`error: ${e}`);
        }
      }
      /**
       * Evaluate template quality from raw LLM output.
       * Returns { score: 0-1, pass: score >= 0.6 }.
       */
      evaluateTemplateQuality(raw, type) {
        let score = 0;
        let checks = 0;
        checks++;
        const name = typeof raw.name === "string" ? raw.name.trim() : "";
        if (name.length > 0 && name.length <= 50) score += 1;
        else if (name.length > 50) score += 0.3;
        checks++;
        const desc = typeof raw.description === "string" ? raw.description.trim() : "";
        if (desc.length >= 30) score += 1;
        else if (desc.length >= 10) score += 0.4;
        checks++;
        const triggers = Array.isArray(raw.triggers) ? raw.triggers : [];
        if (triggers.length >= 2 && triggers.some((t) => typeof t === "string" && t.length > 10)) score += 1;
        else if (triggers.length >= 1) score += 0.4;
        checks++;
        if (type === "workflow") {
          const steps = Array.isArray(raw.steps) ? raw.steps : [];
          if (steps.length >= 2 && steps.some((s) => typeof s.action === "string" && s.action.length > 10)) score += 1;
          else if (steps.length >= 1) score += 0.3;
        } else {
          const pattern = typeof raw.pattern === "string" ? raw.pattern.trim() : "";
          if (pattern.length >= 20) score += 1;
          else if (pattern.length >= 5) score += 0.3;
        }
        checks++;
        const examples = Array.isArray(raw.examples) ? raw.examples : [];
        if (examples.length >= 1 && examples.some((e) => e.input && e.expected_output)) score += 1;
        else if (examples.length >= 1) score += 0.3;
        const normalized = checks > 0 ? score / checks : 0;
        return { score: Math.round(normalized * 100) / 100, pass: normalized >= 0.6 };
      }
      /**
       * LLM call with 3-level fallback chain (MemOS-style degradation).
       * Level 1: configured evolution model (if any)
       * Level 2: OpenClaw default model (zai provider)
       * Level 3: any other configured provider
       * Each level retries once. Total timeout: 60s.
       */
      async callLLMWithFallback(prompt) {
        const providers = this.getProviderConfig();
        const providerEntries = Object.entries(providers);
        const zaiEntry = providerEntries.find(([k]) => k === "zai");
        const otherEntries = providerEntries.filter(([k]) => k !== "zai");
        const chain = [];
        if (zaiEntry) {
          const [, p] = zaiEntry;
          chain.push({
            name: "zai",
            baseUrl: p.baseUrl,
            apiKey: p.apiKey,
            model: p.models?.[0]?.id ?? "glm-5"
          });
        }
        for (const [name, p] of otherEntries) {
          if (p.baseUrl && p.apiKey) {
            chain.push({
              name,
              baseUrl: p.baseUrl,
              apiKey: p.apiKey,
              model: p.models?.[0]?.id ?? "default"
            });
          }
        }
        if (chain.length === 0) {
          this.api.logger.warn("evolution: no LLM providers configured");
          return null;
        }
        const totalDeadline = Date.now() + 6e4;
        for (const provider of chain) {
          if (Date.now() >= totalDeadline) break;
          for (let attempt = 0; attempt < 2; attempt++) {
            try {
              const timeout = Math.max(5e3, totalDeadline - Date.now());
              const result = await this.callLLM(prompt, provider, timeout);
              if (result) {
                this.api.logger.info(`evolution LLM call succeeded via ${provider.name} (attempt ${attempt + 1})`);
                return result;
              }
            } catch (e) {
              const msg = e instanceof Error ? e.message : String(e);
              this.api.logger.warn(`evolution LLM call failed via ${provider.name} (attempt ${attempt + 1}): ${msg}`);
            }
          }
        }
        this.api.logger.warn("evolution: all LLM providers exhausted");
        return null;
      }
      /**
       * Read recent memory/*.md files (last N days) and extract conversation patterns.
       * Reads the daily notes written during sessions, which contain condensed
       * conversation history — the source of truth for what the user actually asks for.
       */
      readRecentMemoryFiles(days) {
        const results = [];
        try {
          const fs3 = __require("node:fs");
          const path4 = __require("node:path");
          const os3 = __require("node:os");
          const memoryDir = path4.join(os3.homedir(), ".openclaw", "workspace", "memory");
          const cutoff = Date.now() - days * 24 * 60 * 60 * 1e3;
          let files = [];
          try {
            files = fs3.readdirSync(memoryDir);
          } catch {
            return results;
          }
          for (const file of files) {
            if (!file.endsWith(".md")) continue;
            const filePath = path4.join(memoryDir, file);
            let stat;
            try {
              stat = fs3.statSync(filePath);
            } catch {
              continue;
            }
            if (stat.mtimeMs < cutoff) continue;
            let raw;
            try {
              raw = fs3.readFileSync(filePath, "utf8");
            } catch {
              continue;
            }
            if (raw.includes("[facts]:") && raw.includes("[preferences]:")) {
              const factsStart = raw.indexOf("[facts]:");
              const factsEnd = raw.indexOf("[preferences]:", factsStart);
              if (factsStart >= 0 && factsEnd >= 0) {
                raw = raw.slice(0, factsStart) + raw.slice(factsEnd + "[preferences]:".length);
              }
            }
            const lines = raw.split("\n");
            const snippets = [];
            let buffer = "";
            let inCode = false;
            for (const line of lines) {
              if (line.startsWith("```")) {
                inCode = !inCode;
                continue;
              }
              if (inCode) continue;
              if (line.startsWith("# ") || line.startsWith("## ") || line.startsWith("---")) {
                if (buffer.trim().length > 40) snippets.push(buffer.trim().slice(0, 200));
                buffer = line.replace(/^#+\s*/, "").trim() + " ";
              } else if (line.trim().length > 30) {
                buffer += line.trim() + " ";
              }
            }
            if (buffer.trim().length > 40) snippets.push(buffer.trim().slice(0, 200));
            const dm = file.match(/(\d{4}-\d{2}-\d{2})/);
            const date = dm?.[1] ?? file.slice(0, 10);
            const summary = snippets.slice(0, 3).join(" | ").slice(0, 250);
            if (summary.length > 20) results.push({ date, summary, snippets: snippets.slice(0, 5) });
          }
        } catch {
        }
        results.sort((a, b) => b.date.localeCompare(a.date));
        return results;
      }
    };
  }
});

// src/evolution/skill-inventory.ts
var skill_inventory_exports = {};
__export(skill_inventory_exports, {
  SkillInventory: () => SkillInventory
});
import * as fs2 from "node:fs";
import * as path2 from "node:path";
import * as os from "node:os";
var SkillInventory;
var init_skill_inventory = __esm({
  "src/evolution/skill-inventory.ts"() {
    "use strict";
    SkillInventory = class {
      db;
      skillDirs;
      constructor(db) {
        this.db = db;
        this.skillDirs = [
          path2.join(os.homedir(), ".openclaw", "workspace", "skills"),
          path2.join(os.homedir(), ".npm-global", "lib", "node_modules", "openclaw", "skills")
        ];
      }
      /** Scan all installed skills and update inventory */
      scan() {
        const scanned = this.scanFilesystem();
        const existing = new Map(
          this.db.prepare("SELECT id, name, location FROM skills_inventory").all().map((r) => [r.id, r])
        );
        let added = 0, updated = 0;
        const now2 = Date.now();
        for (const skill of scanned) {
          const existingSkill = existing.get(skill.id);
          if (!existingSkill) {
            this.db.prepare(`
          INSERT INTO skills_inventory (id, name, description, location, triggers, tools, examples, tags, last_scanned_at, version, installed_at, updated_at)
          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `).run(
              skill.id,
              skill.name,
              skill.description,
              skill.location,
              JSON.stringify(skill.triggers),
              JSON.stringify(skill.tools),
              JSON.stringify(skill.examples),
              JSON.stringify(skill.tags),
              now2,
              skill.version,
              skill.installedAt,
              now2
            );
            added++;
          } else if (existingSkill.location !== skill.location || existingSkill.name !== skill.name) {
            this.db.prepare(`
          UPDATE skills_inventory SET name=?, description=?, location=?, triggers=?, tools=?, examples=?, tags=?, last_scanned_at=?, version=?, updated_at=? WHERE id=?
        `).run(
              skill.name,
              skill.description,
              skill.location,
              JSON.stringify(skill.triggers),
              JSON.stringify(skill.tools),
              JSON.stringify(skill.examples),
              JSON.stringify(skill.tags),
              now2,
              skill.version,
              now2,
              skill.id
            );
            updated++;
          } else {
            this.db.prepare("UPDATE skills_inventory SET last_scanned_at=? WHERE id=?").run(now2, skill.id);
          }
        }
        const scannedIds = new Set(scanned.map((s) => s.id));
        const removed = this.db.prepare("SELECT id FROM skills_inventory").all().filter((r) => !scannedIds.has(r.id)).length;
        if (scanned.length > 0) {
          this.db.prepare(`DELETE FROM skills_inventory WHERE id NOT IN (${scanned.map(() => "?").join(",")})`).run(...scanned.map((s) => s.id));
        }
        return { added, updated, removed };
      }
      scanFilesystem() {
        const skills = [];
        for (const dir of this.skillDirs) {
          if (!fs2.existsSync(dir)) continue;
          try {
            const entries = fs2.readdirSync(dir, { withFileTypes: true });
            for (const entry of entries) {
              if (!entry.isDirectory()) continue;
              const skillPath = path2.join(dir, entry.name);
              const skill = this.parseSkillDir(skillPath, entry.name);
              if (skill) skills.push(skill);
            }
          } catch (e) {
            console.warn(`skip inaccessible dirs: ${e}`);
          }
        }
        return skills;
      }
      parseSkillDir(dir, fallbackName) {
        const skillFile = path2.join(dir, "SKILL.md");
        if (!fs2.existsSync(skillFile)) return null;
        try {
          const content = fs2.readFileSync(skillFile, "utf-8");
          const name = this.extractFrontmatter(content, "name") ?? fallbackName;
          const description = this.extractFrontmatter(content, "description") ?? "";
          const triggers = this.parseListField(this.extractFrontmatter(content, "triggers") ?? "");
          const tools = this.parseListField(this.extractFrontmatter(content, "tools") ?? "");
          const tags = this.parseListField(this.extractFrontmatter(content, "tags") ?? "");
          const examples = this.parseExamples(content);
          const version = this.extractFrontmatter(content, "version") ?? "1.0.0";
          const stat = fs2.statSync(dir);
          return {
            id: this.normalizeId(name),
            name,
            description,
            location: dir,
            triggers,
            tools,
            examples,
            tags,
            version,
            installedAt: Math.floor(stat.birthtimeMs)
          };
        } catch (e) {
          console.warn(`error: ${e}`);
          return null;
        }
      }
      extractFrontmatter(content, key) {
        const match = content.match(new RegExp(`^${key}:\\s*["']?(.+?)["']?\\s*$`, "m"));
        return match?.[1]?.trim() ?? null;
      }
      parseListField(value) {
        if (!value) return [];
        return value.split(",").map((s) => s.trim()).filter(Boolean);
      }
      parseExamples(content) {
        const examples = [];
        const usageMatch = content.match(/##? [Uu]sage[\n\r]([\s\S]*?)(?=\n##|\n#|$)/);
        if (usageMatch) {
          const lines = usageMatch[1].split("\n").filter((l) => l.trim());
          examples.push(...lines.slice(0, 3));
        }
        return examples;
      }
      normalizeId(name) {
        return `sk_inv_${name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 40)}`;
      }
      /** Record a skill/tool usage event */
      recordUsage(skillId, toolName, success, durationMs) {
        try {
          this.db.prepare(`
        INSERT INTO skill_usage (skill_id, tool_name, success, duration_ms, called_at)
        VALUES (?, ?, ?, ?, ?)
      `).run(skillId, toolName, success ? 1 : 0, durationMs ?? null, Date.now());
        } catch (e) {
          console.warn(`non-critical: ${e}`);
        }
      }
      /** Get usage stats for a skill */
      getUsageStats(skillId, days = 30) {
        const since = Date.now() - days * 24 * 60 * 60 * 1e3;
        return this.db.prepare(`
      SELECT
        COUNT(*) as total_calls,
        SUM(CASE WHEN success=1 THEN 1 ELSE 0 END) as successes,
        SUM(CASE WHEN success=0 THEN 1 ELSE 0 END) as failures,
        AVG(duration_ms) as avg_duration
      FROM skill_usage
      WHERE skill_id = ? AND called_at > ?
    `).get(skillId, since);
      }
      /** Get recently used skills */
      getRecentlyUsed(limit = 20) {
        return this.db.prepare(`
      SELECT DISTINCT skill_id, MAX(called_at) as last_used, COUNT(*) as call_count
      FROM skill_usage
      GROUP BY skill_id
      ORDER BY last_used DESC
      LIMIT ?
    `).all(limit);
      }
      /** Get skill combination patterns (skills used in same time window) */
      getCombinationPatterns(windowMs = 3e5) {
        const rows = this.db.prepare(`
      SELECT skill_id, called_at FROM skill_usage ORDER BY called_at
    `).all();
        const combinations = /* @__PURE__ */ new Map();
        for (let i = 0; i < rows.length; i++) {
          for (let j = i + 1; j < rows.length && rows[j].called_at - rows[i].called_at <= windowMs; j++) {
            const pair = [rows[i].skill_id, rows[j].skill_id].sort().join("+");
            combinations.set(pair, (combinations.get(pair) ?? 0) + 1);
          }
        }
        return Array.from(combinations.entries()).filter(([, count]) => count >= 2).map(([pair, count]) => ({ skills: pair.split("+"), count })).sort((a, b) => b.count - a.count);
      }
      safeParseArray(raw) {
        if (!raw) return [];
        try {
          return JSON.parse(raw);
        } catch {
          return [];
        }
      }
      getAll() {
        return this.db.prepare("SELECT * FROM skills_inventory ORDER BY name").all().map((r) => ({
          ...r,
          triggers: this.safeParseArray(r.triggers),
          tools: this.safeParseArray(r.tools),
          examples: this.safeParseArray(r.examples),
          tags: this.safeParseArray(r.tags)
        }));
      }
    };
  }
});

// src/evolution/skill-analyzer.ts
var skill_analyzer_exports = {};
__export(skill_analyzer_exports, {
  SkillAnalyzer: () => SkillAnalyzer
});
var SkillAnalyzer;
var init_skill_analyzer = __esm({
  "src/evolution/skill-analyzer.ts"() {
    "use strict";
    SkillAnalyzer = class {
      skillInventory;
      db;
      api;
      constructor(skillInventory, db, api) {
        this.skillInventory = skillInventory;
        this.db = db;
        this.api = api;
      }
      async analyze() {
        const scanResult = this.skillInventory.scan();
        this.api.logger.info(`skill inventory: ${scanResult.added} added, ${scanResult.updated} updated`);
        const insights = this.analyzeUsagePatterns();
        const suggestions = this.analyzeOpportunities();
        const now2 = Date.now();
        for (const insight of [...insights, ...suggestions]) {
          try {
            this.db.prepare(`
          INSERT INTO skill_insights (type, skill_a, skill_b, confidence, description, recommendation, discovered_at)
          VALUES (?, ?, ?, ?, ?, ?, ?)
        `).run(
              insight.type,
              insight.skillA ?? null,
              insight.skillB ?? null,
              insight.confidence,
              insight.description,
              insight.recommendation,
              now2
            );
          } catch (e) {
            console.warn(`dedup by time + type: ${e}`);
          }
        }
        return { insights: insights.length, suggestions: suggestions.length };
      }
      analyzeUsagePatterns() {
        const insights = [];
        const allSkills = this.skillInventory.getAll();
        const recentlyUsed = this.skillInventory.getRecentlyUsed(100);
        const usedIds = new Set(recentlyUsed.map((r) => r.skill_id));
        for (const skill of allSkills) {
          if (!usedIds.has(skill.id)) {
            insights.push({
              type: "unused",
              skillA: skill.id,
              confidence: 0.8,
              description: `Skill "${skill.name}" is installed but never used in the last 30 days`,
              recommendation: `Consider removing or repurposing "${skill.name}"`
            });
          }
        }
        const combinations = this.skillInventory.getCombinationPatterns();
        for (const combo of combinations.slice(0, 5)) {
          insights.push({
            type: "combination",
            skillA: combo.skills[0],
            skillB: combo.skills[1],
            confidence: Math.min(0.9, combo.count * 0.2),
            description: `Skills "${combo.skills[0]}" and "${combo.skills[1]}" are frequently used together (${combo.count} times)`,
            recommendation: `Consider combining these into a workflow template`
          });
        }
        return insights;
      }
      analyzeOpportunities() {
        const skills = this.skillInventory.getAll();
        const insights = [];
        for (let i = 0; i < skills.length; i++) {
          for (let j = i + 1; j < skills.length; j++) {
            const a = skills[i], b = skills[j];
            const wordsA = new Set(a.description.toLowerCase().split(/\s+/).filter((w) => w.length > 4));
            const wordsB = new Set(b.description.toLowerCase().split(/\s+/).filter((w) => w.length > 4));
            const overlap = [...wordsA].filter((w) => wordsB.has(w)).length;
            const union = (/* @__PURE__ */ new Set([...wordsA, ...wordsB])).size;
            const jaccard2 = union > 0 ? overlap / union : 0;
            if (jaccard2 >= 0.5) {
              insights.push({
                type: "redundancy",
                skillA: a.id,
                skillB: b.id,
                confidence: jaccard2,
                description: `Skills "${a.name}" and "${b.name}" have overlapping descriptions (${(jaccard2 * 100).toFixed(0)}% similarity)`,
                recommendation: `Review if these skills serve distinct purposes or could be merged`
              });
            }
          }
        }
        return insights;
      }
      getInsights(limit = 20) {
        return this.db.prepare(`
      SELECT * FROM skill_insights ORDER BY discovered_at DESC, confidence DESC LIMIT ?
    `).all(limit);
      }
    };
  }
});

// src/evolution/mcp-inventory.ts
var mcp_inventory_exports = {};
__export(mcp_inventory_exports, {
  MCPInventory: () => MCPInventory
});
var MCPInventory;
var init_mcp_inventory = __esm({
  "src/evolution/mcp-inventory.ts"() {
    "use strict";
    MCPInventory = class {
      db;
      api;
      constructor(db, api) {
        this.db = db;
        this.api = api;
      }
      /** Scan MCP servers from config and update inventory */
      scan() {
        const now2 = Date.now();
        let added = 0, updated = 0;
        const sources = this.getMCPConfigSources();
        for (const source of sources) {
          for (const [serverId, serverConfig] of Object.entries(source)) {
            const cfg = serverConfig;
            const name = cfg.name ?? serverId;
            const location = [cfg.command, ...cfg.args ?? []].filter(Boolean).join(" ") || cfg.url || serverId;
            const tools = Array.isArray(cfg.tools) ? cfg.tools.map((t) => typeof t === "string" ? t : t.name ?? "unknown") : [];
            const description = cfg.description ?? `MCP server: ${name}`;
            const existing = this.db.prepare("SELECT id FROM mcp_servers WHERE id=?").get(serverId);
            if (!existing) {
              this.db.prepare(`
            INSERT INTO mcp_servers (id, name, description, location, tools, enabled, last_seen_at, discovered_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
          `).run(serverId, name, description, location, JSON.stringify(tools), 1, now2, now2);
              added++;
            } else {
              this.db.prepare(`
            UPDATE mcp_servers SET name=?, description=?, location=?, tools=?, last_seen_at=?
            WHERE id=?
          `).run(name, description, location, JSON.stringify(tools), now2, serverId);
              updated++;
            }
          }
        }
        return { added, updated };
      }
      /** Read MCP server configs from multiple possible locations */
      getMCPConfigSources() {
        const fs3 = __require("node:fs");
        const path4 = __require("node:path");
        const os3 = __require("node:os");
        const sources = [];
        const config = this.api.config ?? {};
        if (config.mcpServers && Object.keys(config.mcpServers).length > 0) {
          sources.push(config.mcpServers);
        }
        const mcporterPaths = [
          path4.join(os3.homedir(), ".openclaw", "workspace", "config", "mcporter.json"),
          path4.join(os3.homedir(), ".openclaw", "config", "mcporter.json")
        ];
        for (const p of mcporterPaths) {
          try {
            const raw = fs3.readFileSync(p, "utf-8");
            const parsed = JSON.parse(raw);
            if (parsed.mcpServers && Object.keys(parsed.mcpServers).length > 0) {
              sources.push(parsed.mcpServers);
            }
          } catch (e) {
            console.warn(`not found or invalid: ${e}`);
          }
        }
        try {
          const raw = fs3.readFileSync(path4.join(os3.homedir(), ".openclaw", "openclaw.json"), "utf-8");
          const parsed = JSON.parse(raw);
          if (parsed.mcpServers && Object.keys(parsed.mcpServers).length > 0) {
            sources.push(parsed.mcpServers);
          }
        } catch (e) {
          console.warn(`not found: ${e}`);
        }
        return sources;
      }
      /** Record a tool call against an MCP server */
      recordUsage(serverId, toolName, success, durationMs) {
        try {
          this.db.prepare(`
        INSERT INTO mcp_usage (server_id, tool_name, success, duration_ms, called_at)
        VALUES (?, ?, ?, ?, ?)
      `).run(serverId, toolName, success ? 1 : 0, durationMs ?? null, Date.now());
          this.db.prepare("UPDATE mcp_servers SET last_seen_at=? WHERE id=?").run(Date.now(), serverId);
        } catch (e) {
          console.warn(`non-critical: ${e}`);
        }
      }
      /** Get usage stats for an MCP server */
      getUsageStats(serverId, days = 30) {
        const since = Date.now() - days * 24 * 60 * 60 * 1e3;
        return this.db.prepare(`
      SELECT
        COUNT(*) as total_calls,
        SUM(CASE WHEN success=1 THEN 1 ELSE 0 END) as successes,
        SUM(CASE WHEN success=0 THEN 1 ELSE 0 END) as failures,
        AVG(duration_ms) as avg_duration_ms
      FROM mcp_usage
      WHERE server_id = ? AND called_at > ?
    `).get(serverId, since) ?? { total_calls: 0, successes: 0, failures: 0, avg_duration_ms: null };
      }
      /** Get all tool call stats across all servers */
      getToolStats(days = 30) {
        const since = Date.now() - days * 24 * 60 * 60 * 1e3;
        return this.db.prepare(`
      SELECT server_id, tool_name,
        COUNT(*) as call_count,
        SUM(CASE WHEN success=1 THEN 1 ELSE 0 END) as successes,
        AVG(duration_ms) as avg_duration_ms
      FROM mcp_usage
      WHERE called_at > ?
      GROUP BY server_id, tool_name
      ORDER BY call_count DESC
    `).all(since);
      }
      /** Get server rankings by usage */
      getServerRankings(days = 30) {
        const since = Date.now() - days * 24 * 60 * 60 * 1e3;
        return this.db.prepare(`
      SELECT ms.id, ms.name, ms.tools, ms.last_seen_at,
        COUNT(mu.id) as total_calls,
        SUM(CASE WHEN mu.success=1 THEN 1 ELSE 0 END) as successes,
        AVG(mu.duration_ms) as avg_duration_ms
      FROM mcp_servers ms
      LEFT JOIN mcp_usage mu ON ms.id = mu.server_id AND mu.called_at > ?
      GROUP BY ms.id
      ORDER BY total_calls DESC
    `).all(since);
      }
      /** Get all servers */
      getAll() {
        return this.db.prepare("SELECT * FROM mcp_servers ORDER BY name").all().map((r) => ({
          id: r.id,
          name: r.name,
          description: r.description,
          location: r.location,
          tools: (() => {
            try {
              return JSON.parse(r.tools || "[]");
            } catch {
              return [];
            }
          })(),
          enabled: !!r.enabled,
          lastSeenAt: r.last_seen_at,
          discoveredAt: r.discovered_at
        }));
      }
      /** Auto-detect which MCP server a tool belongs to */
      detectServerForTool(toolName) {
        const servers = this.getAll();
        for (const server of servers) {
          if (server.tools.some((t) => t.toLowerCase() === toolName.toLowerCase())) {
            return server.id;
          }
        }
        return null;
      }
    };
  }
});

// src/api/router.ts
function matchPattern(pattern, path4) {
  const patternParts = pattern.split("/");
  const pathParts = path4.split("/");
  if (patternParts.length !== pathParts.length) return null;
  const params = {};
  for (let i = 0; i < patternParts.length; i++) {
    const pp = patternParts[i];
    const segment = pathParts[i];
    if (pp.startsWith(":")) {
      params[pp.slice(1)] = segment;
    } else if (pp !== segment) {
      return null;
    }
  }
  return params;
}
function isHttpError(err) {
  return err instanceof HttpError;
}
function jsonError(status, error, message) {
  return {
    status,
    headers: { "content-type": "application/json" },
    body: { error, message, statusCode: status }
  };
}
function jsonResponse(status, body, headers) {
  return {
    status,
    headers: { "content-type": "application/json", ...headers },
    body
  };
}
var Router, HttpError;
var init_router = __esm({
  "src/api/router.ts"() {
    "use strict";
    Router = class {
      routes = [];
      middlewares = [];
      get(pattern, handler) {
        this.addRoute("GET", pattern, handler);
      }
      post(pattern, handler) {
        this.addRoute("POST", pattern, handler);
      }
      put(pattern, handler) {
        this.addRoute("PUT", pattern, handler);
      }
      delete(pattern, handler) {
        this.addRoute("DELETE", pattern, handler);
      }
      use(middleware) {
        this.middlewares.push(middleware);
      }
      addRoute(method, pattern, handler) {
        this.routes.push({ method, pattern, handler });
      }
      async handle(req) {
        const route = this.matchRoute(req.method, req.path);
        if (!route) {
          return jsonError(404, "Not Found", `No route matches ${req.method} ${req.path}`);
        }
        const dispatch = this.buildMiddlewareChain(route.handler);
        try {
          return await dispatch(req);
        } catch (err) {
          const message = err instanceof Error ? err.message : String(err);
          const status = isHttpError(err) ? err.status : 500;
          return jsonError(status, "Internal Server Error", message);
        }
      }
      matchRoute(method, path4) {
        for (const route of this.routes) {
          if (route.method !== method) continue;
          const params = matchPattern(route.pattern, path4);
          if (params !== null) {
            return { ...route, params };
          }
        }
        return null;
      }
      buildMiddlewareChain(finalHandler) {
        let chain = (req) => Promise.resolve(finalHandler(req));
        for (let i = this.middlewares.length - 1; i >= 0; i--) {
          const mw = this.middlewares[i];
          const next = chain;
          chain = (req) => mw(req, () => next(req));
        }
        return chain;
      }
    };
    HttpError = class extends Error {
      constructor(status, message) {
        super(message);
        this.status = status;
        this.name = "HttpError";
      }
      status;
    };
  }
});

// src/api/websocket.ts
var WebSocketServer;
var init_websocket = __esm({
  "src/api/websocket.ts"() {
    "use strict";
    WebSocketServer = class {
      constructor(workflowService) {
        this.workflowService = workflowService;
      }
      workflowService;
      connections = /* @__PURE__ */ new Map();
      subscriptions = /* @__PURE__ */ new Map();
      eventListener = null;
      nextId = 0;
      init() {
        this.eventListener = this.workflowService.subscribe((event) => {
          const workflowId = event.workflowId;
          if (!workflowId) return;
          const message = { type: "event", event };
          this.broadcastToWorkflow(workflowId, message);
        });
      }
      destroy() {
        if (this.eventListener) {
          this.eventListener();
          this.eventListener = null;
        }
        for (const conn of this.connections.values()) {
          conn.close();
        }
        this.connections.clear();
        this.subscriptions.clear();
      }
      handleConnection(ws) {
        this.connections.set(ws.id, ws);
        this.sendTo(ws.id, { type: "pong" });
        const cleanup = () => {
          this.removeAllSubscriptions(ws.id);
          this.connections.delete(ws.id);
        };
        ws.addEventListener("close", cleanup);
        ws.addEventListener("error", cleanup);
        ws.close = ws.close.bind(ws);
        const originalClose = ws.close;
        ws.close = () => {
          cleanup();
          originalClose();
        };
      }
      broadcast(event, data) {
        const message = JSON.stringify({ type: event, data });
        for (const conn of this.connections.values()) {
          if (conn.isAlive) {
            conn.send(message);
          }
        }
      }
      subscribe(workflowId, wsId) {
        if (!this.subscriptions.has(workflowId)) {
          this.subscriptions.set(workflowId, /* @__PURE__ */ new Set());
        }
        this.subscriptions.get(workflowId).add(wsId);
        this.sendTo(wsId, { type: "subscribed", workflowId });
      }
      unsubscribe(workflowId, wsId) {
        const subs = this.subscriptions.get(workflowId);
        if (subs) {
          subs.delete(wsId);
          if (subs.size === 0) {
            this.subscriptions.delete(workflowId);
          }
        }
        this.sendTo(wsId, { type: "unsubscribed", workflowId });
      }
      handleMessage(wsId, raw) {
        let msg;
        try {
          msg = JSON.parse(raw);
        } catch (e) {
          console.warn(`error: ${e}`);
          this.sendTo(wsId, { type: "error", message: "Invalid JSON" });
          return;
        }
        switch (msg.type) {
          case "subscribe":
            this.subscribe(msg.workflowId, wsId);
            break;
          case "unsubscribe":
            this.unsubscribe(msg.workflowId, wsId);
            break;
          case "ping":
            this.sendTo(wsId, { type: "pong" });
            break;
          default:
            this.sendTo(wsId, { type: "error", message: `Unknown message type: ${msg.type}` });
        }
      }
      get connectionCount() {
        return this.connections.size;
      }
      get subscriptionCount() {
        return this.subscriptions.size;
      }
      generateConnectionId() {
        return `ws-${++this.nextId}`;
      }
      sendTo(wsId, message) {
        const conn = this.connections.get(wsId);
        if (conn?.isAlive) {
          conn.send(JSON.stringify(message));
        }
      }
      broadcastToWorkflow(workflowId, message) {
        const subs = this.subscriptions.get(workflowId);
        if (!subs) return;
        const data = JSON.stringify(message);
        for (const wsId of subs) {
          const conn = this.connections.get(wsId);
          if (conn?.isAlive) {
            conn.send(data);
          }
        }
      }
      removeAllSubscriptions(wsId) {
        for (const [workflowId, subs] of this.subscriptions) {
          subs.delete(wsId);
          if (subs.size === 0) {
            this.subscriptions.delete(workflowId);
          }
        }
      }
    };
  }
});

// src/api/routes/workflows.ts
function asStepId(s) {
  return s;
}
function asWorkflowId(s) {
  return s;
}
function checkOwnership(workflow, userId) {
  if (!workflow.ownerId || !userId) return;
  if (workflow.ownerId !== userId) {
    throw new HttpError(403, "You do not have permission to modify this workflow");
  }
}
function serializeWorkflow(workflow) {
  const steps = Array.from(workflow.steps.values()).map((s) => ({
    id: s.id,
    name: s.name,
    discipline: s.discipline,
    dependencies: s.dependencies,
    config: s.config,
    state: s.state,
    result: s.result,
    error: s.error,
    startedAt: s.startedAt,
    completedAt: s.completedAt
  }));
  return {
    id: workflow.id,
    name: workflow.name,
    description: workflow.description,
    ownerId: workflow.ownerId,
    steps,
    state: workflow.state,
    currentSteps: workflow.currentSteps,
    createdAt: workflow.createdAt,
    updatedAt: workflow.updatedAt,
    metadata: workflow.metadata
  };
}
function createWorkflowRoutes(services, _templates) {
  return {
    async list(req) {
      const query = req.query;
      const limit = query.limit ? parseInt(query.limit, 10) : 50;
      const offset = query.offset ? parseInt(query.offset, 10) : 0;
      const workflows = services.workflowService.list({
        status: query.state,
        template: query.template,
        limit,
        offset
      });
      const total = services.workflowService.list().length;
      return jsonResponse(200, {
        data: workflows.map(serializeWorkflow),
        total,
        limit,
        offset
      });
    },
    async create(req) {
      const body = req.body;
      if (!body?.name) {
        throw new HttpError(400, "Workflow name is required");
      }
      if (!body?.steps || !Array.isArray(body.steps) || body.steps.length === 0) {
        throw new HttpError(400, "At least one step is required");
      }
      const steps = body.steps.map((s, i) => ({
        id: asStepId(s.id ?? `step-${i}`),
        name: s.name,
        discipline: s.discipline,
        dependencies: s.dependencies.map(asStepId),
        config: s.config,
        state: "pending"
      }));
      const workflow = {
        id: crypto.randomUUID(),
        name: body.name,
        description: body.description ?? "",
        ownerId: req.user?.id,
        steps: new Map(steps.map((s) => [s.id, s])),
        dag: {
          nodes: /* @__PURE__ */ new Map(),
          edges: [],
          layers: []
        },
        state: "idle",
        currentSteps: [],
        createdAt: Date.now(),
        updatedAt: Date.now(),
        metadata: body.metadata ?? {}
      };
      const created = services.workflowService.create(workflow);
      return jsonResponse(201, serializeWorkflow(created));
    },
    async get(req) {
      const id = asWorkflowId(req.params["id"] ?? "");
      const workflow = services.workflowService.get(id);
      if (!workflow) {
        throw new HttpError(404, `Workflow not found: ${String(id)}`);
      }
      return jsonResponse(200, serializeWorkflow(workflow));
    },
    async update(req) {
      const id = asWorkflowId(req.params["id"] ?? "");
      const workflow = services.workflowService.get(id);
      if (!workflow) {
        throw new HttpError(404, `Workflow not found: ${String(id)}`);
      }
      checkOwnership(workflow, req.user?.id);
      const body = req.body;
      if (body.name !== void 0) workflow.name = body.name;
      if (body.description !== void 0) workflow.description = body.description;
      if (body.metadata !== void 0) workflow.metadata = body.metadata;
      services.workflowService.update(workflow);
      return jsonResponse(200, serializeWorkflow(workflow));
    },
    async delete_(req) {
      const id = asWorkflowId(req.params["id"] ?? "");
      const workflow = services.workflowService.get(id);
      if (!workflow) {
        throw new HttpError(404, `Workflow not found: ${String(id)}`);
      }
      checkOwnership(workflow, req.user?.id);
      try {
        services.workflowService.delete(id);
      } catch (e) {
        console.warn(`error: ${e}`);
        throw new HttpError(404, `Workflow not found: ${String(id)}`);
      }
      return jsonResponse(204, null);
    },
    async start(req) {
      const id = asWorkflowId(req.params["id"] ?? "");
      const workflow = services.workflowService.get(id);
      if (!workflow) {
        throw new HttpError(404, `Workflow not found: ${String(id)}`);
      }
      checkOwnership(workflow, req.user?.id);
      try {
        services.workflowService.start(id);
      } catch (err) {
        throw new HttpError(409, err instanceof Error ? err.message : "Cannot start workflow");
      }
      const updated = services.workflowService.get(id);
      return jsonResponse(200, { state: updated?.state, id: String(id) });
    },
    async cancel(req) {
      const id = asWorkflowId(req.params["id"] ?? "");
      const workflow = services.workflowService.get(id);
      if (!workflow) {
        throw new HttpError(404, `Workflow not found: ${String(id)}`);
      }
      checkOwnership(workflow, req.user?.id);
      try {
        services.workflowService.cancel(id, true);
      } catch (err) {
        throw new HttpError(409, err instanceof Error ? err.message : "Cannot cancel workflow");
      }
      const updated = services.workflowService.get(id);
      return jsonResponse(200, { state: updated?.state, id: String(id) });
    }
  };
}
var init_workflows = __esm({
  "src/api/routes/workflows.ts"() {
    "use strict";
    init_router();
  }
});

// src/api/routes/executions.ts
function asWorkflowId2(s) {
  return s;
}
function buildLogsFromStatus(status) {
  const logs = [];
  logs.push({
    timestamp: status.startedAt,
    level: "info",
    message: "Workflow execution started"
  });
  for (const stepId of status.completedSteps) {
    logs.push({
      timestamp: status.updatedAt,
      level: "info",
      stepId,
      message: `Step completed: ${String(stepId)}`
    });
  }
  for (const fail of status.failedSteps) {
    logs.push({
      timestamp: status.updatedAt,
      level: "error",
      stepId: fail.stepId,
      message: `Step failed: ${String(fail.stepId)}`,
      data: { error: fail.error }
    });
  }
  if (status.state === "cancelled") {
    logs.push({
      timestamp: status.updatedAt,
      level: "warn",
      message: "Workflow execution cancelled"
    });
  }
  return logs;
}
function createExecutionRoutes(services) {
  return {
    async getStatus(req) {
      const id = asWorkflowId2(req.params["id"] ?? "");
      const status = services.scheduler.getStatus(id);
      if (!status) {
        const workflow = services.workflowService.get(id);
        if (!workflow) {
          throw new HttpError(404, `Execution not found: ${String(id)}`);
        }
        return jsonResponse(200, {
          workflowId: id,
          state: workflow.state,
          progress: 0,
          completedSteps: [],
          failedSteps: [],
          runningSteps: []
        });
      }
      return jsonResponse(200, status);
    },
    async getLogs(req) {
      const id = asWorkflowId2(req.params["id"] ?? "");
      const status = services.scheduler.getStatus(id);
      if (!status) {
        const workflow = services.workflowService.get(id);
        if (!workflow) {
          throw new HttpError(404, `Execution not found: ${String(id)}`);
        }
        return jsonResponse(200, { data: [], total: 0 });
      }
      const logs = buildLogsFromStatus(status);
      return jsonResponse(200, { data: logs, total: logs.length });
    },
    async list(req) {
      const limit = req.query["limit"] ? parseInt(req.query["limit"], 10) : 50;
      const offset = req.query["offset"] ? parseInt(req.query["offset"], 10) : 0;
      const workflows = services.workflowService.list();
      const executions = [];
      for (const wf of workflows) {
        const status = services.scheduler.getStatus(wf.id);
        if (status) {
          executions.push({
            workflowId: wf.id,
            workflowName: wf.name,
            state: status.state,
            progress: status.progress,
            startedAt: status.startedAt,
            updatedAt: status.updatedAt
          });
        }
      }
      const paged = executions.slice(offset, offset + limit);
      return jsonResponse(200, {
        data: paged,
        total: executions.length,
        limit,
        offset
      });
    }
  };
}
var init_executions = __esm({
  "src/api/routes/executions.ts"() {
    "use strict";
    init_router();
  }
});

// src/api/routes/templates.ts
function asStepId2(s) {
  return s;
}
function createTemplateRoutes(templates) {
  return {
    async list(_req) {
      const entries = templates.entries();
      const data = entries.map(([key, tpl]) => ({
        key,
        name: tpl.name,
        description: tpl.description,
        stepCount: tpl.steps.length
      }));
      return jsonResponse(200, { data, total: data.length });
    },
    async create(req) {
      const body = req.body;
      if (!body?.key) {
        throw new HttpError(400, "Template key is required");
      }
      if (!body?.name) {
        throw new HttpError(400, "Template name is required");
      }
      if (!body?.steps || !Array.isArray(body.steps) || body.steps.length === 0) {
        throw new HttpError(400, "At least one step is required");
      }
      const template = {
        name: body.name,
        description: body.description ?? "",
        steps: body.steps.map((s, i) => ({
          id: asStepId2(s.id ?? `step-${i}`),
          name: s.name,
          discipline: s.discipline,
          dependencies: s.dependencies.map(asStepId2),
          config: s.config
        }))
      };
      templates.register(body.key, template);
      return jsonResponse(201, { key: body.key, name: template.name });
    },
    async get(req) {
      const key = req.params["id"] ?? "";
      const template = templates.get(key);
      if (!template) {
        throw new HttpError(404, `Template not found: ${key}`);
      }
      return jsonResponse(200, {
        key,
        name: template.name,
        description: template.description,
        steps: template.steps.map((s) => ({
          id: s.id,
          name: s.name,
          discipline: s.discipline,
          dependencies: s.dependencies,
          config: s.config
        }))
      });
    }
  };
}
var init_templates = __esm({
  "src/api/routes/templates.ts"() {
    "use strict";
    init_router();
  }
});

// src/api/routes/evolved.ts
function createEvolvedRoutes(evolutionStore, skillInventory) {
  return {
    // GET /evolved — list all evolved templates
    async listEvolved(req) {
      if (!evolutionStore) return jsonResponse(503, { error: "Evolution system not ready yet, try again in a few seconds" });
      const type = req.query["type"];
      const templates = evolutionStore.getAll(type);
      return jsonResponse(200, {
        data: templates,
        total: templates.length,
        workflows: templates.filter((t) => t.type === "workflow").length,
        skills: templates.filter((t) => t.type === "skill").length
      });
    },
    // GET /evolved/:id — get single template
    async getEvolved(req) {
      if (!evolutionStore) return jsonResponse(503, { error: "Evolution system not ready yet" });
      const id = req.params["id"] ?? "";
      const t = evolutionStore.getById(id);
      if (!t) throw new HttpError(404, `Template not found: ${id}`);
      return jsonResponse(200, t);
    },
    // GET /evolved/search?q=&type= — search templates
    async searchEvolved(req) {
      if (!evolutionStore) return jsonResponse(503, { error: "Evolution system not ready yet" });
      const q = req.query["q"] ?? "";
      const type = req.query["type"];
      const results = evolutionStore.search(q, type, 20);
      return jsonResponse(200, { data: results, query: q, type });
    },
    // GET /evolved/stats — aggregate stats
    async evolveStats(_req) {
      if (!evolutionStore) return jsonResponse(503, { error: "Evolution system not ready yet" });
      const workflows = evolutionStore.getAll("workflow");
      const skills = evolutionStore.getAll("skill");
      const all = evolutionStore.getAll();
      const totalUses = all.reduce((s, t) => s + t.useCount, 0);
      const totalSuccess = all.reduce((s, t) => s + t.successCount, 0);
      const avgQuality = all.length > 0 ? all.reduce((s, t) => s + t.qualityScore, 0) / all.length : 0;
      return jsonResponse(200, {
        total: all.length,
        workflows: workflows.length,
        skills: skills.length,
        totalUses,
        avgSuccessRate: totalUses > 0 ? totalSuccess / totalUses : 0,
        avgQualityScore: avgQuality,
        topTemplates: all.sort((a, b) => b.useCount - a.useCount).slice(0, 5).map((t) => ({
          id: t.id,
          name: t.name,
          type: t.type,
          useCount: t.useCount,
          qualityScore: t.qualityScore
        }))
      });
    },
    // DELETE /evolved/:id
    async deleteEvolved(req) {
      if (!evolutionStore) return jsonResponse(503, { error: "Evolution system not ready yet" });
      const id = req.params["id"] ?? "";
      evolutionStore.delete(id);
      return jsonResponse(200, { ok: true, id });
    },
    // POST /evolved/:id/record-usage
    async recordUsage(req) {
      if (!evolutionStore) return jsonResponse(503, { error: "Evolution system not ready yet" });
      const id = req.params["id"] ?? "";
      const body = req.body ?? {};
      const success = body.success !== false;
      evolutionStore.recordUsage(id, success);
      return jsonResponse(200, { ok: true, id, success });
    },
    // GET /skills — list all skills (from skillInventory)
    async listSkills(_req) {
      if (!skillInventory) {
        return jsonResponse(200, { data: [], total: 0, note: "Skill inventory not available" });
      }
      try {
        const skills = skillInventory.getAll();
        return jsonResponse(200, { data: skills, total: skills.length });
      } catch (e) {
        return jsonResponse(200, { data: [], total: 0, error: String(e) });
      }
    },
    // GET /skills/search?q= — search skills
    async searchSkills(req) {
      if (!skillInventory) {
        return jsonResponse(200, { data: [], total: 0 });
      }
      const q = (req.query["q"] ?? "").toLowerCase();
      const all = skillInventory.getAll();
      const results = q ? all.filter(
        (s) => (s.name ?? "").toLowerCase().includes(q) || (s.description ?? "").toLowerCase().includes(q) || (s.tags ?? []).some((t) => t.toLowerCase().includes(q))
      ) : all;
      return jsonResponse(200, { data: results.slice(0, 20), total: results.length, query: q });
    }
  };
}
var init_evolved = __esm({
  "src/api/routes/evolved.ts"() {
    "use strict";
    init_router();
  }
});

// src/api/middleware/auth.ts
import { createHash } from "node:crypto";
function base64UrlDecode(s) {
  const padded = s.replace(/-/g, "+").replace(/_/g, "/");
  const pad = 4 - padded.length % 4;
  return atob(pad < 4 ? padded + "=".repeat(pad) : padded);
}
function base64UrlEncode(data) {
  return btoa(data).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
async function hmacSign(payload, secret, algo) {
  const algoName = algo === "HS512" ? "SHA-512" : "SHA-256";
  const key = await crypto.subtle.importKey(
    "raw",
    new TextEncoder().encode(secret),
    { name: "HMAC", hash: algoName },
    false,
    ["sign"]
  );
  const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(payload));
  return base64UrlEncode(String.fromCharCode(...new Uint8Array(sig)));
}
function timingSafeEqual(a, b) {
  if (a.length !== b.length) return false;
  const bufA = Buffer.from(a, "utf8");
  const bufB = Buffer.from(b, "utf8");
  return crypto.timingSafeEqual(bufA, bufB);
}
async function hmacVerify(payload, signature, secret, algo) {
  const expected = await hmacSign(payload, secret, algo);
  return timingSafeEqual(expected, signature);
}
function createJwtAuthMiddleware(options) {
  const algo = options.algorithm ?? "HS256";
  return async (req, next) => {
    const authHeader = req.headers["authorization"] ?? "";
    if (!authHeader.startsWith("Bearer ")) {
      return jsonError(401, "Unauthorized", "Missing or malformed Authorization header");
    }
    const token = authHeader.slice(7);
    const parts = token.split(".");
    if (parts.length !== 3) {
      return jsonError(401, "Unauthorized", "Malformed JWT token");
    }
    const [headerB64, payloadB64, signature] = parts;
    try {
      const valid = await hmacVerify(`${headerB64}.${payloadB64}`, signature, options.secret, algo);
      if (!valid) {
        return jsonError(401, "Unauthorized", "Invalid JWT signature");
      }
      let payload;
      try {
        payload = JSON.parse(base64UrlDecode(payloadB64));
      } catch (e) {
        return jsonError(401, "Unauthorized", "Malformed JWT payload");
      }
      if (payload.exp !== void 0 && payload.exp < Date.now() / 1e3) {
        return jsonError(401, "Unauthorized", "JWT token expired");
      }
      req.user = {
        id: payload.sub ?? "unknown",
        scopes: payload.scopes ?? [],
        type: "jwt"
      };
      return next();
    } catch (e) {
      console.warn(`error: ${e}`);
      return jsonError(401, "Unauthorized", "Invalid JWT token");
    }
  };
}
function createApiKeyAuthMiddleware(options) {
  const headerName = options.headerName ?? "x-api-key";
  return async (req, next) => {
    const key = req.headers[headerName] ?? "";
    if (!key) {
      return jsonError(401, "Unauthorized", `Missing ${headerName} header`);
    }
    if (!options.validKeys.has(key)) {
      return jsonError(401, "Unauthorized", "Invalid API key");
    }
    req.user = {
      id: `api-key:${createHash("sha256").update(key).digest("hex").slice(0, 16)}`,
      scopes: ["read", "write"],
      type: "api-key"
    };
    return next();
  };
}
function createCompositeAuthMiddleware(jwtOptions, apiKeyOptions) {
  const jwtMw = createJwtAuthMiddleware(jwtOptions);
  const apiKeyMw = createApiKeyAuthMiddleware(apiKeyOptions);
  return async (req, next) => {
    const authHeader = req.headers["authorization"] ?? "";
    const apiKeyHeader = req.headers[apiKeyOptions.headerName ?? "x-api-key"] ?? "";
    if (authHeader.startsWith("Bearer ")) {
      return jwtMw(req, next);
    }
    if (apiKeyHeader) {
      return apiKeyMw(req, next);
    }
    return jsonError(401, "Unauthorized", "Provide either Authorization Bearer token or API key");
  };
}
var init_auth = __esm({
  "src/api/middleware/auth.ts"() {
    "use strict";
    init_router();
  }
});

// src/api/index.ts
var api_exports = {};
__export(api_exports, {
  createApiServer: () => createApiServer,
  registerApiWithPlugin: () => registerApiWithPlugin
});
function createApiServer(services, config) {
  const router = new Router();
  const websocket = new WebSocketServer(services.workflowService);
  const wfRoutes = createWorkflowRoutes(services, services.templateRegistry);
  const exRoutes = createExecutionRoutes(services);
  const tplRoutes = createTemplateRoutes(services.templateRegistry);
  const evoRoutes = createEvolvedRoutes(services.evolutionStore, services.skillInventory);
  registerRoutes(router, { wfRoutes, exRoutes, tplRoutes, evoRoutes });
  if (config?.requireAuth !== false && (config?.jwt || config?.apiKeys)) {
    if (config.jwt && config.apiKeys) {
      router.use(createCompositeAuthMiddleware(config.jwt, config.apiKeys));
    } else if (config.jwt) {
      router.use(createJwtAuthMiddleware(config.jwt));
    } else if (config.apiKeys) {
      router.use(createApiKeyAuthMiddleware(config.apiKeys));
    }
  }
  router.use(errorHandlingMiddleware());
  websocket.init();
  return {
    router,
    websocket,
    async handle(req) {
      return router.handle(req);
    },
    handleWsMessage(wsId, raw) {
      websocket.handleMessage(wsId, raw);
    },
    close() {
      websocket.destroy();
    }
  };
}
function registerRoutes(router, routes) {
  router.get("/workflows", routes.wfRoutes.list);
  router.post("/workflows", routes.wfRoutes.create);
  router.get("/workflows/:id", routes.wfRoutes.get);
  router.put("/workflows/:id", routes.wfRoutes.update);
  router.delete("/workflows/:id", routes.wfRoutes.delete_);
  router.post("/workflows/:id/start", routes.wfRoutes.start);
  router.post("/workflows/:id/cancel", routes.wfRoutes.cancel);
  router.get("/executions", routes.exRoutes.list);
  router.get("/executions/:id", routes.exRoutes.getStatus);
  router.get("/executions/:id/logs", routes.exRoutes.getLogs);
  router.get("/templates", routes.tplRoutes.list);
  router.post("/templates", routes.tplRoutes.create);
  router.get("/templates/:id", routes.tplRoutes.get);
  router.get("/evolved", routes.evoRoutes.listEvolved);
  router.get("/evolved/stats", routes.evoRoutes.evolveStats);
  router.get("/evolved/search", routes.evoRoutes.searchEvolved);
  router.get("/evolved/:id", routes.evoRoutes.getEvolved);
  router.delete("/evolved/:id", routes.evoRoutes.deleteEvolved);
  router.post("/evolved/:id/record-usage", routes.evoRoutes.recordUsage);
  router.get("/skills", routes.evoRoutes.listSkills);
  router.get("/skills/search", routes.evoRoutes.searchSkills);
}
function errorHandlingMiddleware() {
  return async (_req, next) => {
    try {
      return await next();
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      const status = isHttpError2(err) ? err.status : 500;
      return jsonResponse(status, {
        error: status >= 500 ? "Internal Server Error" : "Bad Request",
        message,
        statusCode: status
      });
    }
  };
}
function isHttpError2(err) {
  return err instanceof Error && "status" in err && typeof err.status === "number";
}
function registerApiWithPlugin(api, services, config) {
  const server = createApiServer(services, config);
  api.services.register("soloflow.api-server", server);
  api.services.register("soloflow.websocket-server", server.websocket);
  api.rpc.register({
    name: "soloflow.api.handle",
    description: "Handle HTTP API request",
    handler: async (params) => {
      const req = params;
      const response = await server.handle(req);
      return response;
    }
  });
  api.rpc.register({
    name: "soloflow.api.ws-message",
    description: "Handle WebSocket message",
    handler: async (params) => {
      const wsId = params["wsId"];
      const raw = params["raw"];
      server.handleWsMessage(wsId, raw);
      return { ok: true };
    }
  });
  return () => {
    server.close();
    try {
      api.rpc.unregister("soloflow.api.handle");
    } catch (e) {
      console.warn(`best effort: ${e}`);
    }
    try {
      api.rpc.unregister("soloflow.api.ws-message");
    } catch (e) {
      console.warn(`best effort: ${e}`);
    }
    try {
      api.services.unregister("soloflow.api-server");
    } catch (e) {
      console.warn(`best effort: ${e}`);
    }
    try {
      api.services.unregister("soloflow.websocket-server");
    } catch (e) {
      console.warn(`best effort: ${e}`);
    }
  };
}
var init_api = __esm({
  "src/api/index.ts"() {
    "use strict";
    init_router();
    init_websocket();
    init_workflows();
    init_executions();
    init_templates();
    init_evolved();
    init_auth();
  }
});

// src/index.ts
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
import { Type } from "@sinclair/typebox";

// src/types.ts
var WORKFLOW_TRANSITIONS = {
  idle: ["queued"],
  queued: ["running", "cancelled"],
  running: ["paused", "completed", "failed", "cancelled"],
  paused: ["running", "cancelled"],
  completed: [],
  failed: ["queued"],
  cancelled: ["queued"]
};

// src/core/dag.ts
function buildDAG(steps) {
  const nodes = /* @__PURE__ */ new Map();
  const edges = [];
  for (const step2 of steps) {
    nodes.set(step2.id, {
      id: step2.id,
      dependencies: step2.dependencies,
      discipline: step2.discipline,
      action: step2.name
    });
    for (const dep of step2.dependencies) {
      edges.push({ from: dep, to: step2.id });
    }
  }
  const cycle = detectCycle({ nodes, edges, layers: [] });
  if (cycle) {
    throw new Error(`Circular dependency: ${cycle.join(" \u2192 ")}`);
  }
  const inDegree = /* @__PURE__ */ new Map();
  for (const id of nodes.keys()) inDegree.set(id, 0);
  for (const [, node] of nodes) {
    inDegree.set(node.id, node.dependencies.length);
  }
  const layers = [];
  const remaining = new Map(inDegree);
  let queue = Array.from(remaining.entries()).filter(([, d]) => d === 0).map(([id]) => id);
  while (queue.length > 0) {
    layers.push([...queue]);
    const nextQueue = [];
    for (const id of queue) {
      for (const [otherId, otherNode] of nodes) {
        if (otherNode.dependencies.includes(id)) {
          const newDeg = (remaining.get(otherId) ?? 0) - 1;
          remaining.set(otherId, newDeg);
          if (newDeg === 0) nextQueue.push(otherId);
        }
      }
    }
    queue = nextQueue;
  }
  return { nodes, edges, layers };
}
function topologicalSort(dag) {
  return dag.layers.flat();
}
function getReadySteps(dag, completed, running) {
  const ready = [];
  for (const [id, node] of dag.nodes) {
    if (completed.has(id) || running.has(id)) continue;
    if (node.dependencies.every((d) => completed.has(d))) {
      ready.push(id);
    }
  }
  return ready;
}
function detectCycle(dag) {
  const WHITE = 0, GRAY = 1, BLACK = 2;
  const color = /* @__PURE__ */ new Map();
  for (const id of dag.nodes.keys()) color.set(id, WHITE);
  const stack = [];
  function dfs(id) {
    color.set(id, GRAY);
    stack.push(id);
    const node = dag.nodes.get(id);
    if (node) {
      for (const dep of node.dependencies) {
        if (color.get(dep) === GRAY) {
          const cycleStart = stack.indexOf(dep);
          return [...stack.slice(cycleStart), dep];
        }
        if (color.get(dep) === WHITE) {
          const result = dfs(dep);
          if (result) return result;
        }
      }
    }
    color.set(id, BLACK);
    stack.pop();
    return null;
  }
  for (const id of dag.nodes.keys()) {
    if (color.get(id) === WHITE) {
      const result = dfs(id);
      if (result) return result;
    }
  }
  return null;
}

// src/services/workflow-service.ts
var InvalidTransitionError = class extends Error {
  constructor(workflowId, from, to) {
    super(`Invalid transition "${from}" \u2192 "${to}" for workflow ${workflowId}`);
    this.workflowId = workflowId;
    this.from = from;
    this.to = to;
    this.name = "InvalidTransitionError";
  }
  workflowId;
  from;
  to;
};
var WorkflowNotFoundError = class extends Error {
  constructor(workflowId) {
    super(`Workflow not found: ${workflowId}`);
    this.workflowId = workflowId;
    this.name = "WorkflowNotFoundError";
  }
  workflowId;
};
function now() {
  return Date.now();
}
var WorkflowService = class {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  store;
  listeners = /* @__PURE__ */ new Set();
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  constructor(store) {
    this.store = store ?? /* @__PURE__ */ new Map();
  }
  // ── Event helpers ──────────────────────────────────────────────────
  /** Subscribe to state events. Returns an unsubscribe function. */
  subscribe(listener) {
    this.listeners.add(listener);
    return () => {
      this.listeners.delete(listener);
    };
  }
  emit(event) {
    for (const listener of this.listeners) {
      listener(event);
    }
  }
  // ── FSM transition ─────────────────────────────────────────────────
  /**
   * Validate and apply a state transition.
   * @throws {InvalidTransitionError} if the transition is not allowed by WORKFLOW_TRANSITIONS.
   */
  transition(id, targetState) {
    const workflow = this.getOrThrow(id);
    const allowed = WORKFLOW_TRANSITIONS[workflow.state];
    if (!allowed.includes(targetState)) {
      throw new InvalidTransitionError(id, workflow.state, targetState);
    }
    const fromState = workflow.state;
    workflow.state = targetState;
    workflow.updatedAt = now();
    this.emit({
      type: "workflow:state_changed",
      workflowId: id,
      from: fromState,
      to: targetState
    });
  }
  getOrThrow(id) {
    const workflow = this.store.get(id);
    if (!workflow) throw new WorkflowNotFoundError(id);
    return workflow;
  }
  // ── CRUD ───────────────────────────────────────────────────────────
  /** Create a new workflow. Builds its DAG from steps and stores it. */
  create(workflow) {
    const steps = Array.from(workflow.steps.values());
    const dag = buildDAG(steps);
    const record = {
      ...workflow,
      dag,
      state: workflow.state ?? "idle",
      createdAt: workflow.createdAt ?? now(),
      updatedAt: now()
    };
    this.store.set(record.id, record);
    this.emit({ type: "workflow:created", workflowId: record.id });
    return record;
  }
  get(id) {
    return this.store.get(id);
  }
  /** List workflows with optional filtering and pagination. */
  list(filter) {
    let results = Array.from(this.store.values());
    if (filter) {
      if (filter.status !== void 0) {
        results = results.filter((w) => w.state === filter.status);
      }
      if (filter.template !== void 0) {
        results = results.filter(
          (w) => w.metadata["template"] === filter.template
        );
      }
      if (filter.offset !== void 0) {
        results = results.slice(filter.offset);
      }
      if (filter.limit !== void 0) {
        results = results.slice(0, filter.limit);
      }
    }
    return results;
  }
  /** Update an existing workflow in the store. */
  update(workflow) {
    this.getOrThrow(workflow.id);
    workflow.updatedAt = now();
    this.store.set(workflow.id, workflow);
    this.emit({ type: "workflow:state_changed", workflowId: workflow.id, from: workflow.state, to: workflow.state });
  }
  /** Delete a workflow by ID. */
  delete(id) {
    const existed = this.store.delete(id);
    if (!existed) throw new WorkflowNotFoundError(id);
    this.emit({ type: "workflow:deleted", workflowId: id });
  }
  // ── Lifecycle transitions ──────────────────────────────────────────
  /** Transition idle → queued → running (convenience for starting a workflow). */
  start(id) {
    const workflow = this.getOrThrow(id);
    if (workflow.state === "idle") {
      this.transition(id, "queued");
      this.transition(id, "running");
    } else if (workflow.state === "queued") {
      this.transition(id, "running");
    } else if (workflow.state !== "running") {
      throw new InvalidTransitionError(id, workflow.state, "running");
    }
  }
  /** Transition running → paused. */
  pause(id) {
    this.transition(id, "paused");
  }
  /** Transition paused → running. */
  resume(id) {
    this.transition(id, "running");
  }
  /**
   * Cancel a workflow.
   * When `force` is true, cancels from any non-terminal state.
   * Otherwise follows strict FSM rules.
   */
  cancel(id, force = false) {
    if (force) {
      const workflow = this.getOrThrow(id);
      const terminalStates = ["completed", "cancelled"];
      if (terminalStates.includes(workflow.state)) {
        throw new InvalidTransitionError(id, workflow.state, "cancelled");
      }
      const fromState = workflow.state;
      workflow.state = "cancelled";
      workflow.updatedAt = now();
      this.emit({
        type: "workflow:state_changed",
        workflowId: id,
        from: fromState,
        to: "cancelled"
      });
      return;
    }
    this.transition(id, "cancelled");
  }
  /** Retry a failed or cancelled workflow by re-queuing it. */
  retry(id) {
    this.transition(id, "queued");
  }
  // ── DAG helpers exposed for scheduler integration ───────────────────
  /** Get the topologically-sorted step IDs for a workflow. */
  getExecutionOrder(id) {
    const workflow = this.getOrThrow(id);
    return topologicalSort(workflow.dag);
  }
  /** Get the steps that are ready to execute given completed and running sets. */
  getReadySteps(id, completed, running) {
    const workflow = this.getOrThrow(id);
    return getReadySteps(workflow.dag, completed, running);
  }
};

// src/agents/index.ts
var disciplineDefaults = {
  deep: { maxTokens: 8192, temperature: 0.3 },
  quick: { maxTokens: 2048, temperature: 0.5 },
  visual: { maxTokens: 4096, temperature: 0.6 },
  ultrabrain: { maxTokens: 16384, temperature: 0.2 }
};
function getDefaultConfig(discipline) {
  return disciplineDefaults[discipline] ?? {};
}
async function executeAgentStep(step2, ctx, override) {
  const defaults = getDefaultConfig(step2.discipline);
  void { ...defaults, ...override, discipline: step2.discipline };
  const { DisciplineAgent: DisciplineAgent2 } = await Promise.resolve().then(() => (init_discipline(), discipline_exports));
  const agent = new DisciplineAgent2(step2.discipline);
  return agent.execute(
    step2,
    ctx.api,
    ctx.upstreamResults,
    ctx.workflowName
  );
}

// src/services/scheduler.ts
var DEFAULT_MAX_CONCURRENCY = 4;
var DEFAULT_RETRY_ATTEMPTS = 3;
var DEFAULT_RETRY_DELAY_MS = 1e3;
var DEFAULT_STEP_TIMEOUT_MS = 6e4;
var DEFAULT_WORKFLOW_TIMEOUT_FACTOR = 5;
var Semaphore = class {
  constructor(max) {
    this.max = max;
  }
  max;
  current = 0;
  queue = [];
  acquire() {
    if (this.current < this.max) {
      this.current++;
      return Promise.resolve();
    }
    return new Promise((resolve) => this.queue.push(resolve));
  }
  release() {
    if (this.current > 0) this.current--;
    const next = this.queue.shift();
    if (next) {
      this.current++;
      next();
    }
  }
};
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
async function withRetry(fn, maxAttempts, backoffMs) {
  let lastError;
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    try {
      return await fn();
    } catch (err) {
      lastError = err instanceof Error ? err : new Error(String(err));
      if (attempt < maxAttempts - 1) {
        await sleep(backoffMs * 2 ** attempt);
      }
    }
  }
  throw lastError;
}
function withTimeout(promise, ms, message) {
  let timer;
  return Promise.race([
    promise,
    new Promise((_, reject) => {
      timer = setTimeout(() => reject(new Error(message)), ms);
    })
  ]).finally(() => clearTimeout(timer));
}
function resolveOptions(opts) {
  return {
    maxConcurrency: opts?.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY,
    retryAttempts: opts?.retryAttempts ?? DEFAULT_RETRY_ATTEMPTS,
    retryDelayMs: opts?.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS,
    stepTimeoutMs: opts?.timeoutMs ?? DEFAULT_STEP_TIMEOUT_MS,
    onStepStart: opts?.onStepStart,
    onStepComplete: opts?.onStepComplete,
    onStepError: opts?.onStepError
  };
}
var Scheduler = class {
  constructor(workflowService, options) {
    this.workflowService = workflowService;
    this.opts = resolveOptions(options);
  }
  workflowService;
  opts;
  cancelled = /* @__PURE__ */ new Set();
  statuses = /* @__PURE__ */ new Map();
  // ── Public API ──────────────────────────────────────────────────────
  /**
   * Execute an entire workflow DAG.
   *
   * Iterates through layers of ready steps, running each layer in parallel
   * (bounded by `maxConcurrency`). Individual step failures are recorded but
   * do not crash the workflow — steps whose dependencies failed are skipped.
   */
  async execute(workflowId, api) {
    const workflow = this.workflowService.get(workflowId);
    if (!workflow) {
      throw new Error(`Workflow not found: ${workflowId}`);
    }
    if (workflow.state !== "running") {
      throw new Error(
        `Workflow ${workflowId} is not running (current state: ${workflow.state})`
      );
    }
    const order = topologicalSort(workflow.dag);
    const totalSteps = workflow.steps.size;
    if (totalSteps === 0 || order.length === 0) {
      return {
        workflowId,
        completed: [],
        failed: [],
        totalDurationMs: 0
      };
    }
    api.logger.info(
      `[scheduler] Execution order: ${order.join(" \u2192 ")} (${totalSteps} steps)`
    );
    const startedAt = Date.now();
    const completed = /* @__PURE__ */ new Set();
    const failed = [];
    const running = /* @__PURE__ */ new Set();
    const stepResultsMap = /* @__PURE__ */ new Map();
    const status = {
      workflowId,
      state: "running",
      completedSteps: [],
      failedSteps: [],
      runningSteps: [],
      startedAt,
      updatedAt: startedAt,
      progress: 0
    };
    this.statuses.set(workflowId, status);
    const workflowTimeoutMs = this.opts.stepTimeoutMs * totalSteps * DEFAULT_WORKFLOW_TIMEOUT_FACTOR;
    try {
      await withTimeout(
        this.runLoop(workflow, api, completed, failed, running, status, stepResultsMap),
        workflowTimeoutMs,
        `Workflow ${workflowId} timed out after ${workflowTimeoutMs}ms`
      );
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      api.logger.error(`[scheduler] ${msg}`);
      if (status.state === "running") {
        status.state = "failed";
      }
    }
    status.runningSteps = [];
    status.updatedAt = Date.now();
    status.progress = totalSteps > 0 ? (completed.size + failed.length) / totalSteps : 1;
    return {
      workflowId,
      completed: Array.from(completed),
      failed,
      totalDurationMs: Date.now() - startedAt
    };
  }
  /**
   * Execute a single step by ID.
   *
   * Searches across all workflows to locate the step, then runs it with the
   * configured retry and timeout policies.
   */
  async executeStep(stepId, api) {
    const found = this.findStep(stepId);
    if (!found) {
      throw new Error(`Step not found: ${stepId}`);
    }
    const { step: step2, workflow } = found;
    api.logger.debug?.(`[scheduler] Executing step ${stepId} (${step2.discipline})`);
    this.opts.onStepStart?.(stepId);
    const stepResultsMap = /* @__PURE__ */ new Map();
    const result = await withRetry(
      () => withTimeout(
        this.runAgentStep(step2, api, stepResultsMap, workflow.name),
        this.opts.stepTimeoutMs,
        `Step ${stepId} timed out after ${this.opts.stepTimeoutMs}ms`
      ),
      this.opts.retryAttempts,
      this.opts.retryDelayMs
    );
    step2.state = "completed";
    step2.result = result.output;
    step2.completedAt = Date.now();
    this.opts.onStepComplete?.(stepId, result);
    return result;
  }
  /**
   * Cancel a running workflow execution.
   *
   * The cancellation flag is checked between execution waves — in-flight
   * steps will still complete, but no new waves will be launched.
   */
  cancel(workflowId) {
    this.cancelled.add(workflowId);
    const status = this.statuses.get(workflowId);
    if (status && status.state === "running") {
      status.state = "cancelled";
      status.updatedAt = Date.now();
    }
  }
  /**
   * Get the current execution status of a workflow.
   */
  getStatus(workflowId) {
    return this.statuses.get(workflowId);
  }
  // ── Internal: Execution Loop ────────────────────────────────────────
  /**
   * Core loop: repeatedly resolves ready steps and runs each wave in
   * parallel via `Promise.allSettled`, bounded by the semaphore.
   */
  async runLoop(workflow, api, completed, failed, running, status, stepResultsMap) {
    const semaphore = new Semaphore(this.opts.maxConcurrency);
    const failedStepIds = /* @__PURE__ */ new Set();
    while (true) {
      if (this.cancelled.has(workflow.id)) {
        status.state = "cancelled";
        status.updatedAt = Date.now();
        return;
      }
      const readyIds = getReadySteps(workflow.dag, completed, running);
      const executable = readyIds.filter((id) => {
        if (failedStepIds.has(id)) return false;
        const node = workflow.dag.nodes.get(id);
        if (!node) return false;
        return !node.dependencies.some((dep) => failedStepIds.has(dep));
      });
      if (executable.length === 0 && running.size === 0) {
        break;
      }
      if (executable.length === 0) {
        await sleep(50);
        continue;
      }
      const promises = executable.map(
        (stepId) => this.runManagedStep(
          workflow,
          stepId,
          api,
          completed,
          failed,
          failedStepIds,
          running,
          semaphore,
          status,
          stepResultsMap
        )
      );
      await Promise.allSettled(promises);
    }
    status.state = failed.length > 0 && completed.size === 0 ? "failed" : "completed";
    status.updatedAt = Date.now();
  }
  /**
   * Execute a single step within the managed workflow context.
   * Handles semaphore, retry, timeout, state updates, and callbacks.
   */
  async runManagedStep(workflow, stepId, api, completed, failed, failedStepIds, running, semaphore, status, stepResultsMap) {
    await semaphore.acquire();
    running.add(stepId);
    status.runningSteps = Array.from(running);
    status.updatedAt = Date.now();
    const step2 = workflow.steps.get(stepId);
    if (!step2) {
      running.delete(stepId);
      semaphore.release();
      return;
    }
    step2.state = "running";
    step2.startedAt = Date.now();
    this.opts.onStepStart?.(stepId);
    try {
      const result = await withRetry(
        () => withTimeout(
          this.runAgentStep(step2, api, stepResultsMap, workflow.name),
          this.opts.stepTimeoutMs,
          `Step ${stepId} timed out after ${this.opts.stepTimeoutMs}ms`
        ),
        this.opts.retryAttempts,
        this.opts.retryDelayMs
      );
      step2.state = "completed";
      step2.result = result.output;
      step2.completedAt = Date.now();
      stepResultsMap.set(stepId, result);
      completed.add(stepId);
      status.completedSteps = Array.from(completed);
      status.progress = workflow.steps.size > 0 ? completed.size / workflow.steps.size : 1;
      status.updatedAt = Date.now();
      this.opts.onStepComplete?.(stepId, result);
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      step2.state = "failed";
      step2.error = message;
      step2.completedAt = Date.now();
      failed.push({ stepId, error: message });
      failedStepIds.add(stepId);
      status.failedSteps = [...failed];
      status.updatedAt = Date.now();
      this.opts.onStepError?.(
        stepId,
        err instanceof Error ? err : new Error(message)
      );
      api.logger.warn(
        `[scheduler] Step ${stepId} failed after ${this.opts.retryAttempts} attempts: ${message}`
      );
    } finally {
      running.delete(stepId);
      status.runningSteps = Array.from(running);
      semaphore.release();
    }
  }
  // ── Internal: Agent Execution ───────────────────────────────────────
  /** Delegate to the agent discipline executor. */
  async runAgentStep(step2, api, upstreamResults, workflowName) {
    return executeAgentStep(step2, { api, upstreamResults, workflowName });
  }
  // ── Internal: Step Lookup ───────────────────────────────────────────
  /** Find a step by ID across all managed workflows. */
  findStep(stepId) {
    for (const workflow of this.workflowService.list()) {
      const step2 = workflow.steps.get(stepId);
      if (step2) return { workflow, step: step2 };
    }
    return void 0;
  }
};

// src/services/template-registry.ts
function step(id) {
  return id;
}
var researchTemplate = {
  name: "Research Workflow",
  description: "Search the web for a topic, analyze the findings with a deep-reasoning agent, and produce a written summary.",
  steps: [
    {
      id: step("research-search"),
      name: "Web Search",
      discipline: "quick",
      dependencies: [],
      config: {
        tool: "web-search",
        prompt: "Search the web for the latest information on the given topic. Return the top 5 most relevant results with titles, URLs, and brief summaries.",
        topicVar: "topic",
        maxResults: 5
      }
    },
    {
      id: step("research-analysis"),
      name: "Analyze Results",
      discipline: "deep",
      dependencies: [step("research-search")],
      config: {
        tool: "data-analysis",
        prompt: "Analyze the search results from the previous step. Identify key themes, compare different viewpoints, highlight contradictions, and extract actionable insights.",
        inputFrom: step("research-search")
      }
    },
    {
      id: step("research-summary"),
      name: "Write Summary",
      discipline: "deep",
      dependencies: [step("research-analysis")],
      config: {
        tool: "writer",
        prompt: "Based on the analysis, write a comprehensive research summary in markdown with an executive summary, key findings, and conclusions.",
        inputFrom: step("research-analysis"),
        format: "markdown"
      }
    }
  ]
};
var contentTemplate = {
  name: "Content Creation Workflow",
  description: "Generate ideas, write content, create visuals, and prepare for publishing \u2014 end-to-end content production.",
  steps: [
    {
      id: step("content-ideate"),
      name: "Generate Content Ideas",
      discipline: "quick",
      dependencies: [],
      config: {
        tool: "idea",
        prompt: "Generate 5 creative content ideas for the given topic. For each idea provide a title, 2-sentence description, target audience, and suggested format.",
        topicVar: "topic",
        count: 5
      }
    },
    {
      id: step("content-write"),
      name: "Write Content",
      discipline: "deep",
      dependencies: [step("content-ideate")],
      config: {
        tool: "writer",
        prompt: "Write full content based on the selected idea with a compelling introduction, well-structured body, and strong conclusion.",
        inputFrom: step("content-ideate"),
        format: "markdown",
        minWords: 800,
        maxWords: 2e3
      }
    },
    {
      id: step("content-visual"),
      name: "Generate Cover Image",
      discipline: "visual",
      dependencies: [step("content-write")],
      config: {
        tool: "visual",
        prompt: "Design a cover image or thumbnail for the content. The visual should capture the core theme and be eye-catching.",
        inputFrom: step("content-write"),
        dimensions: { width: 1200, height: 630 },
        style: "modern-clean"
      }
    },
    {
      id: step("content-publish"),
      name: "Format and Prepare",
      discipline: "quick",
      dependencies: [step("content-write"), step("content-visual")],
      config: {
        tool: "publisher",
        prompt: "Format the content and visual into a publishable package. Generate metadata, apply final formatting, and produce a ready-to-publish output.",
        contentFrom: step("content-write"),
        visualFrom: step("content-visual"),
        platforms: ["blog", "twitter", "linkedin"]
      }
    }
  ]
};
var codeReviewTemplate = {
  name: "Code Review Workflow",
  description: "Automated code review: reads changed files, analyzes for issues using deep reasoning, and generates a structured review report.",
  steps: [
    {
      id: step("review-read"),
      name: "Read Code",
      discipline: "quick",
      dependencies: [],
      config: {
        tool: "code-reader",
        prompt: "Read and extract the code changes. Fetch the diff for the specified pull request or file paths.",
        repoVar: "repo",
        prVar: "pr",
        includeContext: true,
        contextLines: 5
      }
    },
    {
      id: step("review-analyze"),
      name: "Find Issues",
      discipline: "ultrabrain",
      dependencies: [step("review-read")],
      config: {
        tool: "analyzer",
        prompt: "Perform a thorough code review analysis checking for bugs, security vulnerabilities, performance issues, and anti-patterns.",
        inputFrom: step("review-read"),
        checks: [
          "bug-detection",
          "security-vulnerabilities",
          "performance",
          "code-style",
          "anti-patterns",
          "error-handling",
          "concurrency"
        ]
      }
    },
    {
      id: step("review-report"),
      name: "Generate Review Report",
      discipline: "deep",
      dependencies: [step("review-analyze")],
      config: {
        tool: "reporter",
        prompt: "Generate a comprehensive code review report organized by severity with file locations, suggested fixes, and an overall assessment.",
        inputFrom: step("review-analyze"),
        format: "markdown",
        includeCodeSnippets: true,
        includeFixSuggestions: true
      }
    }
  ]
};
var TemplateRegistry = class {
  templates = /* @__PURE__ */ new Map();
  constructor() {
    this.register("research", researchTemplate);
    this.register("content", contentTemplate);
    this.register("code-review", codeReviewTemplate);
  }
  /** Register a template under the given name. Overwrites any existing entry. */
  register(name, template) {
    this.templates.set(name, template);
  }
  /** Retrieve a template by name, or `undefined` if not registered. */
  get(name) {
    return this.templates.get(name);
  }
  /** Check whether a template with the given name exists. */
  has(name) {
    return this.templates.has(name);
  }
  /** List all registered template names. */
  list() {
    return Array.from(this.templates.keys());
  }
  /** Get all registered templates as an array of `[name, template]` pairs. */
  entries() {
    return Array.from(this.templates.entries());
  }
};

// src/index.ts
import path3 from "node:path";
import { fileURLToPath } from "node:url";
import os2 from "node:os";

// src/skills/task-detector.ts
var TWO_HOURS_MS = 2 * 60 * 60 * 1e3;
var MIN_PATTERN_OCCURRENCES = 2;
var JACCARD_THRESHOLD = 0.5;
function normalize(input) {
  return input.toLowerCase().trim().replace(/\s+/g, " ");
}
function stepSignature(name, discipline) {
  return `${discipline}:${normalize(name)}`;
}
function configKeys(config) {
  return Object.keys(config).sort();
}
function jaccard(a, b) {
  const setA = new Set(a);
  const setB = new Set(b);
  let intersection = 0;
  for (const item of setA) {
    if (setB.has(item)) intersection++;
  }
  const union = setA.size + setB.size - intersection;
  return union === 0 ? 0 : intersection / union;
}
function extractKeywords(text) {
  return normalize(text).split(/[^\w\u4e00-\u9fff]+/).filter((t) => t.length >= 2);
}
var TOOL_CALL_RE = /(\w+)\s*\(/g;
var TaskDetector = class {
  taskHistory = [];
  detectTasks(workflow) {
    if (workflow.state !== "completed") return null;
    const steps = Array.from(workflow.steps.values());
    if (steps.length === 0) return null;
    const completedSteps = steps.filter((s) => s.state === "completed");
    if (completedSteps.length === 0) return null;
    const durationMs = completedSteps.reduce((sum, s) => {
      const stepDuration = s.completedAt && s.startedAt ? s.completedAt - s.startedAt : 0;
      return sum + stepDuration;
    }, 0);
    if (durationMs > TWO_HOURS_MS) return null;
    const detectedSteps = completedSteps.map((s) => ({
      name: s.name,
      discipline: s.discipline,
      config: s.config,
      signature: stepSignature(s.name, s.discipline),
      completedAt: s.completedAt
    }));
    const signatureSequence = detectedSteps.map((s) => s.signature).join("|");
    const task = {
      workflowId: workflow.id,
      workflowName: workflow.name,
      steps: detectedSteps,
      signatureSequence,
      durationMs,
      completedAt: workflow.updatedAt
    };
    this.taskHistory.push(task);
    return task;
  }
  /**
   * Detect task patterns from completed workflows.
   * Now supports fuzzy matching via Jaccard similarity.
   */
  findPatterns(taskHistory) {
    const history = taskHistory ?? this.taskHistory;
    if (history.length < MIN_PATTERN_OCCURRENCES) return [];
    const groups = /* @__PURE__ */ new Map();
    for (const task of history) {
      const existing = groups.get(task.signatureSequence);
      if (existing) {
        existing.push(task);
      } else {
        groups.set(task.signatureSequence, [task]);
      }
    }
    const patterns = [];
    for (const [signature, tasks] of groups) {
      if (tasks.length < MIN_PATTERN_OCCURRENCES) continue;
      const reference = tasks[0];
      const stepSignatures = signature.split("|");
      const disciplines = reference.steps.map((s) => s.discipline);
      const paramTemplates = reference.steps.map((s) => {
        const keys = configKeys(s.config);
        const template = {};
        for (const key of keys) {
          template[key] = typeof s.config[key];
        }
        return template;
      });
      const nameCounts = /* @__PURE__ */ new Map();
      for (const t of tasks) {
        nameCounts.set(t.workflowName, (nameCounts.get(t.workflowName) ?? 0) + 1);
      }
      let bestName = "";
      let bestCount = 0;
      for (const [name, count] of nameCounts) {
        if (count > bestCount) {
          bestName = name;
          bestCount = count;
        }
      }
      const suggestedSteps = reference.steps.map((s) => ({
        name: s.name,
        discipline: s.discipline
      }));
      patterns.push({
        id: `pattern-${signature.replace(/[^a-z0-9]/g, "-")}`,
        stepSignatures,
        paramTemplates,
        occurrenceCount: tasks.length,
        lastSeen: Math.max(...tasks.map((t) => t.completedAt)),
        workflowIds: tasks.map((t) => t.workflowId),
        disciplines,
        confidence: 1,
        suggestedWorkflowName: bestName,
        suggestedSteps
      });
    }
    const merged = [];
    const assigned = /* @__PURE__ */ new Set();
    for (let i = 0; i < patterns.length; i++) {
      if (assigned.has(i)) continue;
      assigned.add(i);
      let group = [patterns[i]];
      for (let j = i + 1; j < patterns.length; j++) {
        if (assigned.has(j)) continue;
        const sigA = patterns[i].stepSignatures;
        const sigB = patterns[j].stepSignatures;
        const sim = jaccard(sigA, sigB);
        if (sim >= JACCARD_THRESHOLD) {
          group.push(patterns[j]);
          assigned.add(j);
        }
      }
      if (group.length > 1) {
        const totalOcc = group.reduce((s, p) => s + p.occurrenceCount, 0);
        const primary = group.sort((a, b) => b.occurrenceCount - a.occurrenceCount)[0];
        primary.confidence = Math.max(...group.map((p) => jaccard(
          p.stepSignatures,
          primary.stepSignatures
        )));
        primary.occurrenceCount = totalOcc;
        primary.workflowIds = group.flatMap((p) => p.workflowIds);
        primary.lastSeen = Math.max(...group.map((p) => p.lastSeen));
      }
      merged.push(group[0]);
    }
    return merged.sort((a, b) => b.occurrenceCount - a.occurrenceCount);
  }
  /**
   * Detect tasks from conversation history.
   * Splits messages into task segments by 2-hour timeout,
   * then extracts keywords, tools used, and topics per segment.
   */
  detectFromConversation(messages) {
    if (messages.length === 0) return [];
    const now2 = Date.now();
    const base = messages[0].timestamp ?? now2;
    const withTs = messages.map((m, i) => ({
      ...m,
      ts: m.timestamp ?? base + i * 6e4
    }));
    const segments = [];
    let current = [withTs[0]];
    for (let i = 1; i < withTs.length; i++) {
      const prev = withTs[i - 1];
      const curr = withTs[i];
      if (curr.ts - prev.ts > TWO_HOURS_MS) {
        segments.push(current);
        current = [];
      }
      current.push({ role: curr.role, content: curr.content, timestamp: curr.ts });
    }
    segments.push(current);
    return segments.map((seg, idx) => {
      const allText = seg.map((m) => m.content).join(" ");
      const keywords = extractKeywords(allText);
      const tools = /* @__PURE__ */ new Set();
      for (const m of seg) {
        if (m.role === "assistant") {
          let match;
          const re = new RegExp(TOOL_CALL_RE.source, "g");
          while ((match = re.exec(m.content)) !== null) {
            tools.add(match[1].toLowerCase());
          }
        }
      }
      const freq = /* @__PURE__ */ new Map();
      for (const kw of keywords) {
        freq.set(kw, (freq.get(kw) ?? 0) + 1);
      }
      const topics = [...freq.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([w]) => w);
      return {
        id: `conv-task-${idx}-${seg[0].timestamp ?? now2}`,
        keywords,
        tools: [...tools],
        topics,
        startTime: seg[0].timestamp ?? now2,
        endTime: seg[seg.length - 1].timestamp ?? now2,
        messageCount: seg.length
      };
    });
  }
  /**
   * Recommend a workflow template based on the current user message.
   * Returns the best matching template ID + confidence, or null.
   */
  recommendWorkflow(userMessage, templates) {
    const msgTokens = extractKeywords(userMessage);
    if (msgTokens.length === 0) return null;
    const patterns = this.findPatterns();
    let bestPattern = null;
    let bestPatternScore = 0;
    for (const p of patterns) {
      const patternTokens = p.stepSignatures.flatMap((s) => extractKeywords(s));
      const sim = jaccard(msgTokens, patternTokens);
      if (sim > bestPatternScore) {
        bestPatternScore = sim;
        bestPattern = p;
      }
    }
    if (templates && templates.length > 0) {
      let bestTemplateId = "";
      let bestTemplateScore = 0;
      let bestTemplateKeywords = [];
      for (const t of templates) {
        const tTokens = [
          ...extractKeywords(t.name),
          ...extractKeywords(t.description),
          ...t.triggers?.flatMap((tr) => extractKeywords(tr)) ?? [],
          ...t.tags?.flatMap((tag) => extractKeywords(tag)) ?? []
        ];
        const sim = jaccard(msgTokens, tTokens);
        if (sim > bestTemplateScore) {
          bestTemplateScore = sim;
          bestTemplateId = t.id;
          bestTemplateKeywords = msgTokens.filter((tk) => tTokens.includes(tk));
        }
      }
      if (bestTemplateScore >= JACCARD_THRESHOLD) {
        return {
          templateId: bestTemplateId,
          confidence: bestTemplateScore,
          matchedKeywords: bestTemplateKeywords
        };
      }
    }
    if (bestPattern && bestPatternScore >= JACCARD_THRESHOLD) {
      return {
        templateId: bestPattern.id,
        confidence: bestPatternScore,
        matchedKeywords: msgTokens.filter(
          (tk) => bestPattern.stepSignatures.some((s) => s.includes(tk))
        )
      };
    }
    return null;
  }
  getHistory() {
    return this.taskHistory;
  }
  clearHistory() {
    this.taskHistory = [];
  }
};

// src/index.ts
init_hooks();
init_discipline();
init_memory();
init_vector();

// src/visual/yaml-sync.ts
var import_yaml = __toESM(require_dist(), 1);
function dagToYaml(dag, metadata) {
  const steps = [];
  for (const [id, node] of dag.nodes) {
    steps.push({
      id,
      name: node.action,
      discipline: node.discipline,
      depends_on: node.dependencies.map((d) => d)
    });
  }
  const doc = {
    name: metadata?.name ?? "unnamed-workflow",
    description: metadata?.description,
    version: metadata?.version,
    author: metadata?.author,
    steps
  };
  return (0, import_yaml.stringify)(doc, { indentSeq: true, lineWidth: 0 });
}
function yamlToDag(yaml) {
  let parsed;
  try {
    parsed = (0, import_yaml.parse)(yaml);
  } catch (err) {
    throw new SyntaxError(
      `Invalid YAML: ${err instanceof Error ? err.message : String(err)}`
    );
  }
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
    throw new TypeError("YAML root must be a mapping (object)");
  }
  const root = parsed;
  const validDisciplines = /* @__PURE__ */ new Set([
    "deep",
    "quick",
    "visual",
    "ultrabrain"
  ]);
  const rawSteps = root["steps"];
  if (!Array.isArray(rawSteps)) {
    throw new TypeError("YAML must contain a 'steps' array");
  }
  const nodes = /* @__PURE__ */ new Map();
  const edges = [];
  const layerMap = /* @__PURE__ */ new Map();
  for (const raw of rawSteps) {
    const id = String(raw["id"] ?? "");
    if (!id) {
      throw new TypeError("Each step must have a non-empty 'id'");
    }
    const discipline = String(raw["discipline"] ?? "quick");
    if (!validDisciplines.has(discipline)) {
      throw new TypeError(
        `Step '${id}' has invalid discipline '${discipline}'. Must be one of: deep, quick, visual, ultrabrain`
      );
    }
    const deps = Array.isArray(raw["depends_on"]) ? raw["depends_on"].map((d) => String(d)) : [];
    nodes.set(id, {
      id,
      dependencies: deps,
      discipline,
      action: String(raw["name"] ?? id)
    });
    for (const dep of deps) {
      edges.push({ from: dep, to: id });
    }
  }
  const visiting = /* @__PURE__ */ new Set();
  const visited = /* @__PURE__ */ new Set();
  function computeLayer(id) {
    if (layerMap.has(id)) return layerMap.get(id);
    if (visiting.has(id)) {
      layerMap.set(id, 0);
      return 0;
    }
    visiting.add(id);
    const node = nodes.get(id);
    let maxDepLayer = -1;
    if (node) {
      for (const dep of node.dependencies) {
        if (nodes.has(dep)) {
          maxDepLayer = Math.max(maxDepLayer, computeLayer(dep));
        }
      }
    }
    visiting.delete(id);
    visited.add(id);
    const layer = maxDepLayer + 1;
    layerMap.set(id, layer);
    return layer;
  }
  for (const id of nodes.keys()) {
    computeLayer(id);
  }
  const maxLayer = Math.max(0, ...Array.from(layerMap.values()));
  const layers = Array.from({ length: maxLayer + 1 }, () => []);
  for (const [id, layer] of layerMap) {
    layers[layer].push(id);
  }
  const dag = {
    nodes,
    edges,
    layers
  };
  const metadata = {
    name: typeof root["name"] === "string" ? root["name"] : "unnamed-workflow",
    description: typeof root["description"] === "string" ? root["description"] : void 0,
    version: typeof root["version"] === "string" ? root["version"] : void 0,
    author: typeof root["author"] === "string" ? root["author"] : void 0
  };
  return { dag, metadata };
}
function validateWorkflow(dag) {
  const errors = [];
  const warnings = [];
  const nodeIds = new Set(dag.nodes.keys());
  const WHITE = 0, GRAY = 1, BLACK = 2;
  const color = /* @__PURE__ */ new Map();
  for (const id of nodeIds) color.set(id, WHITE);
  const path4 = [];
  function dfs(id) {
    color.set(id, GRAY);
    path4.push(id);
    const node = dag.nodes.get(id);
    if (node) {
      for (const dep of node.dependencies) {
        if (color.get(dep) === GRAY) return true;
        if (color.get(dep) === WHITE && dfs(dep)) return true;
      }
    }
    color.set(id, BLACK);
    path4.pop();
    return false;
  }
  for (const id of nodeIds) {
    path4.length = 0;
    if (color.get(id) === WHITE && dfs(id)) {
      errors.push(
        `Cycle detected: ${path4.map((s) => s).join(" \u2192 ")} \u2192 ${path4[0] ?? id}`
      );
    }
  }
  for (const [id, node] of dag.nodes) {
    for (const dep of node.dependencies) {
      if (!nodeIds.has(dep)) {
        errors.push(
          `Step '${id}' depends on '${dep}' which does not exist`
        );
      }
    }
  }
  const referencedAsTarget = /* @__PURE__ */ new Set();
  for (const edge of dag.edges) {
    referencedAsTarget.add(edge.to);
  }
  for (const [id] of dag.nodes) {
    const node = dag.nodes.get(id);
    if (node && node.dependencies.length === 0 && !referencedAsTarget.has(id)) {
      if (dag.nodes.size > 1) {
      }
    }
  }
  const roots = [];
  for (const [id, node] of dag.nodes) {
    if (node.dependencies.length === 0) {
      roots.push(id);
    }
  }
  if (roots.length === 0 && dag.nodes.size > 0) {
    errors.push("No root steps found \u2014 every step has at least one dependency");
  }
  const reachable = /* @__PURE__ */ new Set();
  function markReachable(id) {
    if (reachable.has(id)) return;
    reachable.add(id);
    const node = dag.nodes.get(id);
    if (node) {
      for (const dep of node.dependencies) {
        markReachable(dep);
      }
    }
  }
  for (const id of nodeIds) {
    markReachable(id);
  }
  const dependedUpon = /* @__PURE__ */ new Set();
  for (const [, node] of dag.nodes) {
    for (const dep of node.dependencies) {
      dependedUpon.add(dep);
    }
  }
  for (const edge of dag.edges) {
    dependedUpon.add(edge.from);
  }
  if (dag.nodes.size > 1) {
    for (const [id, node] of dag.nodes) {
      if (node.dependencies.length === 0 && !dependedUpon.has(id)) {
        warnings.push(
          `Step '${id}' is disconnected (no dependencies and nothing depends on it)`
        );
      }
    }
  }
  for (const edge of dag.edges) {
    if (!nodeIds.has(edge.from)) {
      errors.push(
        `Edge references non-existent source '${edge.from}'`
      );
    }
    if (!nodeIds.has(edge.to)) {
      errors.push(
        `Edge references non-existent target '${edge.to}'`
      );
    }
  }
  return {
    valid: errors.length === 0,
    errors,
    warnings
  };
}
function previewWorkflow(dag) {
  const lines = [];
  if (dag.nodes.size === 0) {
    return "(empty workflow)";
  }
  lines.push("Workflow Preview");
  lines.push("=".repeat(50));
  lines.push("");
  const totalSteps = dag.nodes.size;
  const totalEdges = dag.edges.length;
  lines.push(`Steps: ${totalSteps} | Dependencies: ${totalEdges}`);
  lines.push("");
  if (dag.layers.length > 0) {
    lines.push("Execution Order (by layer):");
    lines.push("-".repeat(40));
    for (let i = 0; i < dag.layers.length; i++) {
      const layer = dag.layers[i];
      const stepLabels = layer.map((id) => {
        const node = dag.nodes.get(id);
        const name = node?.action ?? id;
        const deps = node && node.dependencies.length > 0 ? ` [needs: ${node.dependencies.map((d) => d).join(", ")}]` : "";
        return `${name}${deps}`;
      });
      const prefix = layer.length > 1 ? `  Layer ${i} (parallel):` : `  Layer ${i}:`;
      lines.push(prefix);
      for (const label of stepLabels) {
        lines.push(`    - ${label}`);
      }
    }
  }
  lines.push("");
  lines.push("Dependency Graph:");
  lines.push("-".repeat(40));
  for (const [_id, node] of dag.nodes) {
    const name = node.action;
    const discipline = node.discipline;
    if (node.dependencies.length === 0) {
      lines.push(`  ${name} (${discipline}) \u2192 entry`);
    } else {
      const deps = node.dependencies.map((d) => {
        const depNode = dag.nodes.get(d);
        return depNode?.action ?? d;
      });
      lines.push(
        `  ${deps.join(" \u2192 ")} \u2192 ${name} (${discipline})`
      );
    }
  }
  return lines.join("\n");
}

// src/index.ts
var PLUGIN_NAME = "soloflow";
var PLUGIN_VERSION = "0.8.0";
var index_default = definePluginEntry({
  id: "workflow-orchestration",
  name: "SoloFlow",
  description: "DAG-based workflow orchestration with discipline agents, memory, and skill evolution",
  register(api) {
    const log = api.logger ?? {
      info: (...a) => console.log(`[${PLUGIN_NAME}]`, ...a),
      warn: (...a) => console.warn(`[${PLUGIN_NAME}]`, ...a),
      error: (...a) => console.error(`[${PLUGIN_NAME}]`, ...a),
      debug: (...a) => console.debug(`[${PLUGIN_NAME}]`, ...a)
    };
    log.info(`v${PLUGIN_VERSION} activating (safe mode)\u2026`);
    const workflowService = new WorkflowService();
    const scheduler = new Scheduler(workflowService);
    const templateRegistry = new TemplateRegistry();
    const dataDir = path3.join(os2.homedir(), ".openclaw", "data", "soloflow");
    let sqliteStore = null;
    let memorySystem = null;
    let vectorSystem = null;
    let evolutionStore = null;
    let evolutionAnalyzer = null;
    let skillInventory = null;
    let skillAnalyzer = null;
    let mcpInventory = null;
    let hookSystem2 = null;
    let unregisterBuiltinHooks = null;
    let workflowSubscription = null;
    const MAX_STEP_RESULT_CHARS = 2e3;
    const MAX_WORKFLOW_CONTENT_CHARS = 5e4;
    const decomposedWorkflows = /* @__PURE__ */ new Set();
    function decomposeWorkflow(wf) {
      if (!memorySystem) return Promise.resolve();
      if (decomposedWorkflows.has(wf.id)) return Promise.resolve();
      decomposedWorkflows.add(wf.id);
      try {
        const stepTexts = Array.from(wf.steps.values()).map((s) => {
          const raw = typeof s.result === "string" ? s.result : JSON.stringify(s.result ?? "");
          const truncated = raw.length > MAX_STEP_RESULT_CHARS ? raw.slice(0, MAX_STEP_RESULT_CHARS) + "...[truncated]" : raw;
          return `[${s.name}] ${s.state}: ${truncated}`;
        }).join("\n\n");
        if (stepTexts.length < 50) return Promise.resolve();
        const content = stepTexts.length > MAX_WORKFLOW_CONTENT_CHARS ? stepTexts.slice(0, MAX_WORKFLOW_CONTENT_CHARS) + "\n...[content truncated]" : stepTexts;
        return memorySystem.decomposeDocument({
          id: wf.id,
          content,
          sourceType: "workflow_result",
          createdAt: Date.now()
        });
      } catch (e) {
        log.debug?.(`R\xB3Mem decompose skipped: ${e}`);
        return Promise.resolve();
      }
    }
    void (async () => {
      try {
        const { SqliteStore: SqliteStore2 } = await Promise.resolve().then(() => (init_sqlite_store(), sqlite_store_exports));
        const store = new SqliteStore2(dataDir);
        store.loadAll();
        workflowService.store = store;
        sqliteStore = store;
        log.info(`SQLite store loaded from ${dataDir}`);
        const mod = await Promise.resolve().then(() => (init_memory(), memory_exports));
        memorySystem = new mod.MemorySystem({ disableLobsterPress: true });
        await memorySystem.init();
        try {
          const r3mem = await Promise.resolve().then(() => (init_r3mem_store(), r3mem_store_exports));
          const r3memStore = new r3mem.R3MemStore(store.database);
          memorySystem.setR3MemStore(r3memStore);
        } catch (e) {
          log.debug?.(`R\xB3Mem init non-critical: ${e}`);
        }
        const entries = store.loadEpisodicEntries();
        memorySystem.episodic.restoreEntries(entries);
        memorySystem.episodic.setPersistCallback((entry) => {
          store.storeEpisodicEntry(entry);
        });
        memorySystem.episodic.setDeletePersistCallback((workflowId) => {
          store.deleteEpisodicByWorkflow(workflowId);
        });
        log.info(`memory system ready (episodic: ${entries.length} entries restored)`);
        try {
          const { EvolutionStore: EvolutionStore2 } = await Promise.resolve().then(() => (init_evolution_store(), evolution_store_exports));
          const { EvolutionAnalyzer: EvolutionAnalyzer2 } = await Promise.resolve().then(() => (init_analyzer(), analyzer_exports));
          evolutionStore = new EvolutionStore2(store.database);
          evolutionAnalyzer = new EvolutionAnalyzer2({
            api,
            memorySystem,
            evolutionStore,
            async onTemplateFound(template) {
              evolutionStore.save(template);
              if (template.type === "skill" && template.pattern) {
                try {
                  const fs3 = await import("node:fs");
                  const os3 = await import("node:os");
                  const skillsDir = path3.join(os3.homedir(), ".openclaw", "workspace", "skills");
                  const slug = template.name.toLowerCase().replace(/[^a-z0-9-]/g, "-");
                  const skillDir = path3.join(skillsDir, slug);
                  fs3.mkdirSync(skillDir, { recursive: true });
                  const skillFile = path3.join(skillDir, "SKILL.md");
                  if (fs3.existsSync(skillFile)) {
                    log.warn(`skill '${template.name}' already exists at ${skillFile}, skipping`);
                    return;
                  }
                  const triggerKeywords = (template.triggers || []).join(", ");
                  const pushyDesc = (template.description || template.name) + (triggerKeywords ? `. Use when: ${triggerKeywords}.` : "") + (template.scope && template.scope !== "general" ? ` Scope: ${template.scope}.` : "");
                  const frontmatter = [
                    "---",
                    `name: ${template.name}`,
                    `description: ${JSON.stringify(pushyDesc)}`,
                    "---",
                    ""
                  ].join("\n");
                  const sections = [];
                  sections.push(`# ${template.name}`);
                  sections.push("");
                  sections.push(template.description || "Auto-evolved skill pattern.");
                  sections.push("");
                  if ((template.triggers || []).length > 0) {
                    sections.push("## When to Use");
                    sections.push("");
                    sections.push(...template.triggers.map((t) => `- ${t}`));
                    sections.push("");
                  }
                  if ((template.prerequisites || []).length > 0) {
                    sections.push("## Prerequisites");
                    sections.push("");
                    sections.push(...template.prerequisites.map((p) => `- ${p}`));
                    sections.push("");
                  }
                  const allTools = [.../* @__PURE__ */ new Set([...template.tools_required || [], ...template.tools_optional || []])];
                  if (allTools.length > 0) {
                    sections.push("## Tools");
                    sections.push("");
                    if ((template.tools_required || []).length > 0) {
                      sections.push("**Required:**");
                      sections.push(...template.tools_required.map((t) => `- \`${t}\``));
                      sections.push("");
                    }
                    if ((template.tools_optional || []).length > 0) {
                      sections.push("**Optional:**");
                      sections.push(...template.tools_optional.map((t) => `- \`${t}\``));
                      sections.push("");
                    }
                  }
                  sections.push("## Instructions");
                  sections.push("");
                  sections.push(template.pattern || "Follow the detected pattern from workflow execution history.");
                  sections.push("");
                  if ((template.examples || []).length > 0) {
                    sections.push("## Examples");
                    sections.push("");
                    for (const ex of template.examples) {
                      if (ex.input || ex.expected_output) {
                        sections.push(`**Input:** ${ex.input || "(context-dependent)"}`);
                        sections.push(`**Output:** ${ex.expected_output || "(expected result)"}`);
                        sections.push("");
                      }
                    }
                  }
                  const metaParts = [
                    `Disciplines: ${(template.disciplines_used || []).join(", ") || "N/A"}`,
                    `Estimated duration: ${template.estimated_duration || "unknown"}`,
                    `Auto-generated by SoloFlow Skill Evolution`,
                    `Date: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`
                  ];
                  sections.push("---");
                  sections.push(metaParts.join(" | "));
                  const body = sections.join("\n");
                  fs3.writeFileSync(skillFile, frontmatter + body, "utf8");
                  log.info(`evolved skill written to ${skillFile}`);
                } catch (e) {
                  log.warn(`failed to write skill file: ${e}`);
                }
              }
            }
          });
          const wfCount = evolutionStore.count("workflow");
          const skCount = evolutionStore.count("skill");
          log.info(`evolution system ready (${wfCount} workflow templates, ${skCount} skill patterns)`);
          if (wfCount === 0 && skCount === 0) {
            log.info("no templates yet \u2014 run soloflow_evolve to start analysis, or set up a cron at 02:00 Beijing");
          }
          try {
            const { SkillInventory: SkillInventory2 } = await Promise.resolve().then(() => (init_skill_inventory(), skill_inventory_exports));
            const { SkillAnalyzer: SkillAnalyzer2 } = await Promise.resolve().then(() => (init_skill_analyzer(), skill_analyzer_exports));
            skillInventory = new SkillInventory2(store.database);
            skillAnalyzer = new SkillAnalyzer2(skillInventory, store.database, { logger: log });
            const scanResult = skillInventory.scan();
            log.info(`skill inventory: ${scanResult.added + scanResult.updated} skills scanned`);
          } catch (e) {
            log.warn(`skill inventory disabled: ${e}`);
          }
          try {
            const { MCPInventory: MCPInventory2 } = await Promise.resolve().then(() => (init_mcp_inventory(), mcp_inventory_exports));
            mcpInventory = new MCPInventory2(store.database, { config: api.config, logger: log });
            const mcpResult = mcpInventory.scan();
            log.info(`mcp inventory: ${mcpResult.added + mcpResult.updated} servers registered`);
          } catch (e) {
            log.warn(`mcp inventory disabled: ${e}`);
          }
          log.info("evolution system ready \u2014 cron job 'soloflow-nightly-evolve' handles daily analysis at 02:00 Beijing");
          try {
            const fsMod = await import("node:fs");
            const agentsMdPath = path3.join(os2.homedir(), ".openclaw", "workspace", "AGENTS.md");
            if (fsMod.existsSync(agentsMdPath)) {
              const agentsContent = fsMod.readFileSync(agentsMdPath, "utf8");
              if (!agentsContent.includes("## SoloFlow Workflow Matching")) {
                const lines = [
                  "",
                  "## SoloFlow Workflow Matching",
                  "",
                  "When the user's message suggests a multi-step task that might match an existing SoloFlow workflow template, **proactively check** and suggest:",
                  "",
                  "1. Extract 2-3 keywords from the user's message",
                  '2. Call `soloflow_templates(query="<keywords>", limit=3)` to check for matches',
                  "3. If a match scores well (description triggers align with the message), suggest:",
                  '   - "I found a workflow template that can help: **<name>** (<N> steps). Want me to run it?"',
                  "4. Only suggest if the user seems to want help *doing* something, not just asking questions",
                  "5. Don't call soloflow_templates for simple chitchat, greetings, or meta-conversations",
                  "",
                  "**Trigger examples (check templates, not exhaustive):**",
                  "- Camera/patrol/monitoring/security check -> check camera-related templates",
                  "- Code review/cleanup/quality/refactor -> check code quality templates",
                  "- Debug API/error/black box -> check API debugging templates",
                  "- Daily report/summary/learning -> check report templates",
                  "- Generate image/design -> check generation templates",
                  "- Deploy/publish/push -> check deployment templates",
                  ""
                ];
                const injection = lines.join("\n");
                const toolsIdx = agentsContent.indexOf("\n## Tools");
                if (toolsIdx !== -1) {
                  const updated = agentsContent.slice(0, toolsIdx) + "\n" + injection + agentsContent.slice(toolsIdx);
                  fsMod.writeFileSync(agentsMdPath, updated, "utf8");
                  log.info("injected SoloFlow workflow matching rules into AGENTS.md");
                } else {
                  fsMod.appendFileSync(agentsMdPath, "\n" + injection, "utf8");
                  log.info("appended SoloFlow workflow matching rules to AGENTS.md");
                }
              } else {
                log.info("AGENTS.md already has SoloFlow workflow matching rules \u2014 skipping");
              }
            }
          } catch (e) {
            log.debug?.(`AGENTS.md injection skipped: ${e}`);
          }
        } catch (e) {
          log.warn(`evolution system disabled: ${e}`);
        }
      } catch (e) {
        log.warn(`SQLite + memory system disabled: ${e}`);
      }
      try {
        const taskDetector = new TaskDetector();
        const _getStore = () => evolutionStore;
        api.registerHook("before_prompt_build", async (event, ctx) => {
          const store = _getStore();
          if (!store) return;
          const trigger = ctx?.trigger;
          if (trigger && trigger !== "user") return;
          const prompt = event?.prompt ?? "";
          if (!prompt || prompt.length < 3) return;
          if (prompt.includes("soloflow_create") || prompt.includes("soloflow_start") || prompt.includes("soloflow_templates") || prompt.includes("soloflow_status")) {
            return;
          }
          const templates = store.search("", void 0, 30);
          const templateList = templates.map((t) => ({
            id: t.id,
            name: t.name,
            description: t.description,
            triggers: t.triggers ?? [],
            tags: t.tags ?? []
          }));
          const recommendation = taskDetector.recommendWorkflow(prompt, templateList);
          if (recommendation && recommendation.confidence >= 0.7) {
            const matched = templates.find((t) => t.id === recommendation.templateId);
            if (matched) {
              const keywords = recommendation.matchedKeywords?.join(", ") ?? "";
              return {
                prependContext: [
                  `
[SoloFlow Workflow Match]`,
                  `Detected potential workflow match (confidence: ${(recommendation.confidence * 100).toFixed(0)}%, keywords: ${keywords}):`,
                  `- **${matched.name}** (${matched.type}): ${matched.description}`,
                  `- Template ID: ${matched.id}`,
                  `- Quality: ${(matched.qualityScore ?? 0.5).toFixed(2)}, Steps: ${matched.steps?.length ?? "?"}`,
                  `Consider asking the user if they want to run this workflow via soloflow_start.`,
                  `[SoloFlow End]
`
                ].join("\n")
              };
            }
          }
          return void 0;
        });
        log.info("auto workflow recommendation hook registered");
      } catch (e) {
        log.debug?.(`workflow recommendation hook failed: ${e}`);
      }
      try {
        const { createApiServer: createApiServer2 } = await Promise.resolve().then(() => (init_api(), api_exports));
        const apiServer = createApiServer2(
          { workflowService, scheduler, templateRegistry, evolutionStore, skillInventory },
          { requireAuth: false }
        );
        api.registerHttpRoute({
          path: "/soloflow",
          match: "prefix",
          auth: "plugin",
          handler: async (req, res) => {
            const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
            if (url.pathname === "/soloflow/skills" || url.pathname === "/soloflow/skills/") {
              try {
                const fs3 = await import("node:fs");
                const __dirname = path3.dirname(fileURLToPath(import.meta.url));
                const html = fs3.readFileSync(path3.join(__dirname, "visual-builder", "skills.html"), "utf8");
                res.setHeader("content-type", "text/html; charset=utf-8");
                res.end(html);
                return true;
              } catch (e) {
                log.warn(`Skill Viewer not available: ${e}`);
              }
            }
            if (url.pathname === "/soloflow/builder" || url.pathname === "/soloflow/builder/") {
              try {
                const fs3 = await import("node:fs");
                const __dirname = path3.dirname(fileURLToPath(import.meta.url));
                const html = fs3.readFileSync(path3.join(__dirname, "visual-builder", "index.html"), "utf8");
                res.setHeader("content-type", "text/html; charset=utf-8");
                res.end(html);
                return true;
              } catch (e) {
                log.warn(`Visual Builder not available: ${e}`);
              }
            }
            const internalPath = url.pathname.replace(/^\/soloflow/, "") || "/";
            const query = {};
            for (const [k, v] of url.searchParams) query[k] = v;
            const headers = {};
            for (const [k, v] of Object.entries(req.headers)) {
              if (typeof v === "string") headers[k] = v;
              else if (Array.isArray(v) && v[0] !== void 0) headers[k] = v[0];
            }
            let body = void 0;
            if (req.method === "POST" || req.method === "PUT" || req.method === "PATCH") {
              const chunks = [];
              for await (const chunk of req) chunks.push(chunk);
              const raw = Buffer.concat(chunks).toString("utf8");
              if (raw.trim()) {
                try {
                  body = JSON.parse(raw);
                } catch (e) {
                  log.warn(`body parse error: ${e}`);
                }
              }
            }
            const apiReq = { method: req.method ?? "GET", path: internalPath, params: {}, query, body, headers };
            const apiRes = await apiServer.handle(apiReq);
            res.statusCode = apiRes.status ?? 200;
            for (const [k, v] of Object.entries(apiRes.headers ?? {})) res.setHeader(k, v);
            res.setHeader("content-type", "application/json; charset=utf-8");
            res.end(JSON.stringify(apiRes.body));
            return true;
          }
        });
        log.info(`API server ready at /soloflow`);
      } catch (e) {
        log.warn(`API server disabled: ${e}`);
      }
    })();
    void (async () => {
      try {
        const mod = await Promise.resolve().then(() => (init_vector(), vector_exports));
        const { detectEmbeddingConfig: detectEmbeddingConfig2, validateEmbeddingConfig: validateEmbeddingConfig2 } = await Promise.resolve().then(() => (init_embedding_config(), embedding_config_exports));
        const detectedEmbedding = detectEmbeddingConfig2();
        let activeEmbeddingConfig = detectedEmbedding;
        if (detectedEmbedding.type !== "local") {
          const valid = await validateEmbeddingConfig2(detectedEmbedding);
          if (!valid) {
            log.warn(`Embedding provider ${detectedEmbedding.type} validation failed, falling back to local`);
            activeEmbeddingConfig = { type: "local" };
          } else {
            log.info(`Using ${detectedEmbedding.type} embedding provider (model: ${detectedEmbedding.model})`);
          }
        }
        vectorSystem = new mod.VectorSearchSystem({ embedding: activeEmbeddingConfig, search: {} });
        await vectorSystem.init();
        log.info("vector search ready");
        if (memorySystem) {
          vectorSystem.setSemanticMemory(memorySystem.semantic);
          vectorSystem.setEpisodicMemory(memorySystem.episodic);
          memorySystem.setUnifiedSources({
            ftsSearch: (query, limit) => {
              try {
                return sqliteStore.searchEpisodicFTS(query, limit);
              } catch (e) {
                log.debug?.(`FTS5 search failed: ${e}`);
                return [];
              }
            },
            vectorSearch: async (query, limit) => {
              try {
                const results = await vectorSystem.retriever.search(query, limit);
                return results.map((r) => ({ id: r.id, score: r.score }));
              } catch (e) {
                log.debug?.(`vector search failed: ${e}`);
                return [];
              }
            },
            episodicLoader: (id) => {
              for (const entry of memorySystem.episodic.all()) {
                if (entry.id === id) return entry;
              }
              return null;
            }
          });
        }
      } catch (e) {
        log.warn(`vector search disabled: ${e}`);
      }
    })();
    void (async () => {
      try {
        const { HookSystem: HookSystem2, registerBuiltinHooks: registerBuiltinHooks2 } = await Promise.resolve().then(() => (init_hooks(), hooks_exports));
        hookSystem2 = new HookSystem2();
        unregisterBuiltinHooks = registerBuiltinHooks2(hookSystem2);
        workflowSubscription = workflowService.subscribe((event) => {
          try {
            const type = event["type"];
            if ((type === "workflow:completed" || type === "workflow:failed") && memorySystem) {
              const wfId = event["workflowId"];
              const wf = workflowService.get(wfId);
              if (wf) {
                memorySystem.storeWorkflowExecution(wf).catch(() => {
                });
                if (vectorSystem) vectorSystem.indexWorkflow(wf).catch(() => {
                });
                decomposeWorkflow(wf).catch(() => {
                });
                const templateId = wf.metadata?.["template"];
                if (templateId && evolutionStore) {
                  const success = type === "workflow:completed";
                  try {
                    evolutionStore.recordUsage(templateId, success);
                  } catch (e) {
                    log.debug?.(`recordUsage failed: ${e}`);
                  }
                }
              }
            }
          } catch (e) {
            log.debug?.(`hook error: ${e}`);
          }
        });
      } catch (e) {
        log.warn(`hook system disabled: ${e}`);
      }
    })();
    api.registerTool(
      {
        name: "soloflow_create",
        description: "Create a SoloFlow workflow. Provide a name and an array of steps with id, name, discipline (deep|quick|visual|ultrabrain), and action.",
        label: "SoloFlow: Create Workflow",
        parameters: Type.Object({
          name: Type.String({ description: "Workflow name" }),
          templateId: Type.Optional(Type.String({ description: "Template this workflow was created from (for usage tracking)" })),
          description: Type.Optional(Type.String({ description: "Workflow description" })),
          steps: Type.Array(
            Type.Object({
              id: Type.String({ description: "Unique step ID" }),
              name: Type.String({ description: "Step display name" }),
              discipline: Type.Union(
                [
                  Type.Literal("deep"),
                  Type.Literal("quick"),
                  Type.Literal("visual"),
                  Type.Literal("ultrabrain")
                ],
                { description: "Agent discipline for this step" }
              ),
              action: Type.String({ description: "Task prompt or action" }),
              dependencies: Type.Optional(
                Type.Array(Type.String(), { description: "IDs of steps this depends on" })
              ),
              config: Type.Optional(
                Type.Record(Type.String(), Type.Unknown(), { description: "Extra step config" })
              )
            }),
            { description: "Workflow steps" }
          )
        }),
        async execute(_toolCallId, params) {
          try {
            const { name, description, steps } = params;
            const now2 = Date.now();
            const wfId = `wf_${now2.toString(36)}`;
            const stepMap = /* @__PURE__ */ new Map();
            for (const s of steps) {
              stepMap.set(s.id, {
                id: s.id,
                name: s.name,
                discipline: s.discipline ?? "quick",
                dependencies: s.dependencies ?? [],
                config: { prompt: s.action, ...s.config ?? {} },
                state: "pending"
              });
            }
            const wf = {
              id: wfId,
              name,
              description: description ?? "",
              steps: stepMap,
              dag: null,
              state: "idle",
              currentSteps: [],
              createdAt: now2,
              updatedAt: now2,
              metadata: params.templateId ? { template: params.templateId } : {}
            };
            const created = workflowService.create(wf);
            return {
              content: [{ type: "text", text: JSON.stringify({
                id: created.id,
                name: created.name,
                state: created.state,
                steps: created.steps.size
              }) }],
              details: { workflowId: created.id }
            };
          } catch (e) {
            return {
              content: [{ type: "text", text: `Error: ${e instanceof Error ? e.message : String(e)}` }],
              details: { error: true }
            };
          }
        }
      }
    );
    api.registerTool(
      {
        name: "soloflow_start",
        description: "Start executing a SoloFlow workflow by ID",
        label: "SoloFlow: Start Workflow",
        parameters: Type.Object({
          workflowId: Type.String({ description: "Workflow ID to start" })
        }),
        async execute(_toolCallId, params) {
          try {
            const wfId = params.workflowId;
            const wf = workflowService.get(wfId);
            if (!wf) {
              return {
                content: [{ type: "text", text: `Workflow not found: ${wfId}` }],
                details: { error: true }
              };
            }
            workflowService.start(wfId);
            const readyIds = workflowService.getReadySteps(wfId, /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set());
            const readySteps = readyIds.map((id) => {
              const s = wf.steps.get(id);
              return {
                id: s.id,
                name: s.name,
                discipline: s.discipline,
                action: s.config?.["prompt"] ?? s.name,
                dependencies: s.dependencies
              };
            });
            return {
              content: [{ type: "text", text: JSON.stringify({
                workflowId: wfId,
                totalSteps: wf.steps.size,
                readySteps
              }, null, 2) }],
              details: { workflowId: wfId, state: "running", readyCount: readySteps.length }
            };
          } catch (e) {
            return {
              content: [{ type: "text", text: `Error: ${e instanceof Error ? e.message : String(e)}` }],
              details: { error: true }
            };
          }
        }
      }
    );
    api.registerTool(
      {
        name: "soloflow_status",
        description: "Get the current status of a SoloFlow workflow",
        label: "SoloFlow: Workflow Status",
        parameters: Type.Object({
          workflowId: Type.String({ description: "Workflow ID" })
        }),
        async execute(_toolCallId, params) {
          const wf = workflowService.get(params.workflowId);
          if (!wf) {
            return {
              content: [{ type: "text", text: "Workflow not found" }],
              details: { error: true }
            };
          }
          const execStatus = scheduler.getStatus(params.workflowId);
          const steps = Array.from(wf.steps.values()).map((s) => ({
            id: s.id,
            name: s.name,
            discipline: s.discipline,
            state: s.state,
            error: s.error,
            result: s.result,
            durationMs: s.startedAt && s.completedAt ? s.completedAt - s.startedAt : void 0
          }));
          const completedCount = steps.filter((s) => s.state === "completed").length;
          const failedCount = steps.filter((s) => s.state === "failed").length;
          const totalCount = steps.length;
          return {
            content: [{ type: "text", text: JSON.stringify({
              id: wf.id,
              name: wf.name,
              state: wf.state,
              progress: execStatus?.progress ?? (totalCount > 0 ? completedCount / totalCount : void 0),
              completedSteps: execStatus?.completedSteps?.length ?? completedCount,
              failedSteps: execStatus?.failedSteps?.length ?? failedCount,
              steps
            }, null, 2) }],
            details: { workflowId: wf.id, state: wf.state }
          };
        }
      }
    );
    api.registerTool(
      {
        name: "soloflow_list",
        description: "List all SoloFlow workflows",
        label: "SoloFlow: List Workflows",
        parameters: Type.Object({
          status: Type.Optional(
            Type.String({ description: "Filter by status: running|completed|failed|cancelled" })
          ),
          discipline: Type.Optional(
            Type.String({ description: "Filter by step discipline: deep|quick|visual|ultrabrain" })
          )
        }),
        async execute(_toolCallId, params) {
          const filter = params.status ? { status: params.status } : void 0;
          let wfs = workflowService.list(filter);
          if (params.discipline) {
            wfs = wfs.filter(
              (w) => Array.from(w.steps.values()).some((s) => s.discipline === params.discipline)
            );
          }
          return {
            content: [{ type: "text", text: JSON.stringify(
              wfs.map((w) => ({
                id: w.id,
                name: w.name,
                state: w.state,
                steps: w.steps.size,
                createdAt: w.createdAt
              })),
              null,
              2
            ) }],
            details: { count: wfs.length }
          };
        }
      }
    );
    api.registerTool(
      {
        name: "soloflow_cancel",
        description: "Cancel a running SoloFlow workflow",
        label: "SoloFlow: Cancel Workflow",
        parameters: Type.Object({
          workflowId: Type.String({ description: "Workflow ID to cancel" }),
          force: Type.Optional(
            Type.Boolean({ description: "Force cancel from any non-terminal state" })
          )
        }),
        async execute(_toolCallId, params) {
          try {
            const wfId = params.workflowId;
            workflowService.cancel(wfId);
            scheduler.cancel(wfId);
            return {
              content: [{ type: "text", text: `Workflow ${wfId} cancelled` }],
              details: { workflowId: wfId, state: "cancelled" }
            };
          } catch (e) {
            return {
              content: [{ type: "text", text: `Error: ${e instanceof Error ? e.message : String(e)}` }],
              details: { error: true }
            };
          }
        }
      }
    );
    api.registerTool(
      {
        name: "soloflow_ready_steps",
        description: "Get steps that are ready to execute (all dependencies met). The main agent calls this to know which steps to spawn next.",
        label: "SoloFlow: Get Ready Steps",
        parameters: Type.Object({
          workflowId: Type.String({ description: "Workflow ID" })
        }),
        async execute(_toolCallId, params) {
          const wfId = params.workflowId;
          const wf = workflowService.get(wfId);
          if (!wf) return { content: [{ type: "text", text: "Workflow not found" }], details: { error: true } };
          const completed = /* @__PURE__ */ new Set();
          const running = /* @__PURE__ */ new Set();
          for (const [id, step2] of wf.steps) {
            if (step2.state === "completed") completed.add(id);
            else if (step2.state === "running") running.add(id);
          }
          const readyIds = workflowService.getReadySteps(wfId, completed, running);
          const readySteps = readyIds.map((id) => {
            const s = wf.steps.get(id);
            return {
              id: s.id,
              name: s.name,
              discipline: s.discipline,
              action: (s.config?.["prompt"] ?? s.name).slice(0, 200),
              dependencies: s.dependencies
            };
          });
          return {
            content: [{ type: "text", text: JSON.stringify({ readySteps, completed: completed.size, running: running.size, total: wf.steps.size }, null, 2) }],
            details: { workflowId: wfId, readyCount: readySteps.length }
          };
        }
      }
    );
    api.registerTool(
      {
        name: "soloflow_advance_step",
        description: "Mark a step as completed with its result. This unlocks downstream dependent steps. The main agent calls this after confirming a subagent has finished.",
        label: "SoloFlow: Advance Step",
        parameters: Type.Object({
          workflowId: Type.String({ description: "Workflow ID" }),
          stepId: Type.String({ description: "Step ID to mark complete" }),
          result: Type.Optional(Type.String({ description: "The text output/result from executing this step" })),
          error: Type.Optional(Type.String({ description: "Error message if the step failed" }))
        }),
        async execute(_toolCallId, params) {
          const wfId = params.workflowId;
          const stepId = params.stepId;
          const wf = workflowService.get(wfId);
          if (!wf) return { content: [{ type: "text", text: "Workflow not found" }], details: { error: true } };
          const step2 = wf.steps.get(stepId);
          if (!step2) return { content: [{ type: "text", text: `Step not found: ${stepId}` }], details: { error: true } };
          if (step2.state === "completed") return { content: [{ type: "text", text: `Step ${stepId} already completed` }], details: { error: true } };
          step2.state = params.error ? "failed" : "completed";
          step2.result = params.result ?? null;
          step2.error = params.error ?? void 0;
          step2.completedAt = Date.now();
          workflowService.update(wf);
          const allSteps = Array.from(wf.steps.values());
          const allDone = allSteps.every((s) => s.state === "completed" || s.state === "failed");
          const anyFailed = allSteps.some((s) => s.state === "failed");
          let newState = wf.state;
          let message;
          if (allDone) {
            newState = anyFailed ? "failed" : "completed";
            wf.state = newState;
            wf.updatedAt = Date.now();
            workflowService.update(wf);
            message = `Workflow ${wfId} ${newState}!`;
          } else {
            const completed = /* @__PURE__ */ new Set();
            const running = /* @__PURE__ */ new Set();
            for (const [id, s] of wf.steps) {
              if (s.state === "completed") completed.add(id);
              else if (s.state === "running") running.add(id);
            }
            const newReady = workflowService.getReadySteps(wfId, completed, running);
            message = `Step ${stepId} completed. ${newReady.length} step(s) now ready: ${newReady.join(", ") || "none"}`;
          }
          if (evolutionStore && !params.error) {
            try {
              const allSkills = evolutionStore.search("", "skill", 50);
              const stepAction = step2?.action?.toLowerCase() ?? "";
              for (const skill of allSkills) {
                if (skill.pattern && stepAction.length > 0) {
                  const patternWords = skill.pattern.toLowerCase().split(/\s+/);
                  const overlap = patternWords.filter((w) => w.length > 3 && stepAction.includes(w));
                  if (overlap.length >= 2 || overlap.length >= 1 && patternWords.length <= 5) {
                    evolutionStore.recordUsage(skill.id, true);
                  }
                }
              }
            } catch (e) {
              log.debug?.(`skill usage record failed: ${e}`);
            }
          }
          if (memorySystem && !params.error) {
            try {
              const wfSnapshot = workflowService.get(wfId);
              if (wfSnapshot) {
                await memorySystem.storeWorkflowExecution(wfSnapshot);
              }
            } catch (e) {
              log.warn(`memory store failed: ${e}`);
            }
          }
          return {
            content: [{ type: "text", text: JSON.stringify({
              workflowId: wfId,
              stepId,
              stepState: step2.state,
              workflowState: newState,
              message,
              completedCount: allSteps.filter((s) => s.state === "completed").length,
              totalSteps: allSteps.length
            }, null, 2) }],
            details: { workflowId: wfId, stepState: step2.state, workflowState: newState }
          };
        }
      }
    );
    api.registerTool(
      {
        name: "soloflow_memory",
        description: "Query SoloFlow's cognitive memory (working, episodic, semantic). Search past workflow executions, stored facts, and patterns.",
        label: "SoloFlow: Query Memory",
        parameters: Type.Object({
          query: Type.String({ description: "Search query text" }),
          tier: Type.Optional(Type.String({ description: "Memory tier: working|episodic|semantic|entity (default: all)" })),
          limit: Type.Optional(Type.Integer({ description: "Max results (default: 10)" }))
        }),
        async execute(_toolCallId, params) {
          if (!memorySystem) {
            return {
              content: [{ type: "text", text: "Memory system not available" }],
              details: { error: true }
            };
          }
          try {
            if (params.tier === "entity") {
              const entities = memorySystem.queryEntities({
                text: params.query,
                limit: params.limit ?? 10
              });
              return {
                content: [{ type: "text", text: JSON.stringify({
                  totalMatches: entities.length,
                  entries: entities.map((e) => ({
                    tier: "entity",
                    text: e.text,
                    type: e.type,
                    score: e.confidence.toFixed(3)
                  }))
                }, null, 2) }],
                details: { count: entities.length }
              };
            }
            const result = await memorySystem.query({
              text: params.query,
              tiers: params.tier ? [params.tier] : void 0,
              limit: params.limit ?? 10
            });
            const entries = result.entries.map((e) => ({
              tier: e.tier,
              score: e.score.toFixed(3),
              ...e.tier === "episodic" ? {
                workflowId: e.entry.workflowId,
                workflowName: e.entry.workflowName,
                finalState: e.entry.finalState,
                durationMs: e.entry.durationMs,
                steps: e.entry.stepSummary?.length ?? 0
              } : {},
              ...e.tier === "semantic" ? {
                key: e.entry.key,
                category: e.entry.category,
                importance: e.entry.importance,
                retrievability: e.entry.retrievability?.toFixed(3)
              } : {},
              ...e.tier === "working" ? {
                key: e.entry.key,
                source: e.entry.source
              } : {}
            }));
            return {
              content: [{ type: "text", text: JSON.stringify({
                totalMatches: result.totalMatches,
                entries
              }, null, 2) }],
              details: { count: entries.length }
            };
          } catch (e) {
            return {
              content: [{ type: "text", text: `Memory query error: ${e instanceof Error ? e.message : String(e)}` }],
              details: { error: true }
            };
          }
        }
      }
    );
    api.registerTool(
      {
        name: "soloflow_evolve",
        description: "Trigger Skill Auto-Evolution analysis. Scans workflow history and extracts reusable patterns into templates and skill patterns.",
        label: "SoloFlow: Evolve Skills",
        parameters: Type.Object({
          type: Type.Optional(Type.String({ description: "Filter: 'workflow', 'skill', or omit for all" }))
        }),
        async execute(_toolCallId, params) {
          if (!evolutionAnalyzer) {
            return { content: [{ type: "text", text: "Evolution system not available" }], details: { error: true } };
          }
          try {
            const result = await evolutionAnalyzer.analyze(params.type);
            return {
              content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
              details: { workflowsExtracted: result.templates, skillsExtracted: result.skills }
            };
          } catch (e) {
            return {
              content: [{ type: "text", text: `Evolution error: ${e instanceof Error ? e.message : String(e)}` }],
              details: { error: true }
            };
          }
        }
      }
    );
    api.registerTool(
      {
        name: "soloflow_templates",
        description: "List and search evolved workflow templates and skill patterns. Shows reusable patterns extracted from past workflow executions.",
        label: "SoloFlow: List Templates",
        parameters: Type.Object({
          query: Type.Optional(Type.String({ description: "Search query (name/description/tags)" })),
          type: Type.Optional(Type.String({ description: "Filter: 'workflow', 'skill', or omit for all" })),
          limit: Type.Optional(Type.Integer({ description: "Max results (default: 20)" }))
        }),
        async execute(_toolCallId, params) {
          if (!evolutionStore) {
            return { content: [{ type: "text", text: "Evolution store not available" }], details: { error: true } };
          }
          try {
            const templates = evolutionStore.search(
              params.query ?? "",
              params.type,
              params.limit ?? 5
            );
            const formatted = templates.map((t) => ({
              id: t.id,
              type: t.type,
              name: t.name,
              description: t.description,
              triggers: t.triggers ?? [],
              scope: t.scope ?? "general",
              prerequisites: t.prerequisites ?? [],
              tools_required: t.tools_required ?? [],
              tools_optional: t.tools_optional ?? [],
              estimated_duration: t.estimatedDuration ?? "",
              examples: t.examples ?? [],
              quality: t.qualityScore.toFixed(2),
              uses: t.useCount,
              version: t.version,
              ...t.type === "workflow" ? { steps: t.steps?.length ?? 0 } : {},
              ...t.pattern ? { pattern: t.pattern } : {},
              tags: t.tags
            }));
            return {
              content: [{ type: "text", text: JSON.stringify({ total: formatted.length, templates: formatted }, null, 2) }],
              details: { count: formatted.length }
            };
          } catch (e) {
            return {
              content: [{ type: "text", text: `Template query error: ${e instanceof Error ? e.message : String(e)}` }],
              details: { error: true }
            };
          }
        }
      }
    );
    api.registerTool(
      {
        name: "skills_list",
        description: "List all SoloFlow managed skills from inventory.",
        label: "SoloFlow: List Skills",
        parameters: Type.Object({}),
        async execute(_toolCallId, _params) {
          if (!skillInventory) {
            return { content: [{ type: "text", text: "Skill inventory not available" }], details: { error: true } };
          }
          try {
            const skills = skillInventory.getAll();
            return { content: [{ type: "text", text: JSON.stringify({ total: skills.length, skills }, null, 2) }] };
          } catch (e) {
            return { content: [{ type: "text", text: `Error: ${e}` }], details: { error: true } };
          }
        }
      }
    );
    api.registerTool(
      {
        name: "skills_usage",
        description: "Get skill usage analytics: insights, recent usage, and combination patterns.",
        label: "SoloFlow: Skill Usage",
        parameters: Type.Object({}),
        async execute(_toolCallId, _params) {
          if (!skillAnalyzer || !skillInventory) {
            return { content: [{ type: "text", text: "Skill system not available" }], details: { error: true } };
          }
          try {
            const insights = skillAnalyzer.getInsights(20);
            const recent = skillInventory.getRecentlyUsed(10);
            const combinations = skillInventory.getCombinationPatterns().slice(0, 5);
            return { content: [{ type: "text", text: JSON.stringify({ insights, recent, combinations }, null, 2) }] };
          } catch (e) {
            return { content: [{ type: "text", text: `Error: ${e}` }], details: { error: true } };
          }
        }
      }
    );
    api.registerTool(
      {
        name: "skills_scan",
        description: "Scan installed skills and update the SoloFlow inventory.",
        label: "SoloFlow: Scan Skills",
        parameters: Type.Object({}),
        async execute(_toolCallId, _params) {
          if (!skillInventory) {
            return { content: [{ type: "text", text: "Skill inventory not available" }], details: { error: true } };
          }
          try {
            const result = skillInventory.scan();
            return { content: [{ type: "text", text: JSON.stringify(result) }] };
          } catch (e) {
            return { content: [{ type: "text", text: `Error: ${e}` }], details: { error: true } };
          }
        }
      }
    );
    api.registerTool({
      name: "mcp_servers",
      description: "List all registered MCP servers and their tools.",
      label: "SoloFlow: MCP Servers",
      parameters: Type.Object({
        server_id: Type.Optional(Type.String())
      }),
      async execute(_toolCallId, params) {
        if (!mcpInventory) {
          return { content: [{ type: "text", text: "MCP inventory not available" }], details: { error: true } };
        }
        try {
          mcpInventory.scan();
          if (params.server_id) {
            const stats = mcpInventory.getUsageStats(params.server_id);
            const servers2 = mcpInventory.getAll().filter((s) => s.id === params.server_id);
            return { content: [{ type: "text", text: JSON.stringify({ server: servers2[0] ?? null, stats }, null, 2) }] };
          }
          const servers = mcpInventory.getAll();
          return { content: [{ type: "text", text: JSON.stringify({ total: servers.length, servers }, null, 2) }] };
        } catch (e) {
          return { content: [{ type: "text", text: `Error: ${e}` }], details: { error: true } };
        }
      }
    });
    api.registerTool({
      name: "mcp_stats",
      description: "Get MCP server usage statistics and tool rankings.",
      label: "SoloFlow: MCP Stats",
      parameters: Type.Object({
        days: Type.Optional(Type.Integer({ minimum: 1, maximum: 90, default: 30 }))
      }),
      async execute(_toolCallId, params) {
        if (!mcpInventory) {
          return { content: [{ type: "text", text: "MCP inventory not available" }], details: { error: true } };
        }
        try {
          const days = params.days ?? 30;
          const rankings = mcpInventory.getServerRankings(days);
          const toolStats = mcpInventory.getToolStats(days);
          return { content: [{ type: "text", text: JSON.stringify({ days, rankings, topTools: toolStats.slice(0, 20) }, null, 2) }] };
        } catch (e) {
          return { content: [{ type: "text", text: `Error: ${e}` }], details: { error: true } };
        }
      }
    });
    api.registerGatewayMethod("soloflow.metrics", async (opts) => {
      const wfs = workflowService.list();
      opts.respond(true, {
        version: PLUGIN_VERSION,
        totalWorkflows: wfs.length,
        running: wfs.filter((w) => w.state === "running").length,
        completed: wfs.filter((w) => w.state === "completed").length,
        failed: wfs.filter((w) => w.state === "failed").length,
        memoryReady: memorySystem !== null,
        vectorReady: vectorSystem !== null
      });
    });
    try {
      api.registerHook("plugin:deactivate", () => {
        log.info("deactivating\u2026");
        workflowSubscription?.();
        unregisterBuiltinHooks?.();
        hookSystem2?.clear();
        sqliteStore?.close();
        vectorSystem?.close().catch(() => {
        });
        memorySystem?.close().catch(() => {
        });
        log.info("deactivated");
      });
    } catch (e) {
      log.debug?.(`hook registration skipped: ${e}`);
    }
    log.info(
      `activated (v0.8) \u2014 15 tools registered, memory + evolution + skills + MCP active`
    );
    if (skillInventory) {
      const originalExecute = api.executeTool?.bind(api);
      api.executeTool = async (toolName, params) => {
        const startTime = Date.now();
        try {
          const result = originalExecute ? await originalExecute(toolName, params) : null;
          const duration = Date.now() - startTime;
          try {
            const allSkills = skillInventory.getAll();
            const normalized = toolName.replace(/_/g, " ").toLowerCase();
            const matched = allSkills.find(
              (s) => s.tools?.includes(toolName) || s.name.toLowerCase().includes(normalized)
            );
            skillInventory.recordUsage(matched?.id ?? toolName, toolName, true, duration);
          } catch (e) {
            log.debug?.(`skill usage record failed: ${e}`);
          }
          try {
            if (mcpInventory) {
              const serverId = mcpInventory.detectServerForTool(toolName);
              if (serverId) {
                mcpInventory.recordUsage(serverId, toolName, true, duration);
              }
            }
          } catch (e) {
            log.debug?.(`mcp usage record failed: ${e}`);
          }
          return result;
        } catch (e) {
          const duration = Date.now() - startTime;
          try {
            skillInventory.recordUsage(toolName, toolName, false, duration);
          } catch (e2) {
            log.debug?.(`skill usage record failed: ${e2}`);
          }
          try {
            if (mcpInventory) {
              const serverId = mcpInventory.detectServerForTool(toolName);
              if (serverId) {
                mcpInventory.recordUsage(serverId, toolName, false, duration);
              }
            }
          } catch (e2) {
            log.debug?.(`mcp usage record failed: ${e2}`);
          }
          throw e;
        }
      };
      log.info("tool usage tracking enabled (skills + MCP)");
    }
  }
});
export {
  DisciplineAgent,
  HookSystem,
  MemorySystem,
  Scheduler,
  VectorSearchSystem,
  WorkflowService,
  allAgents,
  dagToYaml,
  index_default as default,
  getAgent,
  getMetrics,
  previewWorkflow,
  validateWorkflow,
  yamlToDag
};
