import { getOrCreateSpan } from './chunk-G2SVLNSC.js';
import { EntityType } from './chunk-A6UBX7NY.js';

// src/observability/types/core.ts
var SamplingStrategyType = /* @__PURE__ */ ((SamplingStrategyType2) => {
  SamplingStrategyType2["ALWAYS"] = "always";
  SamplingStrategyType2["NEVER"] = "never";
  SamplingStrategyType2["RATIO"] = "ratio";
  SamplingStrategyType2["CUSTOM"] = "custom";
  return SamplingStrategyType2;
})(SamplingStrategyType || {});

// src/observability/types/metrics.ts
var DEFAULT_BLOCKED_LABELS = [
  "trace_id",
  "span_id",
  "run_id",
  "request_id",
  "user_id",
  "resource_id",
  "session_id",
  "thread_id"
];

// src/observability/no-op.ts
var noOpCounter = {
  add() {
  }
};
var noOpGauge = {
  set() {
  }
};
var noOpHistogram = {
  record() {
  }
};
var noOpTracingContext = {
  currentSpan: void 0
};
var noOpLoggerContext = {
  debug() {
  },
  info() {
  },
  warn() {
  },
  error() {
  },
  fatal() {
  }
};
var noOpMetricsContext = {
  emit() {
  },
  counter() {
    return noOpCounter;
  },
  gauge() {
    return noOpGauge;
  },
  histogram() {
    return noOpHistogram;
  }
};
var NoOpObservability = class {
  setMastraContext(_options) {
    return;
  }
  setLogger(_options) {
    return;
  }
  getSelectedInstance(_options) {
    return;
  }
  async getRecordedTrace(_args) {
    return null;
  }
  async addScore(_args) {
    return;
  }
  async addFeedback(_args) {
    return;
  }
  registerInstance(_name, _instance, _isDefault = false) {
    return;
  }
  getInstance(_name) {
    return;
  }
  getDefaultInstance() {
    return;
  }
  listInstances() {
    return /* @__PURE__ */ new Map();
  }
  unregisterInstance(_name) {
    return false;
  }
  hasInstance(_name) {
    return false;
  }
  setConfigSelector(_selector) {
    return;
  }
  clear() {
    return;
  }
  async shutdown() {
    return;
  }
};

// src/observability/context-factory.ts
function deriveLoggerContext(tracing) {
  const span = tracing.currentSpan;
  return span?.observabilityInstance?.getLoggerContext?.(span) ?? noOpLoggerContext;
}
function deriveMetricsContext(tracing) {
  const span = tracing.currentSpan;
  return span?.observabilityInstance?.getMetricsContext?.(span) ?? noOpMetricsContext;
}
function createObservabilityContext(tracingContext) {
  const tracing = tracingContext ?? noOpTracingContext;
  return {
    tracing,
    loggerVNext: deriveLoggerContext(tracing),
    metrics: deriveMetricsContext(tracing),
    tracingContext: tracing
    // alias — preferred at forwarding sites
  };
}
function resolveObservabilityContext(partial) {
  const tracing = partial.tracing ?? partial.tracingContext ?? noOpTracingContext;
  return {
    tracing,
    loggerVNext: partial.loggerVNext ?? deriveLoggerContext(tracing),
    metrics: partial.metrics ?? deriveMetricsContext(tracing),
    tracingContext: tracing
    // alias — preferred at forwarding sites
  };
}

// src/observability/context.ts
var AGENT_GETTERS = ["getAgent", "getAgentById"];
var AGENT_METHODS_TO_WRAP = ["generate", "stream", "generateLegacy", "streamLegacy"];
var WORKFLOW_GETTERS = ["getWorkflow", "getWorkflowById"];
var WORKFLOW_METHODS_TO_WRAP = ["execute", "createRun", "createRun"];
function isNoOpSpan(span) {
  return span.constructor.name === "NoOpSpan" || span.__isNoOp === true;
}
function isMastra(mastra) {
  const hasAgentGetters = AGENT_GETTERS.every((method) => typeof mastra?.[method] === "function");
  const hasWorkflowGetters = WORKFLOW_GETTERS.every((method) => typeof mastra?.[method] === "function");
  return hasAgentGetters && hasWorkflowGetters;
}
function wrapMastra(mastra, tracingContext) {
  if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {
    return mastra;
  }
  if (!isMastra(mastra)) {
    return mastra;
  }
  try {
    return new Proxy(mastra, {
      get(target, prop) {
        try {
          if (AGENT_GETTERS.includes(prop)) {
            return (...args) => {
              const agent = target[prop](...args);
              return wrapAgent(agent, tracingContext);
            };
          }
          if (WORKFLOW_GETTERS.includes(prop)) {
            return (...args) => {
              const workflow = target[prop](...args);
              return wrapWorkflow(workflow, tracingContext);
            };
          }
          const value = target[prop];
          return typeof value === "function" ? value.bind(target) : value;
        } catch (error) {
          console.warn("Tracing: Failed to wrap method, falling back to original", error);
          const value = target[prop];
          return typeof value === "function" ? value.bind(target) : value;
        }
      }
    });
  } catch (error) {
    console.warn("Tracing: Failed to create proxy, using original Mastra instance", error);
    return mastra;
  }
}
function wrapAgent(agent, tracingContext) {
  if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {
    return agent;
  }
  try {
    return new Proxy(agent, {
      get(target, prop) {
        try {
          if (AGENT_METHODS_TO_WRAP.includes(prop)) {
            return (input, options = {}) => {
              return target[prop](input, {
                ...options,
                ...createObservabilityContext(tracingContext)
              });
            };
          }
          const value = target[prop];
          return typeof value === "function" ? value.bind(target) : value;
        } catch (error) {
          console.warn("Tracing: Failed to wrap agent method, falling back to original", error);
          const value = target[prop];
          return typeof value === "function" ? value.bind(target) : value;
        }
      }
    });
  } catch (error) {
    console.warn("Tracing: Failed to create agent proxy, using original instance", error);
    return agent;
  }
}
function wrapWorkflow(workflow, tracingContext) {
  if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {
    return workflow;
  }
  try {
    return new Proxy(workflow, {
      get(target, prop) {
        try {
          if (WORKFLOW_METHODS_TO_WRAP.includes(prop)) {
            if (prop === "createRun" || prop === "createRun") {
              return async (options = {}) => {
                const run = await target[prop](options);
                return run ? wrapRun(run, tracingContext) : run;
              };
            }
            return (input, options = {}) => {
              return target[prop](input, {
                ...options,
                ...createObservabilityContext(tracingContext)
              });
            };
          }
          const value = target[prop];
          return typeof value === "function" ? value.bind(target) : value;
        } catch (error) {
          console.warn("Tracing: Failed to wrap workflow method, falling back to original", error);
          const value = target[prop];
          return typeof value === "function" ? value.bind(target) : value;
        }
      }
    });
  } catch (error) {
    console.warn("Tracing: Failed to create workflow proxy, using original instance", error);
    return workflow;
  }
}
function wrapRun(run, tracingContext) {
  if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {
    return run;
  }
  try {
    return new Proxy(run, {
      get(target, prop) {
        try {
          if (prop === "start") {
            return (startOptions = {}) => {
              return target.start({
                ...startOptions,
                ...createObservabilityContext(startOptions.tracingContext ?? tracingContext)
              });
            };
          }
          const value = target[prop];
          return typeof value === "function" ? value.bind(target) : value;
        } catch (error) {
          console.warn("Tracing: Failed to wrap run method, falling back to original", error);
          const value = target[prop];
          return typeof value === "function" ? value.bind(target) : value;
        }
      }
    });
  } catch (error) {
    console.warn("Tracing: Failed to create run proxy, using original instance", error);
    return run;
  }
}

// src/observability/rag-ingestion.ts
function startRagIngestion(options) {
  const span = getOrCreateSpan({
    ...options,
    entityType: EntityType.RAG_INGESTION,
    type: "rag_ingestion" /* RAG_INGESTION */
  });
  const observabilityContext = createObservabilityContext(span ? { currentSpan: span } : void 0);
  return { span, observabilityContext };
}
async function withRagIngestion(options, fn) {
  const { span, observabilityContext } = startRagIngestion(options);
  try {
    const result = await fn(observabilityContext);
    span?.end({ output: result });
    return result;
  } catch (err) {
    span?.error({ error: err, endSpan: true });
    throw err;
  }
}

export { DEFAULT_BLOCKED_LABELS, NoOpObservability, SamplingStrategyType, createObservabilityContext, noOpLoggerContext, noOpMetricsContext, noOpTracingContext, resolveObservabilityContext, startRagIngestion, withRagIngestion, wrapMastra };
//# sourceMappingURL=chunk-SR7NB44E.js.map
//# sourceMappingURL=chunk-SR7NB44E.js.map