import crypto from "node:crypto";

//#region src/cron/parse.ts
const ISO_TZ_RE = /(Z|[+-]\d{2}:?\d{2})$/i;
const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
const ISO_DATE_TIME_RE = /^\d{4}-\d{2}-\d{2}T/;
function normalizeUtcIso(raw) {
	if (ISO_TZ_RE.test(raw)) return raw;
	if (ISO_DATE_RE.test(raw)) return `${raw}T00:00:00Z`;
	if (ISO_DATE_TIME_RE.test(raw)) return `${raw}Z`;
	return raw;
}
function parseAbsoluteTimeMs(input) {
	const raw = input.trim();
	if (!raw) return null;
	if (/^\d+$/.test(raw)) {
		const n = Number(raw);
		if (Number.isFinite(n) && n > 0) return Math.floor(n);
	}
	const parsed = Date.parse(normalizeUtcIso(raw));
	return Number.isFinite(parsed) ? parsed : null;
}

//#endregion
//#region src/cron/stagger.ts
const DEFAULT_TOP_OF_HOUR_STAGGER_MS = 300 * 1e3;
function parseCronFields(expr) {
	return expr.trim().split(/\s+/).filter(Boolean);
}
function isRecurringTopOfHourCronExpr(expr) {
	const fields = parseCronFields(expr);
	if (fields.length === 5) {
		const [minuteField, hourField] = fields;
		return minuteField === "0" && hourField.includes("*");
	}
	if (fields.length === 6) {
		const [secondField, minuteField, hourField] = fields;
		return secondField === "0" && minuteField === "0" && hourField.includes("*");
	}
	return false;
}
function normalizeCronStaggerMs(raw) {
	const numeric = typeof raw === "number" ? raw : typeof raw === "string" && raw.trim() ? Number(raw) : NaN;
	if (!Number.isFinite(numeric)) return;
	return Math.max(0, Math.floor(numeric));
}
function resolveDefaultCronStaggerMs(expr) {
	return isRecurringTopOfHourCronExpr(expr) ? DEFAULT_TOP_OF_HOUR_STAGGER_MS : void 0;
}
function resolveCronStaggerMs(schedule) {
	const explicit = normalizeCronStaggerMs(schedule.staggerMs);
	if (explicit !== void 0) return explicit;
	const expr = schedule.expr;
	return resolveDefaultCronStaggerMs(typeof expr === "string" ? expr : "") ?? 0;
}

//#endregion
//#region src/infra/format-time/format-duration.ts
function formatDurationSeconds(ms, options = {}) {
	if (!Number.isFinite(ms)) return "unknown";
	const decimals = options.decimals ?? 1;
	const unit = options.unit ?? "s";
	const trimmed = (Math.max(0, ms) / 1e3).toFixed(Math.max(0, decimals)).replace(/\.0+$/, "").replace(/(\.\d*[1-9])0+$/, "$1");
	return unit === "seconds" ? `${trimmed} seconds` : `${trimmed}s`;
}
/** Precise decimal-seconds output: "500ms" or "1.23s". Input is milliseconds. */
function formatDurationPrecise(ms, options = {}) {
	if (!Number.isFinite(ms)) return "unknown";
	if (ms < 1e3) return `${ms}ms`;
	return formatDurationSeconds(ms, {
		decimals: options.decimals ?? 2,
		unit: options.unit ?? "s"
	});
}
/**
* Compact compound duration: "500ms", "45s", "2m5s", "1h30m".
* With `spaced`: "45s", "2m 5s", "1h 30m".
* Omits trailing zero components: "1m" not "1m 0s", "2h" not "2h 0m".
* Returns undefined for null/undefined/non-finite/non-positive input.
*/
function formatDurationCompact(ms, options) {
	if (ms == null || !Number.isFinite(ms) || ms <= 0) return;
	if (ms < 1e3) return `${Math.round(ms)}ms`;
	const sep = options?.spaced ? " " : "";
	const totalSeconds = Math.round(ms / 1e3);
	const hours = Math.floor(totalSeconds / 3600);
	const minutes = Math.floor(totalSeconds % 3600 / 60);
	const seconds = totalSeconds % 60;
	if (hours >= 24) {
		const days = Math.floor(hours / 24);
		const remainingHours = hours % 24;
		return remainingHours > 0 ? `${days}d${sep}${remainingHours}h` : `${days}d`;
	}
	if (hours > 0) return minutes > 0 ? `${hours}h${sep}${minutes}m` : `${hours}h`;
	if (minutes > 0) return seconds > 0 ? `${minutes}m${sep}${seconds}s` : `${minutes}m`;
	return `${seconds}s`;
}
/**
* Rounded single-unit duration for display: "500ms", "5s", "3m", "2h", "5d".
* Returns fallback string for null/undefined/non-finite input.
*/
function formatDurationHuman(ms, fallback = "n/a") {
	if (ms == null || !Number.isFinite(ms) || ms < 0) return fallback;
	if (ms < 1e3) return `${Math.round(ms)}ms`;
	const sec = Math.round(ms / 1e3);
	if (sec < 60) return `${sec}s`;
	const min = Math.round(sec / 60);
	if (min < 60) return `${min}m`;
	const hr = Math.round(min / 60);
	if (hr < 24) return `${hr}h`;
	return `${Math.round(hr / 24)}d`;
}

//#endregion
//#region src/cron/run-detail-format.ts
function formatAge(ms, nowMs = Date.now()) {
	if (!ms || !Number.isFinite(ms)) return "n/a";
	const seconds = Math.max(0, Math.round((nowMs - ms) / 1e3));
	if (seconds < 60) return `${seconds}s ago`;
	const minutes = Math.round(seconds / 60);
	if (minutes < 60) return `${minutes}m ago`;
	const hours = Math.round(minutes / 60);
	if (hours < 48) return `${hours}h ago`;
	return `${Math.round(hours / 24)}d ago`;
}
function formatCronRunLoadedSkills(policy) {
	const skills = policy?.skills;
	const scope = policy?.skillScope;
	if (!skills && !scope) return;
	const mode = scope === "none" ? "No skills" : scope === "agent-default" ? "Inherited from Agent" : skills?.skillFilter === void 0 ? "Inherited from Agent" : skills.skillFilter.length === 0 ? "No skills" : "Narrow selected";
	if (!skills) return `Skills: ${mode}`;
	const listed = skills.names.length > 0 ? skills.names.join(", ") : "none loaded";
	const more = skills.count > skills.names.length ? ` +${skills.count - skills.names.length} more` : "";
	return `Skills: ${mode} · ${skills.count} loaded · ${listed}${more}`;
}
function formatDuration(ms) {
	if (typeof ms !== "number" || !Number.isFinite(ms)) return "n/a";
	if (ms < 1e3) return `${Math.round(ms)}ms`;
	if (ms < 6e4) return `${Math.round(ms / 100) / 10}s`;
	return `${Math.round(ms / 1e3 / 60)}m`;
}
function formatRelativeFuture(ms, nowMs = Date.now()) {
	if (typeof ms !== "number" || !Number.isFinite(ms)) return "n/a";
	const delta = ms - nowMs;
	const seconds = Math.max(0, Math.round(Math.abs(delta) / 1e3));
	const suffix = delta < 0 ? "ago" : "from now";
	if (seconds < 60) return `${seconds}s ${suffix}`;
	const minutes = Math.round(seconds / 60);
	if (minutes < 60) return `${minutes}m ${suffix}`;
	const hours = Math.round(minutes / 60);
	if (hours < 48) return `${hours}h ${suffix}`;
	return `${Math.round(hours / 24)}d ${suffix}`;
}
function formatExecution(detail) {
	const source = detail.execution.source;
	const adapter = detail.execution.adapter;
	if (source === "direct-tool") return `direct tool${adapter ? ` ${adapter}` : ""}`;
	if (source === "direct-text") return "direct text";
	if (source === "model") return detail.execution.model ? `model ${detail.execution.model}` : "model";
	return detail.logEntry?.policy?.effectiveExecutionMode ?? detail.job?.executionPolicy?.executionMode ?? "queue";
}
function formatDelivery(detail) {
	const status = detail.execution.deliveryStatus;
	if (status) return status;
	if (typeof detail.execution.delivered === "boolean") return detail.execution.delivered ? "delivered" : "not-delivered";
	return "unknown";
}
function formatCheckpoint(checkpoint) {
	if (!checkpoint || Object.keys(checkpoint).length === 0) return "";
	const keys = Object.keys(checkpoint).slice(0, 4);
	const suffix = Object.keys(checkpoint).length > keys.length ? ", ..." : "";
	return ` · checkpoint ${keys.join(", ")}${suffix}`;
}
function formatCoordinationEvidence(checkpoint) {
	const evidence = checkpoint?.coordinationEvidence;
	if (!Array.isArray(evidence) || evidence.length === 0) return "";
	const statuses = evidence.map((entry) => {
		const status = entry && typeof entry === "object" && "status" in entry ? entry.status : void 0;
		return typeof status === "string" ? status : "";
	}).filter(Boolean);
	const statusText = statuses.length ? ` · ${statuses.join(", ")}` : "";
	return ` · task-room evidence ${evidence.length}${statusText}`;
}
function readStringField(value, field) {
	if (!value || typeof value !== "object") return;
	const raw = value[field];
	return typeof raw === "string" && raw.trim() ? raw.trim() : void 0;
}
function coordinationEvidenceFromUnknown(value) {
	if (!Array.isArray(value)) return [];
	return value.map((entry) => {
		const agentId = readStringField(entry, "agentId");
		const status = readStringField(entry, "status");
		if (!agentId || !status) return null;
		return {
			agentId,
			status,
			mode: readStringField(entry, "mode"),
			childSessionKey: readStringField(entry, "childSessionKey"),
			runId: readStringField(entry, "runId"),
			summary: readStringField(entry, "summary"),
			outputText: readStringField(entry, "outputText"),
			error: readStringField(entry, "error")
		};
	}).filter((entry) => entry !== null);
}
function previewEvidenceText(value) {
	const text = value?.replace(/\s+/g, " ").trim();
	if (!text) return "";
	return text.length > 140 ? `${text.slice(0, 137).trimEnd()}...` : text;
}
function formatCoordinationEvidenceLines(detail) {
	const entries = [];
	for (const step of detail.stepDetails) entries.push(...coordinationEvidenceFromUnknown(step.checkpoint?.coordinationEvidence));
	entries.push(...coordinationEvidenceFromUnknown(detail.job?.state.lastCoordinationEvidence));
	const seen = /* @__PURE__ */ new Set();
	const unique = entries.filter((entry) => {
		const key = [
			entry.agentId,
			entry.status,
			entry.childSessionKey ?? "",
			entry.runId ?? "",
			entry.error ?? ""
		].join("\0");
		if (seen.has(key)) return false;
		seen.add(key);
		return true;
	});
	if (unique.length === 0) return [];
	return ["Task-room evidence:", ...unique.map((entry) => {
		const mode = entry.mode ? ` · ${entry.mode}` : "";
		const session = entry.childSessionKey ? ` · session ${entry.childSessionKey}` : "";
		const run = entry.runId ? ` · run ${entry.runId}` : "";
		const error = entry.error ? ` · error ${entry.error}` : "";
		const preview = previewEvidenceText(entry.outputText ?? entry.summary);
		const summary = preview ? ` · ${preview}` : "";
		return `- ${entry.agentId}: ${entry.status}${mode}${session}${run}${error}${summary}`;
	})];
}
function formatStepRetry(step, nowMs) {
	const policy = step.retryPolicy;
	const nextRetry = step.nextRetryAtMs ? ` · next retry ${formatRelativeFuture(step.nextRetryAtMs, nowMs)}` : "";
	if (!policy) return nextRetry;
	return ` · retry ${policy.retryOn} · delay ${formatDuration(policy.retryDelayMs)} · backoff ${policy.backoffMultiplier}x${nextRetry}`;
}
function formatStepResume(step) {
	if (!step.resume) return "";
	const keys = step.resume.checkpointKeys.slice(0, 4);
	const suffix = step.resume.checkpointKeys.length > keys.length ? ", ..." : "";
	const source = keys.length ? ` (${keys.join(", ")}${suffix})` : "";
	return ` · ${step.resume.resumable ? "resumable" : "not resumable"}${source}`;
}
function formatSteps(detail, nowMs) {
	const existingStepDetails = detail.stepDetails ?? [];
	const steps = existingStepDetails.length > 0 ? existingStepDetails : (detail.queueRun?.steps ?? []).map((step) => ({
		...step,
		durationMs: typeof step.startedAtMs === "number" && typeof step.completedAtMs === "number" ? Math.max(0, step.completedAtMs - step.startedAtMs) : void 0,
		leaseExpired: false,
		control: {
			available: false,
			label: "No step action",
			reason: ""
		}
	}));
	if (steps.length === 0) return [];
	return steps.map((step) => {
		const timing = [
			step.startedAtMs ? `started ${formatAge(step.startedAtMs, nowMs)}` : void 0,
			step.completedAtMs ? `completed ${formatAge(step.completedAtMs, nowMs)}` : void 0,
			step.durationMs ? `duration ${formatDuration(step.durationMs)}` : void 0
		].filter(Boolean).join(" · ");
		const lease = [step.leaseOwner ? `lease ${step.leaseOwner}` : void 0, step.leaseExpiresAtMs ? `${step.leaseExpired ? "expired" : "expires"} ${formatRelativeFuture(step.leaseExpiresAtMs, nowMs)}` : void 0].filter(Boolean).join(" · ");
		const err = step.error ? ` · ${step.error}` : "";
		const control = step.control.reason ? ` · ${step.control.label}: ${step.control.reason}` : ` · ${step.control.label}`;
		return `- ${[
			`${step.id}: ${step.status}`,
			`attempt ${step.attempt}/${step.maxAttempts}`,
			timing || void 0,
			lease || void 0
		].filter(Boolean).join(" · ")}${formatStepRetry(step, nowMs)}${formatStepResume(step)}${control}${formatCheckpoint(step.checkpoint)}${formatCoordinationEvidence(step.checkpoint)}${err}`;
	});
}
function formatWorkflowGraph(detail) {
	const graph = detail.workflowGraph;
	if (!graph || graph.nodes.length === 0) return;
	const byId = new Map(graph.nodes.map((node) => [node.id, node]));
	const ordered = graph.nodes.map((node) => node.label || node.id);
	const terminal = graph.terminalNodeIds.map((id) => byId.get(id)?.label ?? id).filter(Boolean).join(", ");
	const revision = typeof graph.graphRevision === "number" && Number.isFinite(graph.graphRevision) ? ` · rev ${graph.graphRevision}` : "";
	return `${ordered.join(" -> ")}${terminal ? ` · terminal ${terminal}` : ""}${revision}`;
}
function formatListPreview(values, empty) {
	if (values.length === 0) return empty;
	const visible = values.slice(0, 5);
	const suffix = values.length > visible.length ? `, +${values.length - visible.length}` : "";
	return `${visible.join(", ")}${suffix}`;
}
function compactInline(value, max = 120) {
	const text = value.replace(/\s+/g, " ").trim();
	return text.length > max ? `${text.slice(0, Math.max(0, max - 1)).trim()}...` : text;
}
function runIdFromEntry(entry) {
	return entry?.policy?.runCheckpoint?.runId?.trim();
}
function isEscalationFollowup(entry) {
	const evaluator = entry?.policy?.evaluator;
	return evaluator?.action === "none" && /escalation follow-up completed/i.test(evaluator.reason);
}
function isEscalationTrigger(entry) {
	return entry?.policy?.evaluator?.action === "escalate";
}
function formatRunLogEntryUsage(entry) {
	const usage = entry?.usage;
	if (!usage) return;
	const total = typeof usage.total_tokens === "number" ? usage.total_tokens : void 0;
	const input = typeof usage.input_tokens === "number" ? usage.input_tokens : void 0;
	const output = typeof usage.output_tokens === "number" ? usage.output_tokens : void 0;
	const parts = [
		total !== void 0 ? `${total} tok` : void 0,
		input !== void 0 ? `${input} in` : void 0,
		output !== void 0 ? `${output} out` : void 0
	].filter(Boolean);
	return parts.length > 0 ? parts.join(" · ") : void 0;
}
function formatRunLogEntryModel(entry) {
	if (!entry) return "unknown";
	const source = entry.policy?.resultSource;
	const adapter = entry.policy?.resultAdapter;
	if (source === "direct-tool") return `direct tool${adapter ? ` ${adapter}` : ""}`;
	if (source === "direct-text") return "direct text";
	if (entry.policy?.modelUsed === false) return "no model";
	return `${entry.model ? `model ${entry.model}` : "model"}${entry.policy?.modelSource ? ` · ${entry.policy.modelSource}` : ""}`;
}
function formatEscalationPass(label, entry) {
	const runId = runIdFromEntry(entry);
	const duration = typeof entry?.durationMs === "number" && Number.isFinite(entry.durationMs) ? ` · ${formatDuration(entry.durationMs)}` : "";
	const usage = formatRunLogEntryUsage(entry);
	return `${label}: ${formatRunLogEntryModel(entry)}${usage ? ` · ${usage}` : ""}${duration}${runId ? ` · run ${runId}` : ""}`;
}
function formatCronEscalationPasses(params) {
	const entry = params.entry;
	if (!entry?.policy?.evaluator) return [];
	const triggerEntry = (params.previousEntries ?? []).find(isEscalationTrigger);
	if (isEscalationFollowup(entry) && triggerEntry) return [formatEscalationPass("Cheap pass", triggerEntry), formatEscalationPass("Escalation pass", entry)];
	if (isEscalationTrigger(entry)) return [formatEscalationPass("Cheap pass", entry)];
	return [];
}
function formatCronEscalationContext(params) {
	const entry = params.entry;
	const evaluator = entry?.policy?.evaluator;
	if (!evaluator) return;
	const triggerEntry = (params.previousEntries ?? []).find(isEscalationTrigger);
	const signal = triggerEntry?.policy?.evaluator?.signal ?? params.job?.state.evaluatorLastSignal;
	const triggerRunId = runIdFromEntry(triggerEntry);
	if (isEscalationFollowup(entry)) {
		const parts = ["follow-up completed"];
		if (triggerRunId) parts.push(`trigger run ${triggerRunId}`);
		if (signal) parts.push(`cue "${compactInline(signal)}"`);
		return `Escalation: ${parts.join(" · ")}`;
	}
	if (isEscalationTrigger(entry)) {
		const parts = ["triggered follow-up"];
		if (evaluator.signal) parts.push(`cue "${compactInline(evaluator.signal)}"`);
		return `Escalation: ${parts.join(" · ")}`;
	}
}
function formatGraphRepairReplay(detail) {
	const replay = detail.repairReplay;
	if (!replay) return [];
	const lines = [
		`Repair replay: graph revision ${replay.graphRevision}${replay.parentRevision ? ` from ${replay.parentRevision}` : ""} · repair revision ${replay.repairRevision} · attempt ${replay.repairAttempt}/${replay.maxRepairAttempts}`,
		`Reused checkpoints: ${replay.reusedNodeIds.length}${replay.reusedNodeIds.length ? ` · ${formatListPreview(replay.reusedNodeIds, "")}` : ""}`,
		`Invalidated nodes: ${replay.invalidatedNodeIds.length}${replay.invalidatedNodeIds.length ? ` · ${formatListPreview(replay.invalidatedNodeIds, "")}` : ""}`,
		`Reran nodes: ${formatListPreview(replay.requeuedNodeIds, "none")}`
	];
	if (replay.reason) lines.push(`Repair reason: ${replay.reason}`);
	return lines;
}
function trustedSourceById(detail) {
	const sources = detail.job?.executionPolicy?.trustedSources ?? [];
	return new Map(sources.map((source) => [source.id, source]));
}
function formatTrustedSourceQuality(detail) {
	const trusted = (detail.logEntry?.policy?.sourceQuality?.sources ?? []).filter((source) => source.trustedSourceId);
	if (trusted.length === 0) return [];
	const sourceMap = trustedSourceById(detail);
	return ["Trusted sources:", ...trusted.map((source) => {
		const saved = source.trustedSourceId ? sourceMap.get(source.trustedSourceId) : void 0;
		const score = typeof source.score === "number" ? source.score.toFixed(2) : "n/a";
		const sourceText = saved?.source ? ` · ${saved.source}` : "";
		const counts = saved ? ` · ok ${saved.successCount ?? 0} · fail ${saved.failureCount ?? 0}` : "";
		return `- ${source.trustedSourceId} · ${source.id} · ${source.status ?? "unknown"} · score ${score}${counts}${sourceText}`;
	})];
}
function formatRepairRecommendationCommand(jobId, recommendation, commandPrefix) {
	switch (recommendation.action) {
		case "configure_source": return `${commandPrefix} repair ${jobId} configure`;
		case "add_trusted_source": return `${commandPrefix} repair ${jobId} add-source <url-or-note>`;
		case "retry_replacement": return `${commandPrefix} repair ${jobId} retry`;
		case "stop_source_path": return `${commandPrefix} repair ${jobId} stop-source${recommendation.sourceNodeId ? ` ${recommendation.sourceNodeId}` : ""}`;
	}
}
function formatRepairRecommendations(detail, commandPrefix) {
	const recommendations = detail.recommendedRepairActions ?? [];
	if (recommendations.length === 0) return [];
	return ["Recommended repair:", ...recommendations.map((recommendation) => {
		const command = formatRepairRecommendationCommand(detail.jobId, recommendation, commandPrefix);
		const setup = recommendation.setupCommand ? ` · ${recommendation.setupCommand}` : "";
		return `- ${recommendation.priority}: ${recommendation.label} · ${recommendation.reason} · ${command}${setup}`;
	})];
}
function cronGraphRepairsForRun(job, runId) {
	const state = job?.state;
	if (!state || !runId) return [];
	const scopedRunIds = [state.lastRunCheckpoint?.runId, state.activeRun?.runId].filter((entry) => typeof entry === "string" && entry.trim().length > 0);
	if (scopedRunIds.length > 0 && !scopedRunIds.includes(runId)) return [];
	if (state.lastGraphRepairs?.length) return state.lastGraphRepairs;
	return state.lastGraphRepair ? [state.lastGraphRepair] : [];
}
function formatCronGraphRepairLine(repair) {
	const action = repair.action === "replace_source" ? `replace ${repair.replacesNodeId ?? "source"} -> ${repair.nodeId}` : `add ${repair.nodeId}`;
	const state = repair.applied === true ? "applied" : repair.applied === false ? "not applied" : "planned";
	const reason = repair.applyReason ?? repair.reason;
	return `${action} · ${repair.toolName} · ${state}${reason ? ` · ${reason}` : ""}`;
}
function formatCronGraphRepairLines(repairs, opts) {
	if (repairs.length === 0) return [];
	return repairs.map((repair) => `${opts?.bullet === false ? "" : "- "}${formatCronGraphRepairLine(repair)}`);
}
function formatCronTaskRunDetail(detail, opts) {
	const nowMs = opts?.nowMs ?? Date.now();
	const commandPrefix = opts?.commandPrefix ?? "fased task";
	const lines = [
		`Run: ${detail.runId}`,
		`Task: ${detail.jobName} (${detail.jobId})`,
		`Status: ${detail.status}`
	];
	if (detail.trigger) lines.push(`Trigger: ${detail.trigger}`);
	if (detail.updatedAtMs) lines.push(`Updated: ${formatAge(detail.updatedAtMs, nowMs)} (${new Date(detail.updatedAtMs).toISOString()})`);
	if (detail.agentId) lines.push(`Agent: ${detail.agentId}`);
	if (detail.sessionKey) lines.push(`Session: ${detail.sessionKey}`);
	lines.push(`Execution: ${formatExecution(detail)}`);
	lines.push(`Model used: ${detail.execution.modelUsed === false ? "no" : detail.execution.model ?? "unknown"}`);
	lines.push(`Delivery: ${formatDelivery(detail)}`);
	lines.push(`Duration: ${formatDuration(detail.execution.durationMs)}`);
	if (detail.logEntry?.policy?.planner) {
		const planner = detail.logEntry.policy.planner;
		lines.push(`Planner: ${planner.strategy} · ${planner.rationale}`);
	}
	const loadedSkills = formatCronRunLoadedSkills(detail.logEntry?.policy);
	if (loadedSkills) lines.push(loadedSkills);
	const adaptive = detail.logEntry?.policy?.adaptive ?? detail.job?.state.adaptiveRouting?.lastDecision;
	if (adaptive) lines.push(`Adaptive next: ${adaptive.route} · ${adaptive.reason} · ${adaptive.sampleSize} sample${adaptive.sampleSize === 1 ? "" : "s"}`);
	const workflowGraph = formatWorkflowGraph(detail);
	if (workflowGraph) lines.push(`Workflow: ${workflowGraph}`);
	if (detail.logEntry?.policy?.evaluator) {
		const evaluator = detail.logEntry.policy.evaluator;
		lines.push(`Evaluator: ${evaluator.action} · ${evaluator.reason}`);
	}
	const escalationContext = formatCronEscalationContext({
		entry: detail.logEntry,
		job: detail.job,
		previousEntries: opts?.previousLogEntries
	});
	if (escalationContext) lines.push(escalationContext);
	lines.push(...formatCronEscalationPasses({
		entry: detail.logEntry,
		previousEntries: opts?.previousLogEntries
	}));
	if (detail.logEntry?.policy?.sourceVerificationStatus) {
		const policy = detail.logEntry.policy;
		lines.push(`Source verification: ${policy.sourceVerificationStatus}${typeof policy.sourceConflictCount === "number" ? ` · conflicts ${policy.sourceConflictCount}` : ""}${policy.escalatedBecause ? ` · escalated ${policy.escalatedBecause}` : ""}`);
	}
	if (detail.logEntry?.policy?.sourceQuality) {
		const quality = detail.logEntry.policy.sourceQuality;
		lines.push(`Source quality: best ${quality.bestSourceId ?? "unknown"}${typeof quality.bestScore === "number" ? ` · ${quality.bestScore.toFixed(2)}` : ""} · low ${quality.lowQualityCount ?? 0} · unavailable ${quality.unavailableCount ?? 0}`);
	}
	lines.push(...formatTrustedSourceQuality(detail));
	lines.push(...formatRepairRecommendations(detail, commandPrefix));
	const graphRepairs = cronGraphRepairsForRun(detail.job, detail.runId);
	if (graphRepairs.length > 0) {
		lines.push("Source repair:");
		lines.push(...formatCronGraphRepairLines(graphRepairs));
	}
	lines.push(...formatGraphRepairReplay(detail));
	if (detail.execution.usage?.total_tokens) lines.push(`Tokens: ${detail.execution.usage.total_tokens}`);
	if (detail.execution.error || detail.error) lines.push(`Error: ${detail.execution.error ?? detail.error}`);
	if (detail.execution.summary) lines.push(`Summary: ${detail.execution.summary}`);
	lines.push(...formatCoordinationEvidenceLines(detail));
	const steps = formatSteps(detail, nowMs);
	if (steps.length > 0) {
		lines.push("Steps:");
		lines.push(...steps);
	}
	const actions = [];
	if (detail.controls.canCancel) actions.push(`${commandPrefix} cancel-run ${detail.runId}`);
	if (detail.controls.canRetry) actions.push(`${commandPrefix} retry-run ${detail.runId}`);
	if (detail.controls.canClearStaleLease) actions.push(`${commandPrefix} clear-stale ${detail.runId}`);
	if (actions.length > 0) {
		lines.push("Actions:");
		lines.push(...actions.map((action) => `- ${action}`));
	}
	if (detail.transcriptPath) lines.push(`Transcript: ${detail.transcriptPath}`);
	return lines.join("\n");
}

//#endregion
//#region src/cron/trusted-sources.ts
const MAX_MATCHED_TRUSTED_SOURCES = 3;
const MAX_STORED_TRUSTED_SOURCES = 100;
function payloadText(job) {
	return job.payload.kind === "agentTurn" ? job.payload.message : job.payload.text;
}
function firstUrlFromText$1(value) {
	return value.match(/https?:\/\/[^\s<>"')]+/i)?.[0];
}
function normalizeSource(value) {
	return value.trim().replace(/\s+/g, " ");
}
function shortHash(value) {
	return crypto.createHash("sha256").update(value).digest("hex").slice(0, 12);
}
function uniqueBySource(entries) {
	const seen = /* @__PURE__ */ new Set();
	const out = [];
	for (const entry of entries) {
		const key = normalizeSource(entry.source).toLowerCase();
		if (!key || seen.has(key)) continue;
		seen.add(key);
		out.push(entry);
	}
	return out;
}
function trustedSourceUrl(source) {
	return source.kind === "url" ? firstUrlFromText$1(source.source) : void 0;
}
function classifyTrustedSourceTaskType(text) {
	const value = text.toLowerCase();
	if (/\bwallet\b|\bwallets?\b|\bbalances?\b|\baddress\b/.test(value)) return "wallet";
	if (/\bmining\b|\bsat mining\b|\bminers?\b/.test(value)) return "mining";
	if (/\boffers?\b|\bmarketplace\b|\borders?\b|\brequests?\b/.test(value)) return "offers";
	if (/\bgateway\b|\bproviders?\b|\bmodel auth\b|\bmodel catalog\b|\bapi credentials?\b/.test(value)) return "provider";
	if (/\bmarket\b|\bbtc\b|\bsol\b|\brisk\b|\bnews\b|\bprice\b|\blive\b/.test(value)) return "market";
	if (/\bweb\b|\bsearch\b|\bsource\b|\bexternal\b|\bremote\b|\burl\b/.test(value)) return "external";
	return "general";
}
function createTrustedSourceForJob(params) {
	const source = normalizeSource(params.source);
	const taskType = classifyTrustedSourceTaskType([
		params.job.name,
		params.job.description ?? "",
		payloadText(params.job)
	].join(" "));
	const url = firstUrlFromText$1(source);
	return {
		id: `trusted-${shortHash([
			params.job.agentId ?? "",
			params.job.sessionKey ?? "",
			taskType,
			source.toLowerCase()
		].join("\n"))}`,
		source,
		kind: url ? "url" : "note",
		createdAtMs: params.nowMs,
		updatedAtMs: params.nowMs,
		lastUsedAtMs: params.nowMs,
		useCount: 1,
		agentId: params.job.agentId,
		sessionKey: params.job.sessionKey,
		taskType,
		addedFromTaskId: params.job.id,
		active: true
	};
}
function mergeTrustedSources(current, next) {
	const merged = uniqueBySource([...current ?? [], ...next ?? []]);
	return merged.length > 0 ? merged : void 0;
}
function upsertTrustedSource(store, source) {
	const list = store.trustedSources ? [...store.trustedSources] : [];
	const normalized = normalizeSource(source.source).toLowerCase();
	const existingIndex = list.findIndex((entry) => normalizeSource(entry.source).toLowerCase() === normalized && (entry.agentId ?? "") === (source.agentId ?? "") && (entry.sessionKey ?? "") === (source.sessionKey ?? "") && (entry.taskType ?? "") === (source.taskType ?? ""));
	if (existingIndex >= 0) {
		const existing = list[existingIndex];
		const updated = {
			...existing,
			...source,
			id: existing.id,
			createdAtMs: existing.createdAtMs,
			updatedAtMs: source.updatedAtMs,
			lastUsedAtMs: source.lastUsedAtMs,
			useCount: (existing.useCount ?? 0) + 1,
			successCount: existing.successCount,
			failureCount: existing.failureCount,
			lastRunAtMs: existing.lastRunAtMs,
			lastOutcome: existing.lastOutcome,
			lastQualityScore: existing.lastQualityScore,
			lastQualityBand: existing.lastQualityBand,
			lastError: existing.lastError,
			active: true
		};
		list[existingIndex] = updated;
		store.trustedSources = list;
		return updated;
	}
	list.unshift(source);
	store.trustedSources = list.slice(0, MAX_STORED_TRUSTED_SOURCES);
	return source;
}
function sourceOutcomeIsSuccess(params) {
	if (params.status !== "ok") return false;
	if (params.qualityBand === "unavailable" || params.qualityBand === "low") return false;
	if (typeof params.qualityScore === "number" && params.qualityScore <= 0) return false;
	return true;
}
function recordTrustedSourceOutcome(store, params) {
	const trustedSourceId = params.trustedSourceId?.trim();
	if (!trustedSourceId || !store.trustedSources?.length) return;
	const index = store.trustedSources.findIndex((entry) => entry.id === trustedSourceId);
	if (index < 0) return;
	const current = store.trustedSources[index];
	const success = sourceOutcomeIsSuccess({
		status: params.status,
		qualityBand: params.qualityBand,
		qualityScore: params.qualityScore
	});
	const updated = {
		...current,
		updatedAtMs: params.nowMs,
		lastUsedAtMs: params.nowMs,
		lastRunAtMs: params.nowMs,
		lastOutcome: params.status,
		lastQualityScore: params.qualityScore,
		lastQualityBand: params.qualityBand,
		lastError: params.error,
		useCount: (current.useCount ?? 0) + 1,
		successCount: (current.successCount ?? 0) + (success ? 1 : 0),
		failureCount: (current.failureCount ?? 0) + (success ? 0 : 1)
	};
	store.trustedSources[index] = updated;
	return updated;
}
function trustedSourceOutcomeScore(entry) {
	let score = 0;
	score += Math.min(4, (entry.successCount ?? 0) * 1.5);
	score -= Math.min(8, (entry.failureCount ?? 0) * 2);
	if (entry.lastOutcome && entry.lastOutcome !== "ok") score -= 1.5;
	if (typeof entry.lastQualityScore === "number" && Number.isFinite(entry.lastQualityScore)) score += (entry.lastQualityScore - .5) * 4;
	if (entry.lastQualityBand === "high") score += 2;
	else if (entry.lastQualityBand === "medium") score += .75;
	else if (entry.lastQualityBand === "low") score -= 2.5;
	else if (entry.lastQualityBand === "unavailable") score -= 4;
	return score;
}
function matchingTrustedSourcesForTask(params) {
	const entries = params.store?.trustedSources ?? [];
	if (entries.length === 0) return [];
	const taskType = classifyTrustedSourceTaskType(params.text);
	return uniqueBySource(entries.filter((entry) => entry.active !== false && normalizeSource(entry.source)).filter((entry) => !entry.agentId || entry.agentId === params.agentId).map((entry) => {
		let score = 0;
		if (entry.sessionKey && params.sessionKey && entry.sessionKey === params.sessionKey) score += 8;
		if (entry.agentId && params.agentId && entry.agentId === params.agentId) score += 4;
		if (entry.taskType && entry.taskType === taskType) score += 6;
		if (entry.kind === "url") score += 2;
		score += Math.min(3, entry.useCount ?? 0);
		score += trustedSourceOutcomeScore(entry);
		return {
			entry,
			score
		};
	}).filter(({ score }) => score >= 6).toSorted((a, b) => {
		if (b.score !== a.score) return b.score - a.score;
		return (b.entry.lastUsedAtMs ?? b.entry.createdAtMs) - (a.entry.lastUsedAtMs ?? a.entry.createdAtMs);
	}).map(({ entry }) => entry)).slice(0, params.limit ?? MAX_MATCHED_TRUSTED_SOURCES);
}
function sourceMatchesText(entry, query) {
	return [
		entry.id,
		entry.source,
		entry.kind,
		entry.agentId,
		entry.sessionKey,
		entry.taskType,
		entry.label,
		entry.lastOutcome,
		entry.lastQualityBand,
		entry.lastError
	].filter(Boolean).join(" ").toLowerCase().includes(query.toLowerCase());
}
function listTrustedSources(store, filters = {}) {
	const query = filters.query?.trim();
	return (store.trustedSources ?? []).filter((entry) => filters.includeInactive === true || entry.active !== false).filter((entry) => !filters.agentId || entry.agentId === filters.agentId).filter((entry) => !filters.sessionKey || entry.sessionKey === filters.sessionKey).filter((entry) => !filters.taskType || entry.taskType === filters.taskType).filter((entry) => !query || sourceMatchesText(entry, query)).toSorted((a, b) => {
		const scoreDelta = trustedSourceOutcomeScore(b) - trustedSourceOutcomeScore(a);
		if (scoreDelta !== 0) return scoreDelta;
		return (b.lastUsedAtMs ?? b.createdAtMs) - (a.lastUsedAtMs ?? a.createdAtMs);
	});
}
function setTrustedSourceActive(store, id, active, nowMs) {
	const source = store.trustedSources?.find((entry) => entry.id === id);
	if (!source) return;
	source.active = active;
	source.updatedAtMs = nowMs;
	return source;
}
function removeTrustedSource(store, id) {
	const sources = store.trustedSources ?? [];
	const next = sources.filter((entry) => entry.id !== id);
	if (next.length === sources.length) return false;
	store.trustedSources = next.length > 0 ? next : void 0;
	return true;
}

//#endregion
//#region src/cron/task-planner.ts
const DEFAULT_ESCALATION_SIGNAL_INCLUDES = ["Needs deeper analysis: yes"];
const SOURCE_REPAIR_NODE_IDS = {
	web_fetch: "source-fetch-repair-web-fetch",
	gateway: "source-fetch-repair-gateway",
	wallet: "source-fetch-repair-wallet",
	mining: "source-fetch-repair-mining",
	offers: "source-fetch-repair-offers",
	web_search: "source-fetch-repair-web-search"
};
const SOURCE_REPAIR_WEB_SEARCH_NODE_ID = SOURCE_REPAIR_NODE_IDS.web_search;
function repairNodeSuffix(value) {
	return value.replace(/^source-fetch-/, "").replace(/[^a-z0-9]+/gi, "-").replace(/^-+|-+$/g, "").toLowerCase().slice(0, 48);
}
function sourceRepairNodeIdForTool(toolName, replacesNodeId) {
	const baseNodeId = SOURCE_REPAIR_NODE_IDS[toolName];
	if (!replacesNodeId?.trim()) return baseNodeId;
	const suffix = repairNodeSuffix(replacesNodeId);
	return suffix ? `${baseNodeId}-for-${suffix}` : baseNodeId;
}
function clonePolicy(policy) {
	return {
		...policy,
		allowedSkills: policy?.allowedSkills ? [...policy.allowedSkills] : void 0,
		skillAction: policy?.skillAction ? {
			...policy.skillAction,
			input: policy.skillAction.input ? { ...policy.skillAction.input } : void 0
		} : void 0,
		modelPolicy: policy?.modelPolicy ? { ...policy.modelPolicy } : void 0,
		coordination: policy?.coordination ? {
			...policy.coordination,
			agents: policy.coordination.agents ? [...policy.coordination.agents] : void 0
		} : void 0,
		budget: policy?.budget ? { ...policy.budget } : void 0,
		evaluator: policy?.evaluator ? {
			...policy.evaluator,
			signalIncludes: policy.evaluator.signalIncludes ? [...policy.evaluator.signalIncludes] : void 0
		} : void 0,
		repairPolicy: policy?.repairPolicy ? { ...policy.repairPolicy } : void 0,
		stop: policy?.stop ? {
			...policy.stop,
			outputIncludes: policy.stop.outputIncludes ? [...policy.stop.outputIncludes] : void 0
		} : void 0,
		trustedSources: policy?.trustedSources ? policy.trustedSources.map((source) => ({ ...source })) : void 0,
		planner: policy?.planner ? {
			...policy.planner,
			signals: policy.planner.signals ? [...policy.planner.signals] : void 0,
			graph: policy.planner.graph ? {
				...policy.planner.graph,
				terminalNodeIds: [...policy.planner.graph.terminalNodeIds],
				nodes: policy.planner.graph.nodes.map((node) => ({
					...node,
					dependsOn: node.dependsOn ? [...node.dependsOn] : void 0,
					checkpointKeys: node.checkpointKeys ? [...node.checkpointKeys] : void 0
				}))
			} : void 0,
			steps: policy.planner.steps ? policy.planner.steps.map((step) => ({
				...step,
				checkpointKeys: step.checkpointKeys ? [...step.checkpointKeys] : void 0,
				substeps: step.substeps ? step.substeps.map((substep) => ({
					...substep,
					checkpointKeys: substep.checkpointKeys ? [...substep.checkpointKeys] : void 0
				})) : void 0
			})) : void 0
		} : void 0
	};
}
function normalizeText(params) {
	return [
		params.name,
		params.policy?.objective,
		params.policy?.successCriteria,
		params.message
	].filter((entry) => typeof entry === "string" && entry.trim().length > 0).join(" ").toLowerCase();
}
function hasAny(text, patterns) {
	return patterns.some((pattern) => pattern.test(text));
}
function isMiningSourceTask(text) {
	return /(?:^|\s)@?mining\b|\bsat mining\b|\bminers?\b|\baom\b/.test(text);
}
function isMiningStrategyTask(text) {
	return isMiningSourceTask(text) && hasAny(text, [
		/\bstrategy\b/,
		/\ballocation\b/,
		/\bscore\b/,
		/\bbenchmark\b/,
		/\bperformance rebate\b/,
		/\bnet sol cost\b/,
		/\bskill\b/,
		/\baom\b/
	]);
}
function forbidsExternalSearch(text) {
	return hasAny(text, [/\b(?:do not|don't|dont|never|no|without) (?:use |call |run |add )?(?:live )?(?:web )?search\b/, /\b(?:do not|don't|dont|never|no|without) (?:use |call |run |add )?(?:external|remote|online|internet) sources?\b/]);
}
function asksForExternalSearch(text) {
	if (forbidsExternalSearch(text)) return false;
	return hasAny(text, [
		/\bweb\b/,
		/\binternet\b/,
		/\bonline\b/,
		/\bexternal\b/,
		/\bremote\b/,
		/\bsearch\b/,
		/\bfind (?:online|on the web|sources?)\b/,
		/\bnews\b/,
		/\bheadlines?\b/,
		/\bprice\b/,
		/\bweather\b/,
		/\bbtc\b/,
		/\bmarket (?:news|price|data|source|sources)\b/
	]);
}
function firstUrlFromText(value) {
	return value.match(/https?:\/\/[^\s<>"')]+/i)?.[0];
}
function urlsFromText(value) {
	return new Set(Array.from(value.matchAll(/https?:\/\/[^\s<>"')]+/gi), (match) => match[0].toLowerCase()));
}
function decision(params) {
	return {
		source: "heuristic",
		strategy: params.strategy,
		rationale: params.rationale,
		confidence: params.confidence,
		signals: params.signals,
		steps: params.steps,
		graph: params.graph
	};
}
function planned(policy, planner) {
	return {
		...policy,
		planner
	};
}
function workflowSteps(kind) {
	if (kind === "no-model") return [{
		id: "deliver",
		label: "Deliver",
		description: "Send the prepared task text to the selected delivery target.",
		retryable: true,
		checkpointKeys: ["outputText", "deliveryTarget"]
	}];
	if (kind === "skill-only") return [{
		id: "collect",
		label: "Collect",
		description: "Resolve deterministic tool input and task routing.",
		usesTool: true,
		retryable: true,
		checkpointKeys: ["toolName", "toolInput"]
	}, {
		id: "deliver",
		label: "Deliver",
		description: "Deliver the direct tool result without a model call.",
		retryable: true,
		checkpointKeys: ["outputText", "deliveryTarget"]
	}];
	return [
		{
			id: "collect",
			label: "Collect",
			description: "Collect context, policy, routing, and allowed tools for the run.",
			usesTool: true,
			retryable: true,
			checkpointKeys: [
				"memoryScope",
				"skillScope",
				"deliveryTarget"
			]
		},
		{
			id: "analyze",
			label: "Analyze",
			description: "Plan analysis, run the model/tool executor, and synthesize a replayable result checkpoint.",
			usesModel: true,
			usesTool: true,
			retryable: true,
			checkpointKeys: [
				"summary",
				"outputText",
				"model",
				"provider"
			],
			substeps: [
				{
					id: "plan-analysis",
					label: "Plan analysis",
					description: "Freeze the model, memory, skill, budget, evaluator, and delivery plan before expensive work starts.",
					retryable: true,
					checkpointKeys: [
						"modelPolicy",
						"memoryScope",
						"skillScope",
						"deliveryTarget"
					]
				},
				{
					id: "execute-tool-or-model",
					label: "Execute tool/model",
					description: "Run the selected deterministic tool or model-backed Agent turn.",
					usesModel: true,
					usesTool: true,
					retryable: true,
					checkpointKeys: [
						"summary",
						"outputText",
						"model",
						"provider"
					]
				},
				{
					id: "synthesize",
					label: "Synthesize",
					description: "Normalize the execution checkpoint for evaluator and delivery replay.",
					retryable: true,
					checkpointKeys: [
						"summary",
						"outputText",
						"resultStatus"
					]
				}
			]
		},
		{
			id: "evaluate",
			label: "Evaluate",
			description: "Apply evaluator, budget, stop, and escalation policy to the result.",
			retryable: false,
			checkpointKeys: [
				"resultStatus",
				"evaluator",
				"planner"
			]
		},
		{
			id: "deliver",
			label: "Deliver",
			description: "Deliver the saved result checkpoint without rerunning analysis.",
			retryable: true,
			checkpointKeys: [
				"delivered",
				"deliveryAttempted",
				"deliveryTarget"
			]
		}
	];
}
function normalizePlannerToolName(value) {
	return value?.trim().toLowerCase().replace(/^\$/, "") ?? "";
}
function isPolicyToolAllowed(policy, toolName) {
	const scope = policy?.skillScope;
	if (scope === "none") return false;
	if (scope !== "selected") return true;
	return new Set((policy?.allowedSkills ?? []).map(normalizePlannerToolName)).has(normalizePlannerToolName(toolName));
}
function sourceFetchGraphSpecs(text, policy) {
	const specs = [];
	const add = (spec) => {
		if (isPolicyToolAllowed(policy, spec.toolName) && !specs.some((entry) => entry.id === spec.id)) specs.push(spec);
	};
	const explicitUrls = urlsFromText(text);
	if (firstUrlFromText(text)) add({
		id: "source-fetch-web-fetch",
		label: "Fetch URL",
		toolName: "web_fetch",
		description: "Fetch the explicit URL before model analysis.",
		sourceRole: "primary",
		sourcePriority: 10,
		sourceFreshness: "static",
		sourceExpectedOutputType: "document",
		checkpointKeys: ["sourceUrl", "sourceOutput"]
	});
	if (/\bgateway\b|\bproviders?\b|\bmodel auth\b|\bmodel catalog\b|\bapi credentials?\b/.test(text)) add({
		id: "source-fetch-gateway",
		label: "Provider status",
		toolName: "gateway",
		description: "Read provider/auth/catalog state before model analysis.",
		sourceRole: "primary",
		sourcePriority: 20,
		sourceFreshness: "runtime",
		sourceExpectedOutputType: "provider-status",
		checkpointKeys: ["providerStatus", "sourceOutput"]
	});
	if (/\bwallet\b|\bwallets?\b|\bbalances?\b|\baddress\b/.test(text)) add({
		id: "source-fetch-wallet",
		label: "Wallet state",
		toolName: "wallet",
		description: "Read wallet state before model analysis.",
		sourceRole: "primary",
		sourcePriority: 20,
		sourceFreshness: "runtime",
		sourceExpectedOutputType: "wallet-state",
		checkpointKeys: ["walletState", "sourceOutput"]
	});
	if (isMiningSourceTask(text)) add({
		id: "source-fetch-mining",
		label: "Mining state",
		toolName: "mining",
		description: "Read mining state before model analysis.",
		sourceRole: "primary",
		sourcePriority: 20,
		sourceFreshness: "runtime",
		sourceExpectedOutputType: "mining-state",
		checkpointKeys: ["miningState", "sourceOutput"]
	});
	if (/\boffers?\b|\bmarketplace\b|\borders?\b|\brequests?\b/.test(text)) add({
		id: "source-fetch-offers",
		label: "Offers state",
		toolName: "offers",
		description: "Read offers and marketplace state before model analysis.",
		sourceRole: "primary",
		sourcePriority: 20,
		sourceFreshness: "runtime",
		sourceExpectedOutputType: "offers-state",
		checkpointKeys: ["offersState", "sourceOutput"]
	});
	for (const source of (policy?.trustedSources ?? []).filter((entry) => entry.active !== false)) {
		const url = trustedSourceUrl(source);
		if (!url || explicitUrls.has(url.toLowerCase())) continue;
		const hasPrimarySource = specs.some((spec) => spec.sourceRole === "primary");
		add({
			id: `source-fetch-trusted-${source.id.replace(/^trusted-/, "").slice(0, 48)}`,
			label: "Trusted source",
			toolName: "web_fetch",
			description: "Fetch a saved trusted source before model analysis.",
			sourceRole: hasPrimarySource ? "verification" : "primary",
			sourcePriority: hasPrimarySource ? 15 : 5,
			sourceFreshness: "static",
			sourceExpectedOutputType: "document",
			sourceUrl: url,
			sourceText: source.source,
			trustedSourceId: source.id,
			sourceLabel: source.label,
			checkpointKeys: [
				"trustedSource",
				"sourceUrl",
				"sourceOutput"
			]
		});
	}
	const hasPrimarySource = specs.some((spec) => spec.sourceRole === "primary");
	const asksForVerification = /\bverify\b|\bconfirm\b|\bcross.?check\b|\bdouble.?check\b|\bvalidate\b/.test(text);
	const asksForExplicitSearch = /\bsearch\b|\bfind\b|\bnews\b|\bheadlines?\b|\bweather\b/.test(text);
	if (!(specs.some((spec) => spec.id === "source-fetch-mining") && !asksForExternalSearch(text)) && /\bweb\b|\bsearch\b|\bsource\b|\bmarket\b|\bbtc\b|\bsol\b|\brisk\b|\bnews\b|\bheadline|\bprice\b|\bweather\b|\blive\b|\bavailability\b|\bexternal\b|\bremote\b/.test(text)) add({
		id: "source-fetch-web-search",
		label: "Live search",
		toolName: "web_search",
		description: "Search live external sources before model analysis.",
		sourceRole: hasPrimarySource ? asksForVerification ? "verification" : asksForExplicitSearch ? "primary" : "enrichment" : "primary",
		sourcePriority: hasPrimarySource ? asksForVerification ? 40 : asksForExplicitSearch ? 20 : 80 : 20,
		sourceFreshness: "live",
		sourceExpectedOutputType: "search-results",
		optional: hasPrimarySource && !asksForVerification && !asksForExplicitSearch,
		checkpointKeys: ["searchQuery", "sourceOutput"]
	});
	return specs;
}
function uniquePlannerSkills(values) {
	const out = [];
	const seen = /* @__PURE__ */ new Set();
	for (const value of values) {
		const normalized = normalizePlannerToolName(value);
		if (!normalized || seen.has(normalized)) continue;
		seen.add(normalized);
		out.push(normalized);
	}
	return out;
}
function cheapCheckToolScope(text, policy) {
	if (policy?.skillScope === "none") return {
		skillScope: "none",
		allowedSkills: policy.allowedSkills ? [...policy.allowedSkills] : void 0
	};
	if (policy?.allowedSkills?.length) return {
		skillScope: policy.skillScope ?? "selected",
		allowedSkills: uniquePlannerSkills(policy.allowedSkills)
	};
	if (policy?.skillScope === "selected") return {
		skillScope: policy.skillScope,
		allowedSkills: policy.allowedSkills ? [...policy.allowedSkills] : void 0
	};
	if (policy?.skillAction?.toolName) return {
		skillScope: "selected",
		allowedSkills: [normalizePlannerToolName(policy.skillAction.toolName)]
	};
	const inferredTools = uniquePlannerSkills(sourceFetchGraphSpecs(text, {
		...policy,
		skillScope: void 0,
		allowedSkills: void 0
	}).map((spec) => spec.toolName));
	if (inferredTools.length === 0) return { skillScope: "none" };
	return {
		skillScope: "selected",
		allowedSkills: inferredTools
	};
}
function cheapCheckMemoryScope(policy) {
	if (policy?.memoryScope === "pinned" || policy?.memoryScope === "search") return policy.memoryScope;
	return "none";
}
function needsToolPassNode(text, policy) {
	return Boolean(policy?.skillAction?.toolName) || hasAny(text, [
		/\btool\b/,
		/\bskill\b/,
		/\bservice\b/,
		/\bapi\b/,
		/\bwallet\b/,
		/\bmining\b/,
		/\bprovider\b/,
		/\bgateway\b/,
		/\boffers?\b/,
		/\bmarketplace\b/
	]);
}
function coordinationGraphNode(policy, dependsOn) {
	const mode = policy?.coordination?.mode;
	if (!mode || mode === "none") return;
	const agents = policy?.coordination?.agents?.filter((agent) => agent.trim());
	if (!agents || agents.length === 0) return;
	return {
		id: "coordinate-agents",
		label: mode === "parallel" ? "Coordinate Agents" : "Consult Agents",
		kind: "coordination",
		description: mode === "parallel" ? "Spawn approved local Agents beside the owner Agent and record task-room evidence." : "Consult approved local Agents and record their task-room evidence.",
		dependsOn,
		usesModel: true,
		retryable: true,
		checkpointKeys: [
			"coordinationEvidence",
			"taskRoomEvidence",
			"approval"
		]
	};
}
function cloneWorkflowGraph(graph) {
	return {
		...graph,
		terminalNodeIds: [...graph.terminalNodeIds],
		nodes: graph.nodes.map((node) => ({
			...node,
			dependsOn: node.dependsOn ? [...node.dependsOn] : void 0,
			checkpointKeys: node.checkpointKeys ? [...node.checkpointKeys] : void 0
		}))
	};
}
function inferWorkflowGraphKind(policy) {
	if (policy.executionMode === "no-model" || policy.modelPolicy?.mode === "none") return "no-model";
	if (policy.executionMode === "skill-only" || policy.skillAction) return "skill-only";
	return "model";
}
function strategyForWorkflowGraphKind(kind) {
	if (kind === "no-model") return "no-model";
	if (kind === "skill-only") return "skill-only";
	return "agent-default";
}
function ensureCoordinationNodeInGraph(graph, policy) {
	if (graph.nodes.some((node) => node.id === "coordinate-agents")) return graph;
	const nodes = graph.nodes.map((node) => ({ ...node }));
	const deliverIndex = nodes.findIndex((node) => node.kind === "deliver");
	const anchorNode = deliverIndex >= 0 ? nodes[deliverIndex] : nodes.find((node) => graph.terminalNodeIds.includes(node.id)) ?? nodes[nodes.length - 1];
	const coordination = coordinationGraphNode(policy, anchorNode?.dependsOn && anchorNode.dependsOn.length > 0 ? [...anchorNode.dependsOn] : anchorNode ? [anchorNode.id] : [graph.entryNodeId]);
	if (!coordination) return graph;
	if (deliverIndex >= 0) {
		nodes[deliverIndex] = {
			...nodes[deliverIndex],
			dependsOn: [coordination.id]
		};
		nodes.splice(deliverIndex, 0, coordination);
	} else nodes.push(coordination);
	return {
		...graph,
		nodes
	};
}
function withTaskCoordinationRequest(params) {
	const policy = clonePolicy(params.policy);
	const requestedAgents = Array.from(new Set(params.agents.map((agent) => agent.trim()).filter(Boolean)));
	const existingAgents = policy.coordination?.agents ?? [];
	const agents = Array.from(new Set([...existingAgents, ...requestedAgents]));
	const mode = params.mode ?? policy.coordination?.mode ?? "consult";
	policy.coordination = {
		...policy.coordination,
		mode,
		agents,
		requireApproval: params.requireApproval ?? policy.coordination?.requireApproval ?? true
	};
	const kind = inferWorkflowGraphKind(policy);
	const graph = policy.planner?.graph ? cloneWorkflowGraph(policy.planner.graph) : buildWorkflowGraph({
		kind,
		text: params.message,
		policy,
		skillAction: policy.skillAction
	});
	policy.planner = {
		source: "heuristic",
		strategy: policy.planner?.strategy ?? strategyForWorkflowGraphKind(kind),
		rationale: policy.planner?.rationale ?? "Manual Agent coordination request.",
		confidence: policy.planner?.confidence ?? "medium",
		signals: Array.from(new Set([...policy.planner?.signals ?? [], "manual-agent-request"])),
		steps: policy.planner?.steps ?? workflowSteps(kind),
		graph: ensureCoordinationNodeInGraph(graph, policy)
	};
	return policy;
}
function buildWorkflowGraph(params) {
	if (params.kind === "no-model") {
		const nodes = [{
			id: "prepare-message",
			label: "Prepare message",
			kind: "synthesize",
			description: "Use the stored task text directly without model or tool work.",
			retryable: true,
			checkpointKeys: ["outputText"]
		}];
		const coordination = coordinationGraphNode(params.policy, ["prepare-message"]);
		if (coordination) nodes.push(coordination);
		nodes.push({
			id: "deliver",
			label: "Deliver",
			kind: "deliver",
			description: "Send the prepared message to the selected delivery target.",
			dependsOn: [coordination?.id ?? "prepare-message"],
			retryable: true,
			checkpointKeys: ["deliveryTarget", "delivered"]
		});
		return {
			version: 1,
			entryNodeId: "prepare-message",
			terminalNodeIds: ["deliver"],
			nodes
		};
	}
	if (params.kind === "skill-only") {
		const nodes = [{
			id: "collect-data",
			label: "Collect data",
			kind: "collect",
			description: "Resolve session, delivery target, and deterministic tool input.",
			retryable: true,
			checkpointKeys: ["deliveryTarget", "toolInput"]
		}, {
			id: "tool-pass",
			label: params.skillAction?.toolName ? `${params.skillAction.toolName} pass` : "Tool pass",
			kind: "tool",
			description: params.skillAction?.toolName ? `Run the selected ${params.skillAction.toolName} tool without model inference.` : "Run the selected deterministic tool without model inference.",
			dependsOn: ["collect-data"],
			usesTool: true,
			retryable: true,
			checkpointKeys: [
				"toolName",
				"toolInput",
				"outputText"
			]
		}];
		const coordination = coordinationGraphNode(params.policy, ["tool-pass"]);
		if (coordination) nodes.push(coordination);
		nodes.push({
			id: "validation",
			label: "Validation",
			kind: "validation",
			description: "Validate the direct tool result before delivery.",
			dependsOn: [coordination?.id ?? "tool-pass"],
			retryable: true,
			checkpointKeys: ["resultStatus", "error"]
		}, {
			id: "deliver",
			label: "Deliver",
			kind: "deliver",
			description: "Deliver the validated direct tool result.",
			dependsOn: ["validation"],
			retryable: true,
			checkpointKeys: ["deliveryTarget", "delivered"]
		});
		return {
			version: 1,
			entryNodeId: "collect-data",
			terminalNodeIds: ["deliver"],
			nodes
		};
	}
	const nodes = [{
		id: "collect-data",
		label: "Collect data",
		kind: "collect",
		description: "Collect policy, memory scope, allowed skills, and routing context.",
		retryable: true,
		checkpointKeys: [
			"memoryScope",
			"skillScope",
			"deliveryTarget"
		]
	}];
	const sourceSpecs = sourceFetchGraphSpecs(params.text, params.policy);
	let contextNodeIds = ["collect-data"];
	for (const spec of sourceSpecs) nodes.push({
		id: spec.id,
		label: spec.label,
		kind: "tool",
		description: spec.description,
		dependsOn: ["collect-data"],
		optional: spec.optional,
		sourceRole: spec.sourceRole,
		sourcePriority: spec.sourcePriority,
		sourceFreshness: spec.sourceFreshness,
		sourceExpectedOutputType: spec.sourceExpectedOutputType,
		sourceUrl: spec.sourceUrl,
		sourceText: spec.sourceText,
		trustedSourceId: spec.trustedSourceId,
		sourceLabel: spec.sourceLabel,
		usesTool: true,
		retryable: true,
		checkpointKeys: spec.checkpointKeys
	});
	if (sourceSpecs.length > 0) {
		const sourceNodeIds = sourceSpecs.map((spec) => spec.id);
		nodes.push({
			id: "source-merge",
			label: "Source merge",
			kind: "synthesize",
			description: "Normalize source fetch outputs into a single source bundle.",
			dependsOn: sourceNodeIds,
			retryable: true,
			checkpointKeys: [
				"sourceBundle",
				"sourceStatus",
				"sourceOutput"
			]
		});
		contextNodeIds = ["source-merge"];
		if (sourceSpecs.some((spec) => spec.sourceRole === "verification")) {
			nodes.push({
				id: "source-verify",
				label: "Source verification",
				kind: "validation",
				description: "Compare primary and verification source outputs before analysis.",
				dependsOn: ["source-merge"],
				retryable: false,
				checkpointKeys: [
					"verificationStatus",
					"conflicts",
					"needsReview"
				]
			});
			contextNodeIds = ["source-verify"];
		}
	}
	if (needsToolPassNode(params.text, params.policy)) {
		nodes.push({
			id: "tool-pass",
			label: "Tool pass",
			kind: "tool",
			description: "Run approved deterministic tools to gather supporting facts before analysis.",
			dependsOn: contextNodeIds,
			usesTool: true,
			retryable: true,
			checkpointKeys: [
				"allowedSkills",
				"toolInput",
				"toolOutput"
			]
		});
		contextNodeIds = ["tool-pass"];
	}
	nodes.push({
		id: "model-analysis",
		label: "Model analysis",
		kind: "model",
		description: "Run the selected model-backed Agent turn against the collected context.",
		dependsOn: contextNodeIds,
		usesModel: true,
		usesTool: sourceSpecs.length > 0 || needsToolPassNode(params.text, params.policy),
		retryable: true,
		checkpointKeys: [
			"summary",
			"outputText",
			"model",
			"provider"
		]
	});
	const coordination = coordinationGraphNode(params.policy, ["model-analysis"]);
	if (coordination) nodes.push(coordination);
	nodes.push({
		id: "validation",
		label: "Validation",
		kind: "validation",
		description: "Apply evaluator, budget, stop, and escalation policy.",
		dependsOn: [coordination?.id ?? "model-analysis"],
		retryable: true,
		checkpointKeys: [
			"resultStatus",
			"evaluator",
			"planner"
		]
	}, {
		id: "synthesize",
		label: "Synthesize",
		kind: "synthesize",
		description: "Normalize the result checkpoint for run history and delivery replay.",
		dependsOn: ["validation"],
		retryable: true,
		checkpointKeys: [
			"summary",
			"outputText",
			"resultStatus"
		]
	}, {
		id: "deliver",
		label: "Deliver",
		kind: "deliver",
		description: "Deliver the synthesized result to the selected channel or session.",
		dependsOn: ["synthesize"],
		retryable: true,
		checkpointKeys: ["deliveryTarget", "delivered"]
	});
	return {
		version: 1,
		entryNodeId: "collect-data",
		terminalNodeIds: ["deliver"],
		nodes
	};
}
function uniqueStrings(values) {
	const unique = [...new Set(values.filter((entry) => Boolean(entry)))];
	return unique.length > 0 ? unique : void 0;
}
function repairSourceNode(repair) {
	const sourceExpectedOutputType = repair.toolName === "web_fetch" ? "document" : repair.toolName === "gateway" ? "provider-status" : repair.toolName === "wallet" ? "wallet-state" : repair.toolName === "mining" ? "mining-state" : repair.toolName === "offers" ? "offers-state" : "search-results";
	const label = repair.toolName === "web_fetch" ? "Repair URL fetch" : repair.toolName === "gateway" ? "Repair provider catalog" : repair.toolName === "wallet" ? "Repair wallet state" : repair.toolName === "mining" ? "Repair mining state" : repair.toolName === "offers" ? "Repair offers state" : "Repair live search";
	return {
		id: repair.nodeId,
		label,
		kind: "tool",
		description: `Dynamic source repair: ${repair.reason}`,
		dependsOn: ["collect-data"],
		optional: false,
		sourceRole: "verification",
		sourcePriority: 30,
		sourceFreshness: repair.toolName === "web_search" ? "live" : repair.toolName === "web_fetch" ? "static" : "runtime",
		sourceExpectedOutputType,
		usesTool: true,
		retryable: true,
		checkpointKeys: ["sourceRepair", "sourceOutput"]
	};
}
function redirectDependenciesToVerification(graph) {
	for (const node of graph.nodes) {
		if (node.id === "source-verify") continue;
		if (node.dependsOn?.includes("source-merge")) node.dependsOn = uniqueStrings(node.dependsOn.map((dependency) => dependency === "source-merge" ? "source-verify" : dependency));
	}
}
function replaceGraphDependency(graph, fromNodeId, toNodeId) {
	for (const node of graph.nodes) {
		if (!node.dependsOn?.includes(fromNodeId)) continue;
		node.dependsOn = uniqueStrings(node.dependsOn.map((dependency) => dependency === fromNodeId ? toNodeId : dependency));
	}
}
function removeGraphSourceNode(graph, nodeId) {
	if (!nodeId.startsWith("source-fetch-")) return false;
	const index = graph.nodes.findIndex((node) => node.id === nodeId);
	if (index < 0) return false;
	graph.nodes.splice(index, 1);
	return true;
}
function removeGraphDependency(graph, nodeId) {
	for (const node of graph.nodes) {
		if (!node.dependsOn?.includes(nodeId)) continue;
		node.dependsOn = uniqueStrings(node.dependsOn.filter((dependency) => dependency !== nodeId));
	}
}
function incrementGraphRepairRevision(graph) {
	const parentRevision = typeof graph.graphRevision === "number" && Number.isFinite(graph.graphRevision) ? Math.max(1, Math.floor(graph.graphRevision)) : 1;
	const repairRevision = typeof graph.repairRevision === "number" && Number.isFinite(graph.repairRevision) ? Math.max(0, Math.floor(graph.repairRevision)) + 1 : 1;
	const graphRevision = parentRevision + 1;
	graph.parentRevision = parentRevision;
	graph.repairRevision = repairRevision;
	graph.graphRevision = graphRevision;
	return {
		graphRevision,
		parentRevision,
		repairRevision
	};
}
function stopSourcePathInPolicy(policy, sourceNodeId) {
	const planner = policy?.planner;
	const graph = planner?.graph;
	if (!graph) return {
		applied: false,
		reason: "task has no workflow graph"
	};
	const nodeId = sourceNodeId.trim();
	if (!nodeId.startsWith("source-fetch-")) return {
		applied: false,
		reason: "source path must be a source-fetch graph node"
	};
	if (!graph.nodes.find((node) => node.id === nodeId)) return {
		applied: false,
		reason: `source path ${nodeId} is not present in the graph`
	};
	removeGraphDependency(graph, nodeId);
	if (!removeGraphSourceNode(graph, nodeId)) return {
		applied: false,
		reason: `source path ${nodeId} could not be removed`
	};
	planner.signals = uniqueStrings([...planner.signals ?? [], `graph-repair:source-stopped:${nodeId}`]);
	return {
		applied: true,
		...incrementGraphRepairRevision(graph),
		reason: `stopped source path ${nodeId}`
	};
}
function applySourceGraphRepairToPolicy(policy, repair) {
	const planner = policy?.planner;
	const graph = planner?.graph;
	if (!graph) return {
		applied: false,
		reason: "task has no workflow graph"
	};
	const sourceMerge = graph.nodes.find((node) => node.id === "source-merge");
	if (!sourceMerge) return {
		applied: false,
		reason: "task graph has no source merge node"
	};
	if (!graph.nodes.some((node) => node.id === repair.nodeId)) {
		const sourceMergeIndex = graph.nodes.findIndex((node) => node.id === "source-merge");
		graph.nodes.splice(Math.max(1, sourceMergeIndex), 0, repairSourceNode(repair));
	}
	let replaced = false;
	if (repair.action === "replace_source" && repair.replacesNodeId) {
		const replacingExistingNode = graph.nodes.some((node) => node.id === repair.replacesNodeId);
		replaceGraphDependency(graph, repair.replacesNodeId, repair.nodeId);
		if (!sourceMerge.dependsOn?.includes(repair.nodeId)) sourceMerge.dependsOn = uniqueStrings([...sourceMerge.dependsOn ?? [], repair.nodeId]);
		replaced = replacingExistingNode && removeGraphSourceNode(graph, repair.replacesNodeId);
	} else sourceMerge.dependsOn = uniqueStrings([...sourceMerge.dependsOn ?? [], repair.nodeId]);
	let sourceVerify = graph.nodes.find((node) => node.id === "source-verify");
	if (!sourceVerify) {
		const sourceMergeIndex = graph.nodes.findIndex((node) => node.id === "source-merge");
		sourceVerify = {
			id: "source-verify",
			label: "Source verification",
			kind: "validation",
			description: "Compare primary, verification, and repaired source outputs before analysis.",
			dependsOn: ["source-merge"],
			retryable: false,
			checkpointKeys: [
				"verificationStatus",
				"conflicts",
				"needsReview"
			]
		};
		graph.nodes.splice(sourceMergeIndex + 1, 0, sourceVerify);
		redirectDependenciesToVerification(graph);
	} else sourceVerify.dependsOn = uniqueStrings([...sourceVerify.dependsOn ?? [], "source-merge"]);
	planner.signals = uniqueStrings([...planner.signals ?? [], "graph-repair:source-quality"]);
	const { graphRevision, parentRevision, repairRevision } = incrementGraphRepairRevision(graph);
	if (repair.action === "replace_source" && repair.replacesNodeId) return {
		applied: true,
		graphRevision,
		parentRevision,
		repairRevision,
		reason: replaced ? `replaced ${repair.replacesNodeId} with ${repair.nodeId}` : `added ${repair.nodeId}; source ${repair.replacesNodeId} was not present`
	};
	return {
		applied: true,
		graphRevision,
		parentRevision,
		repairRevision,
		reason: `added ${repair.nodeId}`
	};
}
function canPlan(policy) {
	const alreadyPlanned = policy?.planner?.source === "heuristic";
	const mode = policy?.executionMode;
	if (!alreadyPlanned && mode && mode !== "auto") return false;
	if (!alreadyPlanned && policy?.skillAction) return false;
	const modelMode = policy?.modelPolicy?.mode;
	if (!alreadyPlanned && modelMode && modelMode !== "auto" && modelMode !== "agent-default") return false;
	if (!alreadyPlanned && policy?.modelPolicy?.model?.trim()) return false;
	return true;
}
function isDirectReminder(text) {
	const reminder = hasAny(text, [
		/\bremind me\b/,
		/\breminder\b/,
		/\bping me\b/,
		/\bnotify me\b/,
		/\bsend (?:me |this )?(?:a )?(?:message|note|reminder)\b/
	]);
	const needsWork = hasAny(text, [
		/\bresearch\b/,
		/\banaly[sz]e\b/,
		/\bsummar[yi][sz]e\b/,
		/\bcompare\b/,
		/\bwrite\b/,
		/\bdraft\b/,
		/\bcheck\b/,
		/\bmonitor\b/,
		/\bstatus\b/,
		/\bsearch\b/,
		/\bfind\b/
	]);
	return reminder && !needsWork;
}
function walletAction(text) {
	if (!/(?:^|\s)@?wallet\b/.test(text)) return;
	const asksToSendResult = /\bsend (?:it|this|that|the result|the update|the report|me|back)\b/.test(text);
	if (/\b(?:transfer|swap|prepare|pay|buy|sell)\b/.test(text) || /\bsend\b/.test(text) && !asksToSendResult) return;
	return {
		toolName: "wallet",
		input: { action: /\bassets?\b/.test(text) ? "assets" : /\baddress\b/.test(text) ? "address" : /\blist\b/.test(text) ? "list" : /\ball\b/.test(text) && /\bbalances?\b/.test(text) ? "balances" : /\bbalances?\b/.test(text) ? "balance" : "status" }
	};
}
function miningAction(text) {
	if (!/(?:^|\s)@?mining\b|\bsat mining\b|\bminers?\b/.test(text)) return;
	if (/\b(?:start|stop|claim|withdraw|deposit|fund|commit|set|update|clear|resolve|finalize|submit)\b/.test(text)) return;
	return {
		toolName: "mining",
		input: { action: /\breadiness\b/.test(text) ? "readiness" : /\bhistory\b/.test(text) ? "history" : /\bprofile\b/.test(text) ? "profile" : "status" }
	};
}
function providerHealthAction(text) {
	if (!hasAny(text, [
		/\bproviders?\b/,
		/\bmodel auth\b/,
		/\bmodel catalog\b/,
		/\bauth status\b/,
		/\bcatalog status\b/,
		/\bgateway health\b/
	])) return;
	if (/\b(?:restart|patch|apply|configure|update|delete|clear|rotate)\b/.test(text)) return;
	return {
		toolName: "gateway",
		input: { action: /\bcatalog\b|\bmodels?\b/.test(text) && !/\bauth|credential|sign.?in\b/.test(text) ? "models.catalog.status" : "models.auth.status" }
	};
}
function offersAction(text) {
	if (!/(?:^|\s)@?offers?\b|\bmarketplace\b/.test(text)) return;
	if (/\b(?:create|draft|publish|buy|pay|enable|delete|cancel)\b/.test(text)) return;
	const action = /\borders?\b/.test(text) ? "orders" : /\bpaid\b|\binvoices?\b|\breceipts?\b/.test(text) ? "paid_invoices" : /\brequests?\b/.test(text) ? "local_requests" : /\blocal\b/.test(text) ? "local_offers" : "search";
	return {
		toolName: "offers",
		input: action === "search" ? {
			action,
			query: text.slice(0, 240)
		} : { action }
	};
}
function chooseSkillAction(text) {
	return walletAction(text) ?? miningAction(text) ?? providerHealthAction(text) ?? offersAction(text);
}
function isStrongReasoningTask(text) {
	return hasAny(text, [
		/\bdeep\b/,
		/\bresearch\b/,
		/\banaly[sz]e\b/,
		/\bcompare\b/,
		/\bstrategy\b/,
		/\barchitecture\b/,
		/\bdebug\b/,
		/\broot cause\b/,
		/\bsecurity\b/,
		/\bdesign\b/,
		/\bdecide\b/,
		/\bplan\b/,
		/\bimplement\b/,
		/\bcode\b/,
		/\bwrite\b/,
		/\bdraft\b/
	]);
}
function isCheapModelTask(text) {
	return hasAny(text, [
		/\bcheck\b/,
		/\bmonitor\b/,
		/\bwatch\b/,
		/\bstatus\b/,
		/\bfetch\b/,
		/\bheadline/,
		/\bprice\b/,
		/\bavailability\b/,
		/\bquick\b/,
		/\bsimple\b/
	]);
}
function isNaturalCheapEscalationTask(text) {
	return hasAny(text, [
		/\bcheap(?:er)? (?:check|model|pass|run) first\b/,
		/\bquick (?:check|pass|scan) first\b/,
		/\blightweight (?:check|pass|scan) first\b/,
		/\bstart (?:cheap|small|light|quick)\b/,
		/\b(?:escalate|follow up|deep(?:er)? dive|strong(?:er)? model) if (?:needed|necessary|anything changes)\b/,
		/\b(?:escalate|follow up) only (?:if|when)\b/
	]) || hasAny(text, [
		/\bcheap(?:er)?\b/,
		/\bquick\b/,
		/\blightweight\b/
	]) && hasAny(text, [
		/\bescalat/,
		/\bstrong(?:er)?\b/,
		/\bdeep(?:er)?\b/,
		/\bfollow up\b/
	]);
}
function planTaskExecutionPolicy(input) {
	const policy = clonePolicy(input.policy);
	const trustedSources = mergeTrustedSources(policy.trustedSources, input.trustedSources);
	if (trustedSources) policy.trustedSources = trustedSources;
	if (!canPlan(policy)) return policy;
	const text = normalizeText(input);
	if (policy.planner?.strategy === "cheap-model" && policy.planner.signals?.includes("manual-evaluator")) {
		const toolScope = cheapCheckToolScope(text, policy);
		const plannedPolicy = {
			...policy,
			executionMode: "agent-turn",
			memoryScope: cheapCheckMemoryScope(policy),
			skillScope: toolScope.skillScope,
			allowedSkills: toolScope.allowedSkills,
			modelPolicy: {
				...policy.modelPolicy,
				mode: policy.modelPolicy?.model?.trim() ? "task-override" : "auto"
			},
			evaluator: {
				...policy.evaluator,
				escalateOnSignal: policy.evaluator?.escalateOnSignal !== false,
				signalIncludes: policy.evaluator?.signalIncludes ?? DEFAULT_ESCALATION_SIGNAL_INCLUDES,
				maxEscalations: policy.evaluator?.maxEscalations ?? 1
			}
		};
		return planned(plannedPolicy, {
			...policy.planner,
			steps: policy.planner.steps ?? workflowSteps("model"),
			graph: policy.planner.graph ?? buildWorkflowGraph({
				kind: "model",
				text,
				policy: plannedPolicy
			})
		});
	}
	if (isDirectReminder(text)) return planned({
		...policy,
		executionMode: "no-model",
		memoryScope: "none",
		skillScope: "none",
		modelPolicy: { mode: "none" },
		evaluator: void 0
	}, decision({
		strategy: "no-model",
		rationale: "Direct reminder/delivery text can run without invoking a model.",
		confidence: "high",
		signals: ["reminder"],
		steps: workflowSteps("no-model"),
		graph: buildWorkflowGraph({
			kind: "no-model",
			text,
			policy
		})
	}));
	if (isMiningStrategyTask(text)) {
		const plannedPolicy = {
			...policy,
			executionMode: "agent-turn",
			memoryScope: policy.memoryScope ?? "none",
			skillScope: "selected",
			allowedSkills: ["mining"],
			modelPolicy: {
				...policy.modelPolicy,
				mode: "auto"
			},
			evaluator: void 0
		};
		return planned(plannedPolicy, decision({
			strategy: "strong-model",
			rationale: "SAT mining strategy tasks should use local mining state and the mining tool, without unrelated web search or broad memory.",
			confidence: "high",
			signals: ["mining-strategy"],
			steps: workflowSteps("model"),
			graph: buildWorkflowGraph({
				kind: "model",
				text,
				policy: plannedPolicy
			})
		}));
	}
	const skillAction = chooseSkillAction(text);
	if (skillAction) return planned({
		...policy,
		executionMode: "skill-only",
		memoryScope: "none",
		skillScope: "selected",
		allowedSkills: [skillAction.toolName],
		skillAction,
		modelPolicy: { mode: "none" },
		evaluator: void 0
	}, decision({
		strategy: "skill-only",
		rationale: `Read-only ${skillAction.toolName} status can run through a deterministic tool call.`,
		confidence: "high",
		signals: [skillAction.toolName],
		steps: workflowSteps("skill-only"),
		graph: buildWorkflowGraph({
			kind: "skill-only",
			text,
			policy,
			skillAction
		})
	}));
	if (isNaturalCheapEscalationTask(text)) {
		const toolScope = cheapCheckToolScope(text, policy);
		const plannedPolicy = {
			...policy,
			executionMode: "agent-turn",
			memoryScope: cheapCheckMemoryScope(policy),
			skillScope: toolScope.skillScope,
			allowedSkills: toolScope.allowedSkills,
			modelPolicy: {
				...policy.modelPolicy,
				mode: "auto"
			},
			evaluator: {
				...policy.evaluator,
				escalateOnSignal: true,
				signalIncludes: policy.evaluator?.signalIncludes ?? DEFAULT_ESCALATION_SIGNAL_INCLUDES,
				maxEscalations: policy.evaluator?.maxEscalations ?? 1
			}
		};
		return planned(plannedPolicy, decision({
			strategy: "cheap-model",
			rationale: "Task asks for a lightweight first pass with escalation only when needed.",
			confidence: "high",
			signals: ["natural-escalation"],
			steps: workflowSteps("model"),
			graph: buildWorkflowGraph({
				kind: "model",
				text,
				policy: plannedPolicy
			})
		}));
	}
	if (isStrongReasoningTask(text)) return planned({
		...policy,
		executionMode: "agent-turn",
		memoryScope: policy.memoryScope ?? "search",
		skillScope: policy.skillScope ?? "agent-default",
		modelPolicy: {
			...policy.modelPolicy,
			mode: "auto"
		},
		evaluator: void 0
	}, decision({
		strategy: "strong-model",
		rationale: "Task asks for research, analysis, planning, coding, or synthesis.",
		confidence: "medium",
		signals: ["reasoning"],
		steps: workflowSteps("model"),
		graph: buildWorkflowGraph({
			kind: "model",
			text,
			policy
		})
	}));
	if (isCheapModelTask(text)) {
		const toolScope = cheapCheckToolScope(text, policy);
		const plannedPolicy = {
			...policy,
			executionMode: "agent-turn",
			memoryScope: cheapCheckMemoryScope(policy),
			skillScope: toolScope.skillScope,
			allowedSkills: toolScope.allowedSkills,
			modelPolicy: {
				...policy.modelPolicy,
				mode: "auto"
			},
			evaluator: {
				...policy.evaluator,
				escalateOnSignal: true,
				signalIncludes: policy.evaluator?.signalIncludes ?? DEFAULT_ESCALATION_SIGNAL_INCLUDES,
				maxEscalations: policy.evaluator?.maxEscalations ?? 1
			}
		};
		return planned(plannedPolicy, decision({
			strategy: "cheap-model",
			rationale: "Task looks like a lightweight check or monitor loop.",
			confidence: "medium",
			signals: ["monitor"],
			steps: workflowSteps("model"),
			graph: buildWorkflowGraph({
				kind: "model",
				text,
				policy: plannedPolicy
			})
		}));
	}
	return planned({
		...policy,
		executionMode: "agent-turn",
		memoryScope: policy.memoryScope ?? "session-summary",
		skillScope: policy.skillScope ?? "agent-default",
		modelPolicy: {
			...policy.modelPolicy,
			mode: "agent-default"
		},
		evaluator: void 0
	}, decision({
		strategy: "agent-default",
		rationale: "No deterministic shortcut matched; use the Agent default model and tools.",
		confidence: "low",
		signals: ["default"],
		steps: workflowSteps("model"),
		graph: buildWorkflowGraph({
			kind: "model",
			text,
			policy
		})
	}));
}

//#endregion
export { formatDurationSeconds as C, parseAbsoluteTimeMs as D, resolveDefaultCronStaggerMs as E, formatDurationPrecise as S, resolveCronStaggerMs as T, formatCronGraphRepairLines as _, withTaskCoordinationRequest as a, formatDurationCompact as b, matchingTrustedSourcesForTask as c, removeTrustedSource as d, setTrustedSourceActive as f, formatCronEscalationPasses as g, formatCronEscalationContext as h, stopSourcePathInPolicy as i, mergeTrustedSources as l, cronGraphRepairsForRun as m, planTaskExecutionPolicy as n, createTrustedSourceForJob as o, upsertTrustedSource as p, sourceRepairNodeIdForTool as r, listTrustedSources as s, applySourceGraphRepairToPolicy as t, recordTrustedSourceOutcome as u, formatCronRunLoadedSkills as v, normalizeCronStaggerMs as w, formatDurationHuman as x, formatCronTaskRunDetail as y };