import { i as formatErrorMessage } from "./errors-Cq_Pdh35.js";
import "./agent-scope-CZ-IyS6E.js";
import { l as normalizeAgentId } from "./session-key-CJf5_zWs.js";
import { c as resolveDefaultAgentId, n as listAgentIds, o as resolveAgentWorkspaceDir, t as listAgentEntries } from "./agent-scope-config-CT5O0iC8.js";
import "./defaults-mDjiWzE5.js";
import { x as findModelInCatalog } from "./model-selection-shared-CZph7bhH.js";
import { s as resolveDefaultModelForAgent } from "./model-selection-CYsOE1AU.js";
import { n as loadModelCatalog } from "./model-catalog-w7xOTgbZ.js";
import { i as collectExplicitAllowlist, m as normalizeToolName } from "./tool-policy-0aaOlOoa.js";
import { n as resolveEffectiveToolPolicy } from "./agent-tools.policy-BpoOU1rr.js";
import { h as supportsModelTools } from "./openai-transport-stream-C2CiYRC-.js";
import { i as getPluginToolMeta, o as setPluginToolMeta } from "./tools-Cyfie2t2.js";
import { n as createBundleMcpToolRuntime } from "./agent-bundle-mcp-materialize-Cfot_cEJ.js";
import "./agent-bundle-mcp-tools-pg-vDr6-.js";
import { t as createNodmixCodingTools } from "./agent-tools-fN_yDRs4.js";
import { t as buildWorkspaceSkillStatus } from "./status-BVfeQPe7.js";
import { a as normalizeAgentRuntimeTools, n as inspectRuntimeToolInputSchemas } from "./tool-schema-projection-CsvPwf80.js";
import { t as applyFinalEffectiveToolPolicy } from "./effective-tool-policy-BXWh3rgy.js";
import { a as shouldCreateBundleMcpRuntimeForAttempt } from "./attempt-tool-construction-plan-DhT4U13A.js";
import { t as collectUnavailableAgentSkills } from "./doctor-skills-core-cCtqEFSV.js";
//#region src/flows/doctor-core-checks.runtime.ts
function detectUnavailableSkills(cfg) {
	const agentId = resolveDefaultAgentId(cfg);
	return collectUnavailableAgentSkills(buildWorkspaceSkillStatus(resolveAgentWorkspaceDir(cfg, agentId), {
		config: cfg,
		agentId
	}));
}
function buildDoctorRuntimeModel(params) {
	const provider = params.provider || "openai";
	const id = params.modelId || "gpt-5.5";
	const api = provider === "openai-codex" ? "openai-codex-responses" : provider === "openai" ? "openai-responses" : void 0;
	const baseUrl = provider === "openai-codex" ? "https://chatgpt.com/backend-api" : provider === "openai" ? "https://api.openai.com/v1" : void 0;
	return {
		...params.entry,
		provider,
		id,
		name: params.entry?.name ?? id,
		...api ? { api } : {},
		...baseUrl ? { baseUrl } : {}
	};
}
function toolSchemaDiagnosticToFinding(params) {
	const tool = params.tools[params.diagnostic.toolIndex];
	const pluginId = tool ? getPluginToolMeta(tool)?.pluginId : void 0;
	const owner = pluginId ? ` from plugin ${pluginId}` : "";
	const agent = `Agent ${params.agentId} `;
	const path = pluginId === "bundle-mcp" ? "mcp.servers" : pluginId ? `plugins.entries.${pluginId}` : `tools.${params.diagnostic.toolName}`;
	const fixHint = pluginId === "bundle-mcp" ? "Disable or update the offending MCP server/tool so its parameters are a JSON object schema, then rerun doctor." : "Disable or update the offending plugin/tool so its parameters are a JSON object schema, then rerun doctor.";
	return {
		checkId: "core/doctor/runtime-tool-schemas",
		severity: "error",
		message: `${agent}tool ${params.diagnostic.toolName}${owner} has an unsupported input schema for runtime projection.`,
		path,
		target: params.diagnostic.toolName,
		requirement: params.diagnostic.violations.join(", "),
		fixHint
	};
}
function collectToolSchemaFindings(params) {
	return inspectRuntimeToolInputSchemas(params.tools).map((diagnostic) => toolSchemaDiagnosticToFinding({
		agentId: params.agentId,
		tools: params.tools,
		diagnostic
	}));
}
function collectBundleMcpRuntimeToolSchemaFindings(params) {
	const normalizedTools = normalizeAgentRuntimeTools({
		tools: applyFinalEffectiveToolPolicy({
			bundledTools: params.bundleRuntime.tools,
			config: params.cfg,
			agentId: params.agentId,
			modelProvider: params.modelRef.provider,
			modelId: params.modelRef.model,
			warn: () => {}
		}),
		provider: params.modelRef.provider,
		config: params.cfg,
		workspaceDir: params.workspaceDir,
		env: process.env,
		modelId: params.modelRef.model,
		modelApi: params.model.api,
		model: params.model
	});
	return collectToolSchemaFindings({
		agentId: params.agentId,
		tools: normalizedTools
	});
}
function bundleMcpRuntimeLoadFailureFinding(error) {
	return {
		checkId: "core/doctor/runtime-tool-schemas",
		severity: "error",
		message: "Configured MCP tool schema validation could not load the runtime tool set.",
		path: "mcp.servers",
		requirement: formatErrorMessage(error),
		fixHint: "Fix or disable the offending MCP server, then rerun doctor before relying on assistant tool startup."
	};
}
function bundleMcpRuntimeDiagnosticFinding(diagnostic) {
	return {
		checkId: "core/doctor/runtime-tool-schemas",
		severity: "error",
		message: `Configured MCP server "${diagnostic.serverName}" could not expose runtime tools for schema validation.`,
		path: `mcp.servers.${diagnostic.serverName}`,
		requirement: diagnostic.message,
		fixHint: "Fix or disable the offending MCP server, then rerun doctor before relying on assistant tool startup."
	};
}
function makeBundleMcpDiagnosticSentinel(name) {
	const sentinel = {
		name,
		label: "Bundle MCP diagnostic",
		description: "Internal doctor sentinel for bundle MCP schema diagnostics.",
		parameters: {
			type: "object",
			properties: {}
		},
		execute: async () => ({
			content: [],
			details: {}
		})
	};
	setPluginToolMeta(sentinel, {
		pluginId: "bundle-mcp",
		optional: false
	});
	return sentinel;
}
function synthesizeBundleMcpAllowlistSentinelName(params) {
	const normalized = normalizeToolName(params.allowlistEntry);
	const serverPrefix = normalizeToolName(`${params.safeServerName}__`);
	if (normalized.startsWith(serverPrefix)) return normalized;
	const separatorIndex = normalized.lastIndexOf("__");
	if (separatorIndex < 0) return;
	const toolPattern = normalized.slice(separatorIndex + 2);
	if (!toolPattern) return;
	const concreteToolName = toolPattern.replace(/\*/g, "diagnostic").replace(/\?/g, "x");
	return `${params.safeServerName}__${concreteToolName}`;
}
function collectBundleMcpDiagnosticSentinels(params) {
	const sentinels = [makeBundleMcpDiagnosticSentinel(`${params.diagnostic.safeServerName}__runtime_schema`)];
	const effectivePolicy = resolveEffectiveToolPolicy({
		config: params.cfg,
		agentId: params.agentId,
		modelProvider: params.modelRef.provider,
		modelId: params.modelRef.model
	});
	const explicitAllowlist = collectExplicitAllowlist([
		effectivePolicy.globalPolicy,
		effectivePolicy.globalProviderPolicy,
		effectivePolicy.agentPolicy,
		effectivePolicy.agentProviderPolicy,
		effectivePolicy.profileAlsoAllow ? { allow: effectivePolicy.profileAlsoAllow } : void 0,
		effectivePolicy.providerProfileAlsoAllow ? { allow: effectivePolicy.providerProfileAlsoAllow } : void 0
	]);
	if (explicitAllowlist.length === 0) return sentinels;
	for (const entry of explicitAllowlist) {
		const sentinelName = synthesizeBundleMcpAllowlistSentinelName({
			safeServerName: params.diagnostic.safeServerName,
			allowlistEntry: entry
		});
		if (sentinelName) sentinels.push(makeBundleMcpDiagnosticSentinel(sentinelName));
	}
	return sentinels;
}
function shouldReportBundleMcpRuntimeDiagnostic(params) {
	return applyFinalEffectiveToolPolicy({
		bundledTools: collectBundleMcpDiagnosticSentinels(params),
		config: params.cfg,
		agentId: params.agentId,
		modelProvider: params.modelRef.provider,
		modelId: params.modelRef.model,
		warn: () => {}
	}).length > 0;
}
function filterPolicyActiveBundleMcpDiagnostics(params) {
	return params.diagnostics.filter((diagnostic) => shouldReportBundleMcpRuntimeDiagnostic({
		cfg: params.cfg,
		agentId: params.agentId,
		modelRef: params.modelRef,
		diagnostic
	}));
}
function isAcpRuntimeAgent(cfg, agentId) {
	return listAgentEntries(cfg).find((candidate) => normalizeAgentId(candidate.id) === agentId)?.runtime?.type === "acp";
}
async function collectRuntimeToolSchemaFindings(cfg) {
	const catalog = await loadModelCatalog({ config: cfg });
	const findings = [];
	const bundleRuntimeByWorkspace = /* @__PURE__ */ new Map();
	const bundleRuntimeLoadErrorsByWorkspace = /* @__PURE__ */ new Map();
	const reportedBundleRuntimeLoadErrors = /* @__PURE__ */ new Set();
	try {
		for (const agentId of listAgentIds(cfg)) {
			if (isAcpRuntimeAgent(cfg, agentId)) continue;
			const workspaceDir = resolveAgentWorkspaceDir(cfg, agentId);
			const modelRef = resolveDefaultModelForAgent({
				cfg,
				agentId,
				allowPluginNormalization: true
			});
			const model = buildDoctorRuntimeModel({
				entry: findModelInCatalog(catalog, modelRef.provider, modelRef.model),
				provider: modelRef.provider,
				modelId: modelRef.model
			});
			if (!supportsModelTools(model)) continue;
			const normalizedTools = normalizeAgentRuntimeTools({
				tools: createNodmixCodingTools({
					agentId,
					workspaceDir,
					config: cfg,
					modelProvider: modelRef.provider,
					modelId: modelRef.model,
					modelApi: model.api,
					modelCompat: model.compat,
					modelContextWindowTokens: model.contextWindow,
					allowGatewaySubagentBinding: true,
					emitBeforeToolCallDiagnostics: false
				}),
				provider: modelRef.provider,
				config: cfg,
				workspaceDir,
				env: process.env,
				modelId: modelRef.model,
				modelApi: model.api,
				model
			});
			findings.push(...collectToolSchemaFindings({
				agentId,
				tools: normalizedTools
			}));
			if (!shouldCreateBundleMcpRuntimeForAttempt({ toolsEnabled: true })) continue;
			if (!bundleRuntimeByWorkspace.has(workspaceDir) && !bundleRuntimeLoadErrorsByWorkspace.has(workspaceDir)) try {
				bundleRuntimeByWorkspace.set(workspaceDir, await createBundleMcpToolRuntime({
					workspaceDir,
					cfg
				}));
			} catch (error) {
				bundleRuntimeLoadErrorsByWorkspace.set(workspaceDir, bundleMcpRuntimeLoadFailureFinding(error));
			}
			const bundleRuntimeLoadError = bundleRuntimeLoadErrorsByWorkspace.get(workspaceDir);
			if (bundleRuntimeLoadError) {
				if (!reportedBundleRuntimeLoadErrors.has(workspaceDir)) {
					findings.push(bundleRuntimeLoadError);
					reportedBundleRuntimeLoadErrors.add(workspaceDir);
				}
				continue;
			}
			const bundleRuntime = bundleRuntimeByWorkspace.get(workspaceDir);
			if (bundleRuntime) {
				if (bundleRuntime.diagnostics && bundleRuntime.diagnostics.length > 0) {
					const policyActiveDiagnostics = filterPolicyActiveBundleMcpDiagnostics({
						diagnostics: bundleRuntime.diagnostics,
						cfg,
						agentId,
						modelRef
					});
					findings.push(...policyActiveDiagnostics.map(bundleMcpRuntimeDiagnosticFinding));
				}
				findings.push(...collectBundleMcpRuntimeToolSchemaFindings({
					bundleRuntime,
					cfg,
					agentId,
					workspaceDir,
					modelRef,
					model
				}));
			}
		}
	} finally {
		await Promise.all([...bundleRuntimeByWorkspace.values()].map((runtime) => runtime.dispose()));
	}
	return findings;
}
//#endregion
export { collectRuntimeToolSchemaFindings, detectUnavailableSkills };
