"use client";
import { adaptWorkflowGraphToUi, formatDurationMs } from '../../chunk-UQXVCVAN.mjs';
import { WorkflowWorkspace } from '../../chunk-O6M3KDGT.mjs';
export { RolesPageView, UsersPageView } from '../../chunk-O6M3KDGT.mjs';
import { DatasourceModal, findCategory, DIALECT_CATEGORIES } from '../../chunk-5RM6NGZ6.mjs';
export { DIALECT_CATEGORIES, DatasourceFormModal, DatasourceModal, findCategory, findDialect } from '../../chunk-5RM6NGZ6.mjs';
import { defaultRuleForm, RuleForm, ExecutionTimelinePanel } from '../../chunk-2WXRRQM3.mjs';
import '../../chunk-JB6RNAD2.mjs';
import '../../chunk-LEXBTVGM.mjs';
import '../../chunk-PCYL4MII.mjs';
import { HeroSection, PageLoadingState, PageEmptyState, EntityCard, Badge, ManagementPageLayout, CreateActionButton, Button, GlassModal, FormGrid, FormSelect, FormInput, FormTextarea, SectionHeader, Text, Form, FormActionsRow, Table, TableHead, TableRow, TableHeader, TableBody, TableCell, InlineForm, CopyableId } from '../../chunk-JN6IL6OH.mjs';
import '../../chunk-D2JF6C3E.mjs';
import '../../chunk-7VJ7CMMT.mjs';
import { useLink } from '../../chunk-QWG2FMUN.mjs';
import '../../chunk-ZV5EZXXO.mjs';
import '../../chunk-SYNVNTLJ.mjs';
import '../../chunk-OZNTQROP.mjs';
import '../../chunk-G7JQ4OCE.mjs';
import { CubeTransparentIcon, CpuChipIcon, ChatBubbleLeftEllipsisIcon, WrenchScrewdriverIcon, AdjustmentsHorizontalIcon, CircleStackIcon, RectangleStackIcon, ClockIcon, LinkIcon, KeyIcon, ArrowPathIcon, TrashIcon } from '@heroicons/react/24/outline';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useState, useMemo, useEffect } from 'react';

function AgentsModelsPageView({ labels, models, loading }) {
  const hero = /* @__PURE__ */ jsx(
    HeroSection,
    {
      icon: /* @__PURE__ */ jsx(CubeTransparentIcon, { className: "h-5 w-5" }),
      label: labels.title,
      title: labels.title,
      subtitle: labels.subtitle,
      gradient: "from-emerald-500 to-teal-700"
    }
  );
  const content = loading ? /* @__PURE__ */ jsx(PageLoadingState, {}) : models.length === 0 ? /* @__PURE__ */ jsx(PageEmptyState, { title: labels.empty, message: labels.subtitle, iconName: "folder-open" }) : /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3", children: models.map((model) => /* @__PURE__ */ jsx(
    EntityCard,
    {
      accentGradient: "from-emerald-500 to-teal-700",
      icon: /* @__PURE__ */ jsx("div", { className: "flex h-11 w-11 items-center justify-center rounded-lg bg-emerald-500/10 text-emerald-600 dark:bg-emerald-500/20 dark:text-emerald-400", children: /* @__PURE__ */ jsx(CubeTransparentIcon, { className: "h-6 w-6" }) }),
      title: model.name,
      subtitle: `${labels.provider}: ${model.provider}`,
      status: /* @__PURE__ */ jsx(Badge, { color: model.enabled ? "emerald" : "zinc", children: model.enabled ? labels.enabled : labels.disabled })
    },
    model.id
  )) });
  return /* @__PURE__ */ jsx(ManagementPageLayout, { hero, content });
}
function AgentsConfigPageView({ labels, agents, models, loading, onCreate, onUpdate, onDelete }) {
  const [editing, setEditing] = useState(null);
  const [createOpen, setCreateOpen] = useState(false);
  const modelOptions = models.map((model) => ({ value: model.id, label: `${model.name} (${model.provider})` }));
  const hero = /* @__PURE__ */ jsx(
    HeroSection,
    {
      icon: /* @__PURE__ */ jsx(CpuChipIcon, { className: "h-5 w-5" }),
      label: labels.title,
      title: labels.title,
      subtitle: labels.subtitle,
      gradient: "from-violet-500 to-indigo-700",
      toolbar: /* @__PURE__ */ jsx(
        CreateActionButton,
        {
          mode: "desktop",
          label: labels.addAgent,
          onClick: () => setCreateOpen(true),
          accent: "violet"
        }
      )
    }
  );
  const mobileAction = /* @__PURE__ */ jsx(
    CreateActionButton,
    {
      mode: "mobile",
      label: labels.addAgent,
      onClick: () => setCreateOpen(true),
      accent: "violet"
    }
  );
  const content = loading ? /* @__PURE__ */ jsx(PageLoadingState, {}) : agents.length === 0 ? /* @__PURE__ */ jsx(PageEmptyState, { title: labels.empty, message: labels.subtitle, iconName: "folder-open" }) : /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3", children: agents.map((agent) => {
    const modelRecord = models.find((model) => model.id === String(agent.modelId ?? ""));
    return /* @__PURE__ */ jsx(
      EntityCard,
      {
        accentGradient: "from-violet-500 to-indigo-700",
        icon: /* @__PURE__ */ jsx("div", { className: "flex h-11 w-11 items-center justify-center rounded-lg bg-violet-500/10 text-violet-600 dark:bg-violet-500/20 dark:text-violet-400", children: /* @__PURE__ */ jsx(CpuChipIcon, { className: "h-6 w-6" }) }),
        title: String(agent.name ?? ""),
        subtitle: String(modelRecord?.name ?? agent.modelId ?? ""),
        status: agent.activePromptVersion > 0 ? /* @__PURE__ */ jsxs(Badge, { color: "emerald", children: [
          "v",
          agent.activePromptVersion
        ] }) : null,
        footer: /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", outline: true, onClick: () => setEditing(agent), children: labels.edit }),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              size: "sm",
              color: "rose",
              onClick: () => {
                if (window.confirm(labels.deleteConfirm)) onDelete(agent);
              },
              children: labels.delete
            }
          )
        ] }),
        children: /* @__PURE__ */ jsxs("p", { className: "text-xs text-slate-500 dark:text-slate-400", children: [
          labels.activeVersion,
          ": ",
          agent.activePromptVersion,
          " \xB7 Prompts: ",
          agent.promptCount
        ] })
      },
      String(agent.agentId ?? agent.id ?? agent.name)
    );
  }) });
  const renderForm = (initial, onSubmit) => /* @__PURE__ */ jsx(
    GlassModal,
    {
      open: true,
      onClose: () => {
        setEditing(null);
        setCreateOpen(false);
      },
      title: initial.title,
      maxWidth: "lg",
      showFormFooter: true,
      submitLabel: labels.save,
      onSubmit: (event) => {
        const form = new FormData(event.currentTarget);
        onSubmit({
          agentId: initial.agentId,
          name: String(form.get("name") ?? "").trim(),
          modelId: String(form.get("modelId") ?? ""),
          systemPrompt: String(form.get("systemPrompt") ?? "").trim(),
          maxTokens: Number(form.get("maxTokens") ?? 2048),
          temperature: Number(form.get("temperature") ?? 0.2),
          outputSchema: String(form.get("outputSchema") ?? "").trim() || void 0
        });
      },
      children: /* @__PURE__ */ jsxs(FormGrid, { children: [
        /* @__PURE__ */ jsx(FormInput, { name: "name", label: labels.name, defaultValue: initial.name ?? "", required: true }),
        /* @__PURE__ */ jsx(FormSelect, { name: "modelId", label: labels.model, options: modelOptions, defaultValue: initial.modelId ?? modelOptions[0]?.value ?? "", required: true }),
        /* @__PURE__ */ jsx(FormInput, { name: "maxTokens", label: String(labels.maxTokens), type: "number", defaultValue: String(initial.maxTokens ?? 2048) }),
        /* @__PURE__ */ jsx(FormInput, { name: "temperature", label: labels.temperature, type: "number", step: 0.1, min: 0, max: 2, defaultValue: String(initial.temperature ?? 0.2) }),
        /* @__PURE__ */ jsx(FormTextarea, { name: "systemPrompt", label: labels.systemPrompt, defaultValue: initial.systemPrompt ?? "", rows: 4 }),
        /* @__PURE__ */ jsx(FormTextarea, { name: "outputSchema", label: labels.outputSchema, placeholder: labels.outputSchemaPlaceholder, defaultValue: initial.outputSchema ?? "", rows: 4 })
      ] })
    }
  );
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(ManagementPageLayout, { hero, content, mobileAction }),
    createOpen && renderForm({ title: labels.createTitle }, (input) => {
      onCreate(input);
      setCreateOpen(false);
    }),
    editing && renderForm(
      {
        title: labels.editTitle,
        agentId: String(editing.agentId ?? editing.id ?? ""),
        name: String(editing.name ?? ""),
        modelId: String(editing.modelId ?? ""),
        systemPrompt: String(editing.systemPrompt ?? ""),
        maxTokens: Number(editing.maxTokens ?? 2048),
        temperature: Number(editing.temperature ?? 0.2),
        outputSchema: String(editing.outputSchema ?? "")
      },
      (input) => {
        onUpdate(String(editing.agentId ?? editing.id ?? ""), input);
        setEditing(null);
      }
    )
  ] });
}
var LOCALE_OPTIONS = [
  { value: "en", label: "English" },
  { value: "pt-BR", label: "Portugu\xEAs (Brasil)" },
  { value: "es", label: "Espa\xF1ol" },
  { value: "fr", label: "Fran\xE7ais" },
  { value: "de", label: "Deutsch" },
  { value: "it", label: "Italiano" }
];
function AgentsPromptsPageView({ labels, agents, prompts, loading, onCreate, onActivate, onDelete }) {
  const [createOpen, setCreateOpen] = useState(false);
  const agentOptions = useMemo(
    () => agents.map((agent) => ({
      value: String(agent.agentId ?? agent.id ?? ""),
      label: String(agent.name ?? agent.agentId ?? agent.id ?? "")
    })),
    [agents]
  );
  const agentNameById = useMemo(() => {
    const map = /* @__PURE__ */ new Map();
    for (const agent of agents) {
      const id = String(agent.agentId ?? agent.id ?? "");
      if (id) map.set(id, String(agent.name ?? id));
    }
    return map;
  }, [agents]);
  const hero = /* @__PURE__ */ jsx(
    HeroSection,
    {
      icon: /* @__PURE__ */ jsx(ChatBubbleLeftEllipsisIcon, { className: "h-5 w-5" }),
      label: labels.title,
      title: labels.title,
      subtitle: labels.subtitle,
      gradient: "from-sky-500 to-blue-700",
      toolbar: /* @__PURE__ */ jsx(
        CreateActionButton,
        {
          mode: "desktop",
          label: labels.addPrompt,
          onClick: () => setCreateOpen(true),
          accent: "sky"
        }
      )
    }
  );
  const mobileAction = /* @__PURE__ */ jsx(
    CreateActionButton,
    {
      mode: "mobile",
      label: labels.addPrompt,
      onClick: () => setCreateOpen(true),
      accent: "sky"
    }
  );
  const content = loading ? /* @__PURE__ */ jsx(PageLoadingState, {}) : prompts.length === 0 ? /* @__PURE__ */ jsx(PageEmptyState, { title: labels.empty, message: labels.subtitle, iconName: "folder-open" }) : /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3", children: prompts.map((prompt) => {
    const agentName = agentNameById.get(prompt.agentId) ?? prompt.agentId;
    const key = `${prompt.agentId}:${prompt.locale}:${prompt.version}`;
    return /* @__PURE__ */ jsx(
      EntityCard,
      {
        accentGradient: "from-sky-500 to-blue-700",
        icon: /* @__PURE__ */ jsx("div", { className: "flex h-11 w-11 items-center justify-center rounded-lg bg-sky-500/10 text-sky-600 dark:bg-sky-500/20 dark:text-sky-400", children: /* @__PURE__ */ jsx(ChatBubbleLeftEllipsisIcon, { className: "h-6 w-6" }) }),
        title: agentName,
        subtitle: `${prompt.locale} \xB7 v${prompt.version}`,
        status: prompt.isActive ? /* @__PURE__ */ jsx(Badge, { color: "emerald", children: labels.isActive }) : null,
        footer: /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
          !prompt.isActive && /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", outline: true, onClick: () => onActivate(prompt), children: labels.activate }),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              size: "sm",
              color: "rose",
              onClick: () => {
                if (window.confirm(labels.deleteConfirm)) onDelete(prompt);
              },
              children: labels.delete
            }
          )
        ] }),
        children: prompt.prompt && /* @__PURE__ */ jsx("p", { className: "mt-1 line-clamp-3 text-xs text-slate-500 dark:text-slate-400", children: prompt.prompt })
      },
      key
    );
  }) });
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(ManagementPageLayout, { hero, content, mobileAction }),
    /* @__PURE__ */ jsx(
      GlassModal,
      {
        open: createOpen,
        onClose: () => setCreateOpen(false),
        title: labels.createTitle,
        maxWidth: "2xl",
        showFormFooter: true,
        submitLabel: labels.save,
        onSubmit: (event) => {
          const form = new FormData(event.currentTarget);
          const systemPrompt = String(form.get("systemPrompt") ?? "").trim();
          const userTemplate = String(form.get("userTemplate") ?? "").trim();
          const reason = String(form.get("reason") ?? "").trim();
          onCreate({
            agentId: String(form.get("agentId") ?? "").trim(),
            locale: String(form.get("locale") ?? "en").trim(),
            prompt: String(form.get("prompt") ?? "").trim(),
            systemPrompt: systemPrompt || void 0,
            userTemplate: userTemplate || void 0,
            reason: reason || void 0,
            isActive: String(form.get("isActive") ?? "true") === "true"
          });
          setCreateOpen(false);
        },
        children: /* @__PURE__ */ jsxs(FormGrid, { children: [
          /* @__PURE__ */ jsx(FormSelect, { name: "agentId", label: labels.agent, options: agentOptions, required: true }),
          /* @__PURE__ */ jsx(FormSelect, { name: "locale", label: labels.locale, options: LOCALE_OPTIONS, defaultValue: "en" }),
          /* @__PURE__ */ jsx(
            FormSelect,
            {
              name: "isActive",
              label: labels.isActive,
              options: [{ value: "true", label: labels.isActive }, { value: "false", label: labels.isActive }],
              defaultValue: "true"
            }
          ),
          /* @__PURE__ */ jsx(FormInput, { name: "reason", label: labels.reason }),
          /* @__PURE__ */ jsx(FormTextarea, { name: "systemPrompt", label: labels.systemPrompt, rows: 3 }),
          /* @__PURE__ */ jsx(FormTextarea, { name: "userTemplate", label: labels.userTemplate, rows: 3 }),
          /* @__PURE__ */ jsx(FormTextarea, { name: "prompt", label: labels.prompt, rows: 6, required: true })
        ] })
      }
    )
  ] });
}
var TOOL_TYPES = [
  "http",
  "function",
  "database_query",
  "code_execution",
  "api_call"
];
var TOOL_TYPE_OPTIONS = [
  { value: "http", label: "HTTP", description: "Call an HTTP endpoint with templated URL/body." },
  { value: "function", label: "Function", description: "Invoke a pre-registered server-side implementation." },
  { value: "database_query", label: "Database query", description: "Run a parameterized SELECT against a datasource." },
  { value: "code_execution", label: "Code execution", description: "Run sandboxed code (JS/Python) \u2014 experimental." },
  { value: "api_call", label: "API call", description: "Call a third-party API via stored credentials." }
];
var PARAMETER_TYPE_OPTIONS = [
  { value: "string", label: "string" },
  { value: "number", label: "number" },
  { value: "boolean", label: "boolean" },
  { value: "array", label: "array" },
  { value: "object", label: "object" }
];
function AgentsToolDefinitionsPageView({ labels, tools, loading, onCreate, onUpdate, onDelete }) {
  const [editing, setEditing] = useState(null);
  const [createOpen, setCreateOpen] = useState(false);
  const hero = /* @__PURE__ */ jsx(
    HeroSection,
    {
      icon: /* @__PURE__ */ jsx(WrenchScrewdriverIcon, { className: "h-5 w-5" }),
      label: labels.title,
      title: labels.title,
      subtitle: labels.subtitle,
      gradient: "from-amber-500 to-orange-700",
      toolbar: /* @__PURE__ */ jsx(
        CreateActionButton,
        {
          mode: "desktop",
          label: labels.addTool,
          onClick: () => setCreateOpen(true),
          accent: "amber"
        }
      )
    }
  );
  const mobileAction = /* @__PURE__ */ jsx(
    CreateActionButton,
    {
      mode: "mobile",
      label: labels.addTool,
      onClick: () => setCreateOpen(true),
      accent: "amber"
    }
  );
  const content = loading ? /* @__PURE__ */ jsx(PageLoadingState, {}) : tools.length === 0 ? /* @__PURE__ */ jsx(PageEmptyState, { title: labels.empty, message: labels.subtitle, iconName: "folder-open" }) : /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3", children: tools.map((tool) => /* @__PURE__ */ jsx(
    EntityCard,
    {
      accentGradient: "from-amber-500 to-orange-700",
      icon: /* @__PURE__ */ jsx("div", { className: "flex h-11 w-11 items-center justify-center rounded-lg bg-amber-500/10 text-amber-600 dark:bg-amber-500/20 dark:text-amber-400", children: /* @__PURE__ */ jsx(WrenchScrewdriverIcon, { className: "h-6 w-6" }) }),
      title: tool.name,
      subtitle: toolTypeLabel(tool),
      status: /* @__PURE__ */ jsx(Badge, { color: tool.enabled ? "emerald" : "zinc", children: tool.enabled ? labels.enabled : labels.disabled }),
      footer: /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", outline: true, onClick: () => setEditing(tool), children: labels.edit }),
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            size: "sm",
            color: "rose",
            onClick: () => {
              if (window.confirm(labels.deleteConfirm)) onDelete(tool);
            },
            children: labels.delete
          }
        )
      ] }),
      children: tool.description && /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-slate-500 dark:text-slate-400", children: tool.description })
    },
    tool.agentToolId
  )) });
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(ManagementPageLayout, { hero, content, mobileAction }),
    createOpen && /* @__PURE__ */ jsx(
      ToolEditor,
      {
        title: labels.createTitle,
        saveLabel: labels.save,
        initial: defaultForm(),
        onClose: () => setCreateOpen(false),
        onSubmit: (input) => {
          onCreate(input);
          setCreateOpen(false);
        }
      }
    ),
    editing && /* @__PURE__ */ jsx(
      ToolEditor,
      {
        title: labels.editTitle,
        saveLabel: labels.save,
        initial: toolToForm(editing),
        onClose: () => setEditing(null),
        onSubmit: (input) => {
          onUpdate(editing.agentToolId, input);
          setEditing(null);
        }
      }
    )
  ] });
}
function ToolEditor({
  title,
  saveLabel,
  initial,
  onSubmit,
  onClose
}) {
  const [value, setValue] = useState(initial);
  const [error, setError] = useState(null);
  const handleSubmit = () => {
    if (!value.name.trim()) {
      setError("Name is required");
      return;
    }
    const names = value.parameters.map((p) => p.name.trim());
    if (names.some((n) => n.length === 0)) {
      setError("Every parameter must have a name");
      return;
    }
    if (new Set(names).size !== names.length) {
      setError("Parameter names must be unique");
      return;
    }
    onSubmit(value);
  };
  const update = (key, next) => {
    setValue((v) => ({ ...v, [key]: next }));
  };
  return /* @__PURE__ */ jsx(
    GlassModal,
    {
      open: true,
      onClose,
      title,
      maxWidth: "3xl",
      showFormFooter: true,
      submitLabel: saveLabel,
      onSubmit: (event) => {
        event.preventDefault();
        handleSubmit();
      },
      children: /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
        /* @__PURE__ */ jsxs(FormGrid, { children: [
          /* @__PURE__ */ jsx(
            FormInput,
            {
              label: "Name",
              required: true,
              value: value.name,
              onValueChange: (name) => update("name", name),
              placeholder: "get_station_prices"
            }
          ),
          /* @__PURE__ */ jsx(
            FormSelect,
            {
              label: "Tool type",
              value: value.toolType,
              options: TOOL_TYPE_OPTIONS.map((o) => ({ value: o.value, label: o.label })),
              onValueChange: (v) => update("toolType", v),
              hint: TOOL_TYPE_OPTIONS.find((o) => o.value === value.toolType)?.description
            }
          ),
          /* @__PURE__ */ jsx(
            FormSelect,
            {
              label: "Enabled",
              value: value.enabled ? "true" : "false",
              options: [{ value: "true", label: "Enabled" }, { value: "false", label: "Disabled" }],
              onValueChange: (v) => update("enabled", v === "true")
            }
          ),
          /* @__PURE__ */ jsx(
            FormInput,
            {
              label: "Icon (optional)",
              value: value.icon ?? "",
              onValueChange: (icon) => update("icon", icon),
              placeholder: "heroicons:wrench-screwdriver"
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          FormTextarea,
          {
            label: "Description",
            rows: 2,
            value: value.description ?? "",
            onValueChange: (description) => update("description", description),
            placeholder: "One-sentence summary shown to the agent when it picks tools."
          }
        ),
        /* @__PURE__ */ jsx(
          ParametersEditor,
          {
            parameters: value.parameters,
            onChange: (parameters) => update("parameters", parameters)
          }
        ),
        /* @__PURE__ */ jsx(
          HandlerConfigEditor,
          {
            toolType: value.toolType,
            config: value.handlerConfig,
            onChange: (handlerConfig) => update("handlerConfig", handlerConfig)
          }
        ),
        error && /* @__PURE__ */ jsx("p", { className: "rounded-lg border border-red-400/40 bg-red-500/10 p-2 text-xs text-red-600 dark:text-red-300", children: error })
      ] })
    }
  );
}
function ParametersEditor({
  parameters,
  onChange
}) {
  const update = (index, patch) => {
    onChange(parameters.map((p, i) => i === index ? { ...p, ...patch } : p));
  };
  const remove = (index) => {
    onChange(parameters.filter((_, i) => i !== index));
  };
  const add = () => {
    onChange([...parameters, { name: "", type: "string", description: "", required: false }]);
  };
  return /* @__PURE__ */ jsxs("section", { className: "rounded-xl border border-slate-200 bg-slate-50/60 p-3 dark:border-slate-700 dark:bg-slate-900/40", children: [
    /* @__PURE__ */ jsx("h3", { className: "mb-2 text-sm font-semibold text-slate-700 dark:text-slate-200", children: "Parameters" }),
    /* @__PURE__ */ jsx("p", { className: "mb-3 text-xs text-slate-500 dark:text-slate-400", children: "The agent gets these as a JSON Schema. Any parameter marked required must be supplied for the LLM to call the tool." }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      parameters.map((param, index) => /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[1fr_160px_1fr_110px_auto] items-end gap-2", children: [
        /* @__PURE__ */ jsx(
          FormInput,
          {
            label: "Name",
            value: param.name,
            onValueChange: (name) => update(index, { name }),
            placeholder: "station_id"
          }
        ),
        /* @__PURE__ */ jsx(
          FormSelect,
          {
            label: "Type",
            value: param.type,
            options: PARAMETER_TYPE_OPTIONS,
            onValueChange: (t) => update(index, { type: t })
          }
        ),
        /* @__PURE__ */ jsx(
          FormInput,
          {
            label: "Description",
            value: param.description,
            onValueChange: (description) => update(index, { description })
          }
        ),
        /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 pb-2 text-xs text-gray-700 dark:text-gray-300", children: [
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "checkbox",
              checked: param.required,
              onChange: (event) => update(index, { required: event.target.checked }),
              className: "h-4 w-4 rounded border-gray-300"
            }
          ),
          "Required"
        ] }),
        /* @__PURE__ */ jsx(Button, { type: "button", plain: true, onClick: () => remove(index), children: "Remove" })
      ] }, index)),
      /* @__PURE__ */ jsx(Button, { type: "button", outline: true, onClick: add, children: "+ Add parameter" })
    ] })
  ] });
}
function HandlerConfigEditor({
  toolType,
  config,
  onChange
}) {
  const set = (key, value) => onChange({ ...config, [key]: value });
  if (toolType === "http") {
    return /* @__PURE__ */ jsxs("section", { className: "rounded-xl border border-slate-200 bg-slate-50/60 p-3 dark:border-slate-700 dark:bg-slate-900/40", children: [
      /* @__PURE__ */ jsx("h3", { className: "mb-2 text-sm font-semibold text-slate-700 dark:text-slate-200", children: "HTTP handler" }),
      /* @__PURE__ */ jsxs(FormGrid, { children: [
        /* @__PURE__ */ jsx(
          FormSelect,
          {
            label: "Method",
            value: stringProp(config, "method", "GET"),
            options: ["GET", "POST", "PUT", "PATCH", "DELETE"].map((m) => ({ value: m, label: m })),
            onValueChange: (m) => set("method", m)
          }
        ),
        /* @__PURE__ */ jsx(
          FormInput,
          {
            label: "URL template",
            value: stringProp(config, "url"),
            onValueChange: (u) => set("url", u),
            placeholder: "https://api.example.com/stations/{{ station_id }}"
          }
        )
      ] }),
      /* @__PURE__ */ jsx(
        FormTextarea,
        {
          label: "Headers (JSON)",
          rows: 3,
          value: jsonProp(config, "headers"),
          onValueChange: (raw) => setFromJson(set, "headers", raw),
          placeholder: '{ "Authorization": "Bearer {{ apiKey }}" }'
        }
      ),
      /* @__PURE__ */ jsx(
        FormTextarea,
        {
          label: "Body template",
          rows: 3,
          value: stringProp(config, "bodyTemplate"),
          onValueChange: (b) => set("bodyTemplate", b),
          placeholder: '{"query": "{{ search }}"}'
        }
      )
    ] });
  }
  if (toolType === "function") {
    return /* @__PURE__ */ jsxs("section", { className: "rounded-xl border border-slate-200 bg-slate-50/60 p-3 dark:border-slate-700 dark:bg-slate-900/40", children: [
      /* @__PURE__ */ jsx("h3", { className: "mb-2 text-sm font-semibold text-slate-700 dark:text-slate-200", children: "Function handler" }),
      /* @__PURE__ */ jsx(
        FormInput,
        {
          label: "Implementation key",
          value: stringProp(config, "implementationKey"),
          onValueChange: (k) => set("implementationKey", k),
          placeholder: "catalog.get_product_prices",
          hint: "Must match a pre-registered handler on the server side."
        }
      )
    ] });
  }
  if (toolType === "database_query") {
    return /* @__PURE__ */ jsxs("section", { className: "rounded-xl border border-slate-200 bg-slate-50/60 p-3 dark:border-slate-700 dark:bg-slate-900/40", children: [
      /* @__PURE__ */ jsx("h3", { className: "mb-2 text-sm font-semibold text-slate-700 dark:text-slate-200", children: "Database query handler" }),
      /* @__PURE__ */ jsxs(FormGrid, { children: [
        /* @__PURE__ */ jsx(
          FormInput,
          {
            label: "Datasource ID",
            value: stringProp(config, "datasourceId"),
            onValueChange: (v) => set("datasourceId", v),
            placeholder: "UUID from /datasources"
          }
        ),
        /* @__PURE__ */ jsx(
          FormInput,
          {
            label: "Max rows",
            type: "number",
            value: numberProp(config, "maxRows", 100),
            onValueChange: (v) => set("maxRows", Number(v) || 100)
          }
        )
      ] }),
      /* @__PURE__ */ jsx(
        FormTextarea,
        {
          label: "Query template",
          rows: 4,
          value: stringProp(config, "queryTemplate"),
          onValueChange: (v) => set("queryTemplate", v),
          placeholder: "SELECT id, current_price FROM current_prices WHERE station_id = {{ station_id }}"
        }
      )
    ] });
  }
  if (toolType === "code_execution") {
    return /* @__PURE__ */ jsxs("section", { className: "rounded-xl border border-slate-200 bg-slate-50/60 p-3 dark:border-slate-700 dark:bg-slate-900/40", children: [
      /* @__PURE__ */ jsx("h3", { className: "mb-2 text-sm font-semibold text-slate-700 dark:text-slate-200", children: "Code execution handler" }),
      /* @__PURE__ */ jsx("p", { className: "mb-2 text-xs text-amber-600 dark:text-amber-400", children: "Experimental \u2014 sandbox is not yet enforced. Only enable for trusted tools." }),
      /* @__PURE__ */ jsx(
        FormSelect,
        {
          label: "Language",
          value: stringProp(config, "language", "javascript"),
          options: [
            { value: "javascript", label: "JavaScript" },
            { value: "python", label: "Python" }
          ],
          onValueChange: (v) => set("language", v)
        }
      ),
      /* @__PURE__ */ jsx(
        FormTextarea,
        {
          label: "Code",
          rows: 6,
          value: stringProp(config, "code"),
          onValueChange: (v) => set("code", v),
          placeholder: "// return value becomes the tool output\nreturn { price: inputs.x * 1.08 }"
        }
      )
    ] });
  }
  return /* @__PURE__ */ jsxs("section", { className: "rounded-xl border border-slate-200 bg-slate-50/60 p-3 dark:border-slate-700 dark:bg-slate-900/40", children: [
    /* @__PURE__ */ jsx("h3", { className: "mb-2 text-sm font-semibold text-slate-700 dark:text-slate-200", children: "API call handler" }),
    /* @__PURE__ */ jsxs(FormGrid, { children: [
      /* @__PURE__ */ jsx(
        FormInput,
        {
          label: "URL",
          value: stringProp(config, "url"),
          onValueChange: (v) => set("url", v)
        }
      ),
      /* @__PURE__ */ jsx(
        FormSelect,
        {
          label: "Auth",
          value: stringProp(config, "authType", "bearer"),
          options: [
            { value: "none", label: "None" },
            { value: "bearer", label: "Bearer token" },
            { value: "api_key", label: "API key header" },
            { value: "basic", label: "Basic auth" }
          ],
          onValueChange: (v) => set("authType", v)
        }
      ),
      /* @__PURE__ */ jsx(
        FormInput,
        {
          label: "Credential secret id",
          value: stringProp(config, "credentialRef"),
          onValueChange: (v) => set("credentialRef", v),
          placeholder: "UUID from vault",
          hint: "Leave blank if Auth is None."
        }
      )
    ] })
  ] });
}
function parametersToJsonSchema(params) {
  const properties = {};
  const required = [];
  for (const param of params) {
    if (!param.name.trim()) continue;
    properties[param.name] = {
      type: param.type,
      ...param.description ? { description: param.description } : {}
    };
    if (param.required) required.push(param.name);
  }
  const schema = { type: "object", properties };
  if (required.length > 0) schema.required = required;
  return schema;
}
function jsonSchemaToParameters(schema) {
  if (!schema || typeof schema !== "object" || Array.isArray(schema)) return [];
  const root = schema;
  const properties = root.properties;
  if (!properties || typeof properties !== "object" || Array.isArray(properties)) return [];
  const required = Array.isArray(root.required) ? root.required.filter((r) => typeof r === "string") : [];
  const entries = Object.entries(properties);
  return entries.map(([name, raw]) => {
    const def = raw ?? {};
    const rawType = def.type;
    const type = isParameterType(rawType) ? rawType : "string";
    return {
      name,
      type,
      description: typeof def.description === "string" ? def.description : "",
      required: required.includes(name)
    };
  });
}
function isParameterType(v) {
  return v === "string" || v === "number" || v === "boolean" || v === "array" || v === "object";
}
function defaultForm() {
  return {
    name: "",
    description: "",
    toolType: "http",
    parameters: [],
    handlerConfig: { method: "GET" },
    enabled: true
  };
}
function toolToForm(tool) {
  const raw = tool;
  const implRaw = raw.implementationKey ?? raw.implementation_key;
  let handlerConfig = {};
  if (typeof implRaw === "string") {
    try {
      const parsed = JSON.parse(implRaw);
      if (parsed && typeof parsed === "object") {
        const inner = parsed.handlerConfig ?? parsed.handler_config;
        if (inner && typeof inner === "object" && !Array.isArray(inner)) {
          handlerConfig = inner;
        }
      }
    } catch {
      handlerConfig = { implementationKey: implRaw };
    }
  }
  const toolTypeRaw = raw.toolType ?? raw.tool_type ?? raw.category;
  const toolType = TOOL_TYPES.includes(String(toolTypeRaw)) ? toolTypeRaw : "function";
  const parameters = jsonSchemaToParameters(raw.parameters ?? raw.inputSchema ?? raw.input_schema);
  return {
    agentToolId: tool.agentToolId,
    name: tool.name,
    description: tool.description,
    toolType,
    parameters,
    handlerConfig,
    enabled: tool.enabled,
    icon: tool.icon
  };
}
function toolTypeLabel(tool) {
  const raw = tool;
  const t = raw.toolType ?? raw.tool_type ?? tool.category;
  const entry = TOOL_TYPE_OPTIONS.find((o) => o.value === t);
  return entry?.label ?? (typeof t === "string" ? t : "tool");
}
function stringProp(obj, key, fallback = "") {
  const value = obj[key];
  return typeof value === "string" ? value : fallback;
}
function numberProp(obj, key, fallback) {
  const value = obj[key];
  return typeof value === "number" && Number.isFinite(value) ? String(value) : String(fallback);
}
function jsonProp(obj, key) {
  const value = obj[key];
  if (!value) return "";
  if (typeof value === "string") return value;
  try {
    return JSON.stringify(value, null, 2);
  } catch {
    return "";
  }
}
function setFromJson(set, key, raw) {
  if (!raw.trim()) {
    set(key, void 0);
    return;
  }
  try {
    set(key, JSON.parse(raw));
  } catch {
    set(key, raw);
  }
}
function RulesPageView({ labels, rules, loading, onCreate, onUpdate, onDelete }) {
  const [createOpen, setCreateOpen] = useState(false);
  const [editing, setEditing] = useState(null);
  const hero = /* @__PURE__ */ jsx(
    HeroSection,
    {
      icon: /* @__PURE__ */ jsx(AdjustmentsHorizontalIcon, { className: "h-5 w-5" }),
      label: labels.title,
      title: labels.title,
      subtitle: labels.subtitle,
      gradient: "from-fuchsia-500 to-purple-700",
      toolbar: /* @__PURE__ */ jsx(
        CreateActionButton,
        {
          mode: "desktop",
          label: labels.addRule,
          onClick: () => setCreateOpen(true),
          accent: "fuchsia"
        }
      )
    }
  );
  const mobileAction = /* @__PURE__ */ jsx(
    CreateActionButton,
    {
      mode: "mobile",
      label: labels.addRule,
      onClick: () => setCreateOpen(true),
      accent: "fuchsia"
    }
  );
  const content = loading ? /* @__PURE__ */ jsx(PageLoadingState, {}) : rules.length === 0 ? /* @__PURE__ */ jsx(PageEmptyState, { title: labels.empty, message: labels.subtitle, iconName: "folder-open" }) : /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3", children: rules.map((rule) => /* @__PURE__ */ jsx(
    EntityCard,
    {
      accentGradient: "from-fuchsia-500 to-purple-700",
      icon: /* @__PURE__ */ jsx("div", { className: "flex h-11 w-11 items-center justify-center rounded-lg bg-fuchsia-500/10 text-fuchsia-600 dark:bg-fuchsia-500/20 dark:text-fuchsia-400", children: /* @__PURE__ */ jsx(AdjustmentsHorizontalIcon, { className: "h-6 w-6" }) }),
      title: rule.name,
      subtitle: `${labels.order}: ${rule.order ?? 0}`,
      status: /* @__PURE__ */ jsx(Badge, { color: rule.enabled ? "emerald" : "zinc", children: rule.enabled ? labels.enabled : labels.disabled }),
      footer: /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", outline: true, onClick: () => setEditing(rule), children: labels.edit }),
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            size: "sm",
            color: "rose",
            onClick: () => {
              if (window.confirm(labels.deleteConfirm)) onDelete(rule);
            },
            children: labels.delete
          }
        )
      ] }),
      children: rule.description && /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-slate-500 dark:text-slate-400", children: rule.description })
    },
    rule.ruleId
  )) });
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(ManagementPageLayout, { hero, content, mobileAction }),
    createOpen && /* @__PURE__ */ jsx(
      RuleEditor,
      {
        title: labels.createTitle,
        saveLabel: labels.save,
        initial: defaultRuleForm(),
        onClose: () => setCreateOpen(false),
        onSubmit: (value) => {
          onCreate(value);
          setCreateOpen(false);
        }
      }
    ),
    editing && /* @__PURE__ */ jsx(
      RuleEditor,
      {
        title: labels.editTitle,
        saveLabel: labels.save,
        initial: ruleToFormValue(editing),
        onClose: () => setEditing(null),
        onSubmit: (value) => {
          onUpdate(editing.ruleId, value);
          setEditing(null);
        }
      }
    )
  ] });
}
function RuleEditor({
  title,
  saveLabel,
  initial,
  onSubmit,
  onClose
}) {
  const [value, setValue] = useState(initial);
  return /* @__PURE__ */ jsx(
    GlassModal,
    {
      open: true,
      onClose,
      title,
      maxWidth: "3xl",
      showFormFooter: true,
      submitLabel: saveLabel,
      onSubmit: (event) => {
        event.preventDefault();
        onSubmit(value);
      },
      children: /* @__PURE__ */ jsx(RuleForm, { value, onChange: setValue })
    }
  );
}
function ruleToFormValue(rule) {
  const base = defaultRuleForm();
  const rawCondition = rule.condition ?? rule.conditions;
  const rawAction = pickAction(rule);
  return {
    ...base,
    ruleId: rule.ruleId,
    name: rule.name ?? "",
    description: rule.description ?? "",
    enabled: rule.enabled,
    priority: typeof rule.order === "number" ? rule.order : typeof rule.priority === "number" ? rule.priority : 0,
    condition: rawCondition && typeof rawCondition === "object" ? rawCondition : base.condition,
    action: rawAction ?? base.action,
    status: typeof rule.status === "string" ? rule.status : base.status,
    validFrom: typeof rule.validFrom === "string" ? rule.validFrom : base.validFrom,
    validUntil: typeof rule.validUntil === "string" ? rule.validUntil : base.validUntil,
    tags: Array.isArray(rule.tags) ? rule.tags.filter((tag) => typeof tag === "string") : base.tags
  };
}
function pickAction(rule) {
  const singular = rule.action;
  if (singular && typeof singular === "object" && "type" in singular) {
    return singular;
  }
  if (Array.isArray(rule.actions) && rule.actions.length > 0) {
    const first = rule.actions[0];
    if (first && typeof first === "object" && "type" in first) {
      return first;
    }
  }
  return void 0;
}
var SAMPLE_DATASOURCES = [
  {
    id: "ds_bigquery_analytics",
    organizationId: "org_demo",
    name: "BigQuery Analytics",
    dialect: "bigquery",
    credentials: null,
    readOnly: true,
    maxPoolSize: null,
    timeoutMs: 3e4,
    allowedTables: null,
    blockedColumns: null,
    enabled: true,
    createdAt: "2026-03-20T10:00:00Z",
    updatedAt: "2026-03-20T10:00:00Z",
    slug: "bigquery-analytics"
  },
  {
    id: "ds_postgres_prod",
    organizationId: "org_demo",
    name: "Production PostgreSQL",
    dialect: "postgres",
    credentials: null,
    readOnly: true,
    maxPoolSize: 10,
    timeoutMs: 15e3,
    allowedTables: null,
    blockedColumns: null,
    enabled: true,
    createdAt: "2026-03-18T08:30:00Z",
    updatedAt: "2026-03-22T14:00:00Z",
    slug: "production-postgresql"
  },
  {
    id: "ds_snowflake_dw",
    organizationId: "org_demo",
    name: "Snowflake Data Warehouse",
    dialect: "snowflake",
    credentials: null,
    readOnly: true,
    maxPoolSize: null,
    timeoutMs: 3e4,
    allowedTables: null,
    blockedColumns: null,
    enabled: true,
    createdAt: "2026-03-15T09:00:00Z",
    updatedAt: "2026-03-21T11:00:00Z",
    slug: "snowflake-data-warehouse"
  },
  {
    id: "ds_mongodb_events",
    organizationId: "org_demo",
    name: "Event Store (MongoDB)",
    dialect: "mongodb",
    credentials: null,
    readOnly: true,
    maxPoolSize: 5,
    timeoutMs: 1e4,
    allowedTables: null,
    blockedColumns: null,
    enabled: false,
    createdAt: "2026-03-10T12:00:00Z",
    updatedAt: "2026-03-19T16:00:00Z",
    slug: "event-store-mongodb"
  },
  {
    id: "ds_redis_cache",
    organizationId: "org_demo",
    name: "Redis Cache Layer",
    dialect: "redis",
    credentials: null,
    readOnly: false,
    maxPoolSize: 20,
    timeoutMs: 5e3,
    allowedTables: null,
    blockedColumns: null,
    enabled: true,
    createdAt: "2026-03-12T07:00:00Z",
    updatedAt: "2026-03-23T09:00:00Z",
    slug: "redis-cache-layer"
  },
  {
    id: "ds_pinecone_vectors",
    organizationId: "org_demo",
    name: "Pinecone Embeddings",
    dialect: "pinecone",
    credentials: null,
    readOnly: true,
    maxPoolSize: null,
    timeoutMs: 2e4,
    allowedTables: null,
    blockedColumns: null,
    enabled: true,
    createdAt: "2026-03-22T15:00:00Z",
    updatedAt: "2026-03-25T10:00:00Z",
    slug: "pinecone-embeddings"
  }
];
function getDialectLabel(dialect) {
  if (!dialect) return "Unknown";
  for (const category of DIALECT_CATEGORIES) {
    const found = category.dialects.find((d) => d.value === dialect);
    if (found) return found.label;
  }
  return dialect;
}
function getDialectGradient(dialect) {
  if (!dialect) return "from-gray-400 to-gray-500";
  const category = findCategory(dialect);
  return category?.gradient ?? "from-gray-400 to-gray-500";
}
function getDialectIcon(dialect) {
  if (!dialect) return CircleStackIcon;
  const category = findCategory(dialect);
  return category?.icon ?? CircleStackIcon;
}
var DIALECT_LOGO = {
  bigquery: "/logos/datasources/bigquery.svg",
  postgres: "/logos/datasources/postgres.svg",
  postgresql: "/logos/datasources/postgres.svg",
  mysql: "/logos/datasources/mysql.svg",
  mariadb: "/logos/datasources/mariadb.svg",
  snowflake: "/logos/datasources/snowflake.svg",
  mongodb: "/logos/datasources/mongodb.svg",
  redis: "/logos/datasources/redis.svg",
  clickhouse: "/logos/datasources/clickhouse.svg",
  elasticsearch: "/logos/datasources/elasticsearch.svg",
  duckdb: "/logos/datasources/duckdb.svg",
  sqlite: "/logos/datasources/sqlite.svg",
  oracle: "/logos/datasources/oracle.svg",
  mssql: "/logos/datasources/mssql.svg",
  sqlserver: "/logos/datasources/mssql.svg",
  cassandra: "/logos/datasources/cassandra.svg",
  dynamodb: "/logos/datasources/dynamodb.svg",
  cockroach: "/logos/datasources/cockroachdb.svg",
  cockroachdb: "/logos/datasources/cockroachdb.svg",
  supabase: "/logos/datasources/supabase.svg",
  firebase: "/logos/datasources/firebase.svg",
  neo4j: "/logos/datasources/neo4j.svg"
};
function getDialectLogoSrc(dialect) {
  if (!dialect) return null;
  return DIALECT_LOGO[dialect.toLowerCase()] ?? null;
}
function DatasourcesPageView({
  labels,
  datasources: externalDatasources,
  useSampleData = false,
  onCreate
}) {
  const [modalOpen, setModalOpen] = useState(false);
  const [localDatasources, setLocalDatasources] = useState(
    useSampleData ? SAMPLE_DATASOURCES : []
  );
  const datasources = externalDatasources ?? localDatasources;
  const isEmpty = datasources.length === 0;
  function handleCreate(data) {
    if (onCreate) {
      onCreate(data);
      return;
    }
    const newDs = {
      id: `ds_${Date.now()}`,
      organizationId: "org_demo",
      name: data.name,
      dialect: data.dialect,
      credentials: null,
      readOnly: data.readOnly ?? true,
      maxPoolSize: null,
      timeoutMs: 3e4,
      allowedTables: null,
      blockedColumns: null,
      enabled: true,
      createdAt: (/* @__PURE__ */ new Date()).toISOString(),
      updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
      slug: data.name.toLowerCase().replace(/\s+/g, "-")
    };
    setLocalDatasources((previous) => [...previous, newDs]);
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsx(
      HeroSection,
      {
        icon: /* @__PURE__ */ jsx(CircleStackIcon, { className: "h-5 w-5" }),
        label: labels.title,
        title: labels.title,
        subtitle: labels.subtitle,
        gradient: "from-amber-500 to-orange-600",
        toolbar: /* @__PURE__ */ jsx(
          CreateActionButton,
          {
            mode: "desktop",
            label: labels.addDatasource,
            onClick: () => setModalOpen(true),
            accent: "amber"
          }
        )
      }
    ),
    /* @__PURE__ */ jsx(
      CreateActionButton,
      {
        mode: "mobile",
        label: labels.addDatasource,
        onClick: () => setModalOpen(true),
        accent: "amber"
      }
    ),
    isEmpty ? /* @__PURE__ */ jsx(
      PageEmptyState,
      {
        title: labels.emptyTitle,
        message: labels.emptyDescription,
        iconName: "link",
        customIcon: /* @__PURE__ */ jsx(CircleStackIcon, { className: "h-10 w-10 text-amber-500 dark:text-amber-400" })
      }
    ) : /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3", children: datasources.map((ds) => {
      const Icon = getDialectIcon(ds.dialect);
      const gradient = getDialectGradient(ds.dialect);
      const dialectLabel = getDialectLabel(ds.dialect);
      const logoSrc = getDialectLogoSrc(ds.dialect);
      const iconElement = logoSrc ? /* @__PURE__ */ jsx("div", { className: "flex h-11 w-11 items-center justify-center rounded-lg bg-white shadow-sm ring-1 ring-black/5 dark:bg-white/10 dark:ring-white/10", children: /* @__PURE__ */ jsx("img", { src: logoSrc, alt: dialectLabel, className: "h-7 w-7 object-contain" }) }) : /* @__PURE__ */ jsx("div", { className: `flex h-11 w-11 items-center justify-center rounded-lg bg-gradient-to-br ${gradient} shadow-lg`, children: /* @__PURE__ */ jsx(Icon, { className: "h-6 w-6 text-white" }) });
      return /* @__PURE__ */ jsx(
        EntityCard,
        {
          accentGradient: gradient,
          icon: iconElement,
          title: ds.name ?? ds.id,
          subtitle: dialectLabel,
          status: /* @__PURE__ */ jsx(Badge, { color: ds.enabled ? "emerald" : "zinc", children: ds.enabled ? labels.enabled : labels.disabled }),
          footer: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs text-gray-400 dark:text-gray-500", children: [
            ds.readOnly && /* @__PURE__ */ jsx("span", { className: "rounded-full bg-blue-100 px-2 py-0.5 text-[10px] font-semibold text-blue-700 dark:bg-blue-900/30 dark:text-blue-300", children: "Read-only" }),
            ds.timeoutMs && /* @__PURE__ */ jsxs("span", { children: [
              ds.timeoutMs / 1e3,
              "s timeout"
            ] })
          ] }),
          children: /* @__PURE__ */ jsxs("div", { className: "mt-2 text-xs text-gray-500 dark:text-gray-400", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              labels.dialect,
              ": ",
              dialectLabel
            ] }),
            ds.slug && /* @__PURE__ */ jsxs("div", { className: "truncate text-gray-400", children: [
              "/",
              ds.slug
            ] })
          ] })
        },
        ds.id
      );
    }) }),
    /* @__PURE__ */ jsx(
      DatasourceModal,
      {
        open: modalOpen,
        onClose: () => setModalOpen(false),
        labels,
        onSave: handleCreate
      }
    )
  ] });
}
function DashboardPageView({ labels, appLogo }) {
  const hero = /* @__PURE__ */ jsxs("div", { className: "w-full text-center", children: [
    /* @__PURE__ */ jsx("div", { className: "flex justify-center mb-6", children: appLogo }),
    /* @__PURE__ */ jsx("p", { className: "mt-3 text-base text-gray-500 dark:text-gray-400", children: labels.subtitle })
  ] });
  return /* @__PURE__ */ jsx(ManagementPageLayout, { hero, content: null });
}
function AgentsIndexPageView({ labels }) {
  const Link = useLink();
  const tiles = [
    { id: "config", title: labels.configTitle, subtitle: labels.configSubtitle, href: "/agents/config", gradient: "from-violet-500 to-indigo-700", icon: CpuChipIcon },
    { id: "tools", title: labels.toolDefinitionsTitle, subtitle: labels.toolDefinitionsSubtitle, href: "/agents/tool-definitions", gradient: "from-amber-500 to-orange-700", icon: WrenchScrewdriverIcon },
    { id: "models", title: labels.modelsTitle, subtitle: labels.modelsSubtitle, href: "/agents/models", gradient: "from-emerald-500 to-teal-700", icon: CubeTransparentIcon },
    { id: "prompts", title: labels.promptsTitle, subtitle: labels.promptsSubtitle, href: "/agents/prompts", gradient: "from-sky-500 to-blue-700", icon: ChatBubbleLeftEllipsisIcon }
  ];
  const hero = /* @__PURE__ */ jsx(
    HeroSection,
    {
      icon: /* @__PURE__ */ jsx(CpuChipIcon, { className: "h-5 w-5" }),
      label: labels.title,
      title: labels.title,
      subtitle: labels.subtitle,
      gradient: "from-violet-500 to-indigo-700"
    }
  );
  const content = /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4", children: tiles.map((tile) => {
    const Icon = tile.icon;
    return /* @__PURE__ */ jsx(Link, { href: tile.href, className: "block focus:outline-none", children: /* @__PURE__ */ jsx(
      EntityCard,
      {
        accentGradient: tile.gradient,
        icon: /* @__PURE__ */ jsx("div", { className: `flex h-11 w-11 items-center justify-center rounded-lg bg-gradient-to-br ${tile.gradient} shadow-lg`, children: /* @__PURE__ */ jsx(Icon, { className: "h-6 w-6 text-white" }) }),
        title: tile.title,
        children: /* @__PURE__ */ jsx("p", { className: "text-xs text-slate-500 dark:text-slate-400", children: tile.subtitle })
      }
    ) }, tile.id);
  }) });
  return /* @__PURE__ */ jsx(ManagementPageLayout, { hero, content });
}
function WorkflowsPageView({ labels, workflows, onCreate, onUpdateMeta, onPublish }) {
  const selectedWorkflow = workflows[0] ?? null;
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsx(
      SectionHeader,
      {
        icon: /* @__PURE__ */ jsx(RectangleStackIcon, { className: "h-5 w-5 text-white" }),
        title: labels.title,
        subtitle: labels.subtitle,
        gradient: "from-sky-500 to-indigo-600"
      }
    ),
    /* @__PURE__ */ jsxs("section", { className: "liquid-surface rounded-2xl p-4 space-y-3", children: [
      /* @__PURE__ */ jsx(Text, { className: "font-semibold text-slate-900 dark:text-slate-100", children: labels.add }),
      /* @__PURE__ */ jsx(
        Form,
        {
          onSubmit: (event) => {
            event.preventDefault();
            const formData = new FormData(event.currentTarget);
            const name = String(formData.get("name") ?? "").trim();
            const description = String(formData.get("description") ?? "").trim();
            if (!name) return;
            onCreate({ name, description });
            event.currentTarget.reset();
          },
          children: /* @__PURE__ */ jsxs(FormGrid, { children: [
            /* @__PURE__ */ jsx(FormInput, { name: "name", label: labels.workflowName, placeholder: labels.workflowNamePlaceholder, required: true }),
            /* @__PURE__ */ jsx(FormTextarea, { name: "description", label: labels.description, placeholder: labels.workflowDescriptionPlaceholder, rows: 3 }),
            /* @__PURE__ */ jsx(FormActionsRow, { children: /* @__PURE__ */ jsx(Button, { type: "submit", children: labels.create }) })
          ] })
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("section", { className: "liquid-surface rounded-2xl p-4 space-y-3", children: [
      /* @__PURE__ */ jsx(Text, { className: "font-semibold text-slate-900 dark:text-slate-100", children: labels.registry }),
      /* @__PURE__ */ jsxs(Table, { children: [
        /* @__PURE__ */ jsx(TableHead, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
          /* @__PURE__ */ jsx(TableHeader, { children: labels.name }),
          /* @__PURE__ */ jsx(TableHeader, { children: labels.description }),
          /* @__PURE__ */ jsx(TableHeader, { children: labels.version }),
          /* @__PURE__ */ jsx(TableHeader, { children: labels.status }),
          /* @__PURE__ */ jsx(TableHeader, { children: labels.actions })
        ] }) }),
        /* @__PURE__ */ jsx(TableBody, { children: workflows.map((workflow) => /* @__PURE__ */ jsxs(TableRow, { children: [
          /* @__PURE__ */ jsx(TableCell, { children: workflow.name }),
          /* @__PURE__ */ jsx(TableCell, { children: workflow.description }),
          /* @__PURE__ */ jsx(TableCell, { children: String(workflow.version) }),
          /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx(Badge, { children: workflow.isDraft ? labels.statusDraft : labels.statusPublished }) }),
          /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2", children: [
            /* @__PURE__ */ jsx(
              Form,
              {
                onSubmit: (event) => {
                  event.preventDefault();
                  onUpdateMeta({
                    workflowId: workflow.id,
                    name: workflow.name ?? "",
                    description: workflow.description ?? ""
                  });
                },
                children: /* @__PURE__ */ jsx(InlineForm, { children: /* @__PURE__ */ jsx(Button, { type: "submit", outline: true, children: labels.saveMeta }) })
              }
            ),
            /* @__PURE__ */ jsx(Button, { type: "button", color: "sky", onClick: () => onPublish(workflow.id), children: labels.publish })
          ] }) })
        ] }, workflow.id)) })
      ] })
    ] }),
    /* @__PURE__ */ jsxs("section", { className: "liquid-surface rounded-2xl p-4 space-y-3", children: [
      /* @__PURE__ */ jsx(Text, { className: "font-semibold text-slate-900 dark:text-slate-100", children: labels.workspace }),
      selectedWorkflow ? /* @__PURE__ */ jsx("div", { className: "min-h-[680px] rounded-2xl border border-white/65 dark:border-white/12 overflow-hidden", children: /* @__PURE__ */ jsx(WorkflowWorkspace, { graph: adaptWorkflowGraphToUi(selectedWorkflow.graph) }) }) : /* @__PURE__ */ jsx(Text, { children: labels.empty })
    ] })
  ] });
}
var BADGE_COLOR = {
  completed: "emerald",
  failed: "rose",
  running: "sky",
  pending: "amber",
  cancelled: "zinc"
};
function WorkflowRunsPageView({ labels, runs, loading, onCancel, onReplay, onView, onViewTimeline }) {
  const [statusFilter, setStatusFilter] = useState("all");
  const statusOptions = useMemo(() => [
    { value: "all", label: labels.filterAll },
    { value: "pending", label: labels.statusPending },
    { value: "running", label: labels.statusRunning },
    { value: "completed", label: labels.statusCompleted },
    { value: "failed", label: labels.statusFailed },
    { value: "cancelled", label: labels.statusCancelled }
  ], [labels]);
  const statusLabelFor = (status) => {
    switch (status) {
      case "pending":
        return labels.statusPending;
      case "running":
        return labels.statusRunning;
      case "completed":
        return labels.statusCompleted;
      case "failed":
        return labels.statusFailed;
      case "cancelled":
        return labels.statusCancelled;
      default:
        return status;
    }
  };
  const filteredRuns = statusFilter === "all" ? runs : runs.filter((run) => run.status === statusFilter);
  const hero = /* @__PURE__ */ jsx(
    HeroSection,
    {
      icon: /* @__PURE__ */ jsx(ClockIcon, { className: "h-5 w-5" }),
      label: labels.title,
      title: labels.title,
      subtitle: labels.subtitle,
      gradient: "from-indigo-500 to-sky-700",
      toolbar: /* @__PURE__ */ jsx("div", { className: "w-48", children: /* @__PURE__ */ jsx(
        FormSelect,
        {
          name: "statusFilter",
          label: labels.filterStatus,
          options: statusOptions,
          value: statusFilter,
          onValueChange: setStatusFilter
        }
      ) })
    }
  );
  const content = loading ? /* @__PURE__ */ jsx(PageLoadingState, {}) : filteredRuns.length === 0 ? /* @__PURE__ */ jsx(PageEmptyState, { title: labels.empty, message: labels.subtitle, iconName: "folder-open" }) : /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3", children: filteredRuns.map((run) => /* @__PURE__ */ jsxs(
    EntityCard,
    {
      accentGradient: "from-indigo-500 to-sky-700",
      icon: /* @__PURE__ */ jsx("div", { className: "flex h-11 w-11 items-center justify-center rounded-lg bg-indigo-500/10 text-indigo-600 dark:bg-indigo-500/20 dark:text-indigo-400", children: /* @__PURE__ */ jsx(ClockIcon, { className: "h-6 w-6" }) }),
      title: run.id.slice(0, 8),
      subtitle: `${labels.startedAt}: ${new Date(run.createdAt).toLocaleString()}`,
      status: /* @__PURE__ */ jsx(Badge, { color: BADGE_COLOR[run.status] ?? "zinc", children: statusLabelFor(run.status) }),
      footer: /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        onView && /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", outline: true, onClick: () => onView(run), children: labels.view }),
        onViewTimeline && labels.timeline && /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", outline: true, onClick: () => onViewTimeline(run), children: labels.timeline }),
        /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", outline: true, onClick: () => onReplay(run), children: labels.replay }),
        run.status === "running" && /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", color: "rose", onClick: () => onCancel(run), children: labels.cancel })
      ] }),
      children: [
        /* @__PURE__ */ jsxs("dl", { className: "mt-1 grid grid-cols-2 gap-1 text-xs text-slate-500 dark:text-slate-400", children: [
          /* @__PURE__ */ jsx("dt", { children: labels.duration }),
          /* @__PURE__ */ jsx("dd", { className: "text-right", children: formatDurationMs(run.totalDurationMs) }),
          /* @__PURE__ */ jsx("dt", { children: labels.triggeredBy }),
          /* @__PURE__ */ jsx("dd", { className: "text-right truncate", children: run.triggeredBy || "\u2014" })
        ] }),
        run.error && /* @__PURE__ */ jsx("p", { className: "mt-1 line-clamp-2 text-xs text-rose-600 dark:text-rose-400", children: run.error })
      ]
    },
    run.id
  )) });
  return /* @__PURE__ */ jsx(ManagementPageLayout, { hero, content });
}
function RunTimelinePageView({ labels, entries, loading, runId }) {
  const hero = /* @__PURE__ */ jsx(
    HeroSection,
    {
      icon: /* @__PURE__ */ jsx(ClockIcon, { className: "h-5 w-5" }),
      label: labels.title,
      title: labels.title,
      subtitle: `${labels.subtitle} \u2014 ${runId.slice(0, 8)}`,
      gradient: "from-indigo-500 to-violet-700"
    }
  );
  if (loading) {
    return /* @__PURE__ */ jsx(ManagementPageLayout, { hero, content: /* @__PURE__ */ jsx(PageLoadingState, {}) });
  }
  if (entries.length === 0) {
    return /* @__PURE__ */ jsx(
      ManagementPageLayout,
      {
        hero,
        content: /* @__PURE__ */ jsx(PageEmptyState, { title: labels.empty ?? "", message: "", iconName: "folder-open" })
      }
    );
  }
  return /* @__PURE__ */ jsx(
    ManagementPageLayout,
    {
      hero,
      content: /* @__PURE__ */ jsx(
        ExecutionTimelinePanel,
        {
          entries,
          labels
        }
      )
    }
  );
}
var PROVIDER_PRESETS = {
  anthropic_api: {
    label: "Anthropic API",
    description: "Claude Opus, Sonnet, Haiku via api.anthropic.com",
    exampleModels: ["claude-opus-4-7", "claude-sonnet-4-6"]
  },
  openai_api: {
    label: "OpenAI API",
    description: "GPT-4o, o3, o4-mini via api.openai.com",
    exampleModels: ["gpt-4o", "gpt-4o-mini"]
  },
  aws_bedrock: {
    label: "AWS Bedrock",
    description: "Anthropic / Meta / Mistral / Nova served through Bedrock",
    needsRegion: true,
    defaultRegion: "us-east-1",
    exampleModels: ["amazon.nova-lite-v1:0", "anthropic.claude-3-5-sonnet-20241022-v2:0"]
  },
  google_vertex: {
    label: "Google Vertex AI",
    description: "Gemini + third-party models on Vertex",
    needsRegion: true,
    defaultRegion: "us-central1",
    exampleModels: ["gemini-2.0-flash-exp", "gemini-1.5-pro"]
  },
  azure_openai: {
    label: "Azure OpenAI",
    description: "OpenAI deployments hosted on Azure",
    needsRegion: true,
    needsEndpoint: true,
    defaultRegion: "eastus"
  },
  groq: {
    label: "Groq",
    description: "Low-latency Llama / Mixtral inference via api.groq.com"
  },
  mistral: {
    label: "Mistral API",
    description: "mistral.ai hosted open-weight + commercial models"
  },
  huggingface: {
    label: "Hugging Face",
    description: "Inference endpoints + serverless inference API",
    needsEndpoint: true
  },
  ollama: {
    label: "Ollama",
    description: "Self-hosted Ollama server \u2014 provide the base URL",
    needsEndpoint: true
  },
  custom: {
    label: "Custom / OpenAI-compatible",
    description: "Any OpenAI-API-compatible HTTP endpoint",
    needsEndpoint: true
  }
};
var PROVIDER_OPTIONS = Object.keys(PROVIDER_PRESETS).map((slug) => ({
  value: slug,
  label: PROVIDER_PRESETS[slug].label
}));
function ConnectionsPageView({
  labels,
  connections,
  loading,
  onCreate,
  onUpdate,
  onDelete,
  onCreateSecret,
  secretNamePrefix = "platform"
}) {
  const [createOpen, setCreateOpen] = useState(false);
  const [editing, setEditing] = useState(null);
  const hero = /* @__PURE__ */ jsx(
    HeroSection,
    {
      icon: /* @__PURE__ */ jsx(LinkIcon, { className: "h-5 w-5" }),
      label: labels.title,
      title: labels.title,
      subtitle: labels.subtitle,
      gradient: "from-sky-500 to-indigo-600",
      toolbar: /* @__PURE__ */ jsx(
        CreateActionButton,
        {
          mode: "desktop",
          label: labels.add,
          onClick: () => setCreateOpen(true),
          accent: "sky"
        }
      )
    }
  );
  const mobileAction = /* @__PURE__ */ jsx(
    CreateActionButton,
    {
      mode: "mobile",
      label: labels.add,
      onClick: () => setCreateOpen(true),
      accent: "sky"
    }
  );
  const content = loading ? /* @__PURE__ */ jsx(PageLoadingState, {}) : connections.length === 0 ? /* @__PURE__ */ jsx(PageEmptyState, { title: labels.empty, message: labels.subtitle, iconName: "folder-open" }) : /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3", children: connections.map((conn) => /* @__PURE__ */ jsx(
    EntityCard,
    {
      accentGradient: "from-sky-500 to-indigo-600",
      icon: /* @__PURE__ */ jsx("div", { className: "flex h-11 w-11 items-center justify-center rounded-lg bg-sky-500/10 text-sky-600 dark:bg-sky-500/20 dark:text-sky-400", children: /* @__PURE__ */ jsx(LinkIcon, { className: "h-6 w-6" }) }),
      title: conn.name,
      subtitle: providerLabel(conn.providerSlug),
      status: /* @__PURE__ */ jsxs("div", { className: "flex gap-1", children: [
        /* @__PURE__ */ jsx(Badge, { color: conn.enabled ? "emerald" : "zinc", children: conn.enabled ? labels.enable : labels.disable }),
        conn.credentialRef ? /* @__PURE__ */ jsx(Badge, { color: "indigo", children: "Secret set" }) : /* @__PURE__ */ jsx(Badge, { color: "amber", children: "No secret" })
      ] }),
      footer: /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", outline: true, onClick: () => setEditing(conn), children: labels.edit }),
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            size: "sm",
            color: "rose",
            onClick: async () => {
              if (window.confirm(labels.deleteConfirm)) await onDelete(conn);
            },
            children: labels.delete
          }
        )
      ] }),
      children: /* @__PURE__ */ jsxs("dl", { className: "mt-1 space-y-0.5 text-xs text-slate-500 dark:text-slate-400", children: [
        conn.region && /* @__PURE__ */ jsx(Row, { label: "Region", value: conn.region }),
        conn.endpoint && /* @__PURE__ */ jsx(Row, { label: "Endpoint", value: conn.endpoint }),
        conn.modelFilter && conn.modelFilter.length > 0 && /* @__PURE__ */ jsx(Row, { label: "Models", value: conn.modelFilter.join(", ") })
      ] })
    },
    conn.id
  )) });
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(ManagementPageLayout, { hero, content, mobileAction }),
    createOpen && /* @__PURE__ */ jsx(
      ConnectionEditor,
      {
        title: labels.createTitle,
        saveLabel: labels.save,
        initial: defaultConnectionFormValue(),
        mode: "create",
        onClose: () => setCreateOpen(false),
        onCreateSecret,
        secretNamePrefix,
        onSubmit: async (wire) => {
          await onCreate(wire);
          setCreateOpen(false);
        }
      }
    ),
    editing && /* @__PURE__ */ jsx(
      ConnectionEditor,
      {
        title: labels.editTitle,
        saveLabel: labels.save,
        initial: modelToFormValue(editing),
        mode: "edit",
        onClose: () => setEditing(null),
        onCreateSecret,
        secretNamePrefix,
        onSubmit: async (wire) => {
          await onUpdate(editing.id, wire);
          setEditing(null);
        }
      }
    )
  ] });
}
function ConnectionEditor({
  title,
  saveLabel,
  initial,
  mode,
  onClose,
  onSubmit,
  onCreateSecret,
  secretNamePrefix
}) {
  const [value, setValue] = useState(initial);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState(null);
  const preset = PROVIDER_PRESETS[value.providerSlug];
  const handleSubmit = async () => {
    setError(null);
    setSubmitting(true);
    try {
      let credentialRef = value.credentialRef;
      let credentialRefRotated = false;
      if (value.apiKey.trim().length > 0) {
        const secret = await onCreateSecret(`${secretNamePrefix}-${value.providerSlug}-${Date.now()}`, value.apiKey.trim());
        credentialRef = secret.id;
        credentialRefRotated = true;
      }
      const modelFilter = parseCsv(value.modelFilter);
      let config;
      const trimmed = value.configJson.trim();
      if (trimmed.length > 0) {
        try {
          const parsed = JSON.parse(trimmed);
          if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
            throw new Error("config must be a JSON object");
          }
          config = parsed;
        } catch (e) {
          throw new Error(`Invalid config JSON: ${e.message}`);
        }
      }
      if (mode === "create") {
        const wire = {
          providerSlug: value.providerSlug,
          name: value.name.trim(),
          ...value.region.trim() && { region: value.region.trim() },
          ...value.endpoint.trim() && { endpoint: value.endpoint.trim() },
          ...credentialRef && { credentialRef },
          ...modelFilter.length > 0 && { modelFilter },
          ...config && { config }
        };
        await onSubmit(wire);
      } else {
        const wire = {
          name: value.name.trim() || void 0,
          region: value.region.trim() || void 0,
          endpoint: value.endpoint.trim() || void 0,
          // Only thread `credentialRef` when the user actually rotated
          // the key. Omitting it tells the backend to keep the
          // existing pointer intact.
          ...credentialRefRotated && credentialRef ? { credentialRef } : {},
          ...modelFilter.length > 0 ? { modelFilter } : {},
          ...config && { config }
        };
        await onSubmit(wire);
      }
    } catch (e) {
      setError(e.message);
    } finally {
      setSubmitting(false);
    }
  };
  useEffect(() => {
    if (mode === "create" && preset.needsRegion && !value.region && preset.defaultRegion) {
      setValue((v) => ({ ...v, region: preset.defaultRegion ?? "" }));
    }
  }, [mode, preset, value.region]);
  const placeholderModels = useMemo(() => {
    return preset.exampleModels?.join(", ") ?? "";
  }, [preset]);
  return /* @__PURE__ */ jsx(
    GlassModal,
    {
      open: true,
      onClose,
      title,
      maxWidth: "2xl",
      showFormFooter: true,
      submitLabel: submitting ? "\u2026" : saveLabel,
      onSubmit: (event) => {
        event.preventDefault();
        void handleSubmit();
      },
      children: /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
        /* @__PURE__ */ jsxs(FormGrid, { children: [
          /* @__PURE__ */ jsx(
            FormSelect,
            {
              label: "Provider",
              value: value.providerSlug,
              options: PROVIDER_OPTIONS,
              onValueChange: (slug) => setValue((v) => ({ ...v, providerSlug: slug })),
              disabled: mode === "edit",
              hint: preset.description
            }
          ),
          /* @__PURE__ */ jsx(
            FormInput,
            {
              label: "Display name",
              required: true,
              value: value.name,
              onValueChange: (name) => setValue((v) => ({ ...v, name })),
              placeholder: "Production Bedrock, Claude dev, \u2026"
            }
          ),
          preset.needsRegion && /* @__PURE__ */ jsx(
            FormInput,
            {
              label: "Region",
              value: value.region,
              onValueChange: (region) => setValue((v) => ({ ...v, region })),
              placeholder: preset.defaultRegion
            }
          ),
          preset.needsEndpoint && /* @__PURE__ */ jsx(
            FormInput,
            {
              label: "Endpoint URL",
              value: value.endpoint,
              onValueChange: (endpoint) => setValue((v) => ({ ...v, endpoint })),
              placeholder: "https://..."
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          FormInput,
          {
            label: value.credentialRef ? "Rotate API key (leave blank to keep current)" : "API key",
            type: "password",
            value: value.apiKey,
            onValueChange: (apiKey) => setValue((v) => ({ ...v, apiKey })),
            placeholder: value.credentialRef ? "\u2022\u2022\u2022 stored in vault" : "sk-...",
            hint: value.credentialRef ? `Stored secret: ${value.credentialRef.slice(0, 8)}\u2026` : "Plaintext \u2014 pushed to windsock vault on save, never persisted here."
          }
        ),
        /* @__PURE__ */ jsx(
          FormInput,
          {
            label: "Model filter (comma-separated, optional)",
            value: value.modelFilter,
            onValueChange: (modelFilter) => setValue((v) => ({ ...v, modelFilter })),
            placeholder: placeholderModels,
            hint: "Leave blank to allow all models the provider exposes."
          }
        ),
        /* @__PURE__ */ jsxs("details", { className: "rounded-xl border border-slate-200 bg-slate-50/60 p-3 text-sm dark:border-slate-700 dark:bg-slate-900/40", children: [
          /* @__PURE__ */ jsx("summary", { className: "cursor-pointer font-medium text-slate-700 dark:text-slate-200", children: "Advanced config (JSON)" }),
          /* @__PURE__ */ jsx("div", { className: "mt-3", children: /* @__PURE__ */ jsx(
            FormTextarea,
            {
              rows: 4,
              value: value.configJson,
              onValueChange: (configJson) => setValue((v) => ({ ...v, configJson })),
              placeholder: '{\n  "temperature": 0.2\n}',
              hint: "Free-form JSON passed to the runtime provider \u2014 e.g. Bedrock guardrail ids, Azure deployment overrides."
            }
          ) })
        ] }),
        error && /* @__PURE__ */ jsx("p", { className: "rounded-lg border border-red-400/40 bg-red-500/10 p-2 text-xs text-red-600 dark:text-red-300", children: error })
      ] })
    }
  );
}
function Row({ label, value }) {
  return /* @__PURE__ */ jsxs("div", { className: "flex gap-1 truncate", children: [
    /* @__PURE__ */ jsxs("dt", { className: "font-medium", children: [
      label,
      ":"
    ] }),
    /* @__PURE__ */ jsx("dd", { className: "truncate", children: value })
  ] });
}
function providerLabel(slug) {
  if (!slug) return "Unknown provider";
  const key = slug;
  return PROVIDER_PRESETS[key]?.label ?? slug;
}
function parseCsv(raw) {
  return raw.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
}
function defaultConnectionFormValue() {
  return {
    providerSlug: "anthropic_api",
    name: "",
    region: "",
    endpoint: "",
    apiKey: "",
    credentialRef: "",
    modelFilter: "",
    configJson: ""
  };
}
function modelToFormValue(conn) {
  return {
    providerSlug: conn.providerSlug ?? "custom",
    name: conn.name,
    region: conn.region ?? "",
    endpoint: conn.endpoint ?? "",
    apiKey: "",
    credentialRef: conn.credentialRef ?? "",
    modelFilter: (conn.modelFilter ?? []).join(", "),
    configJson: conn.config ? JSON.stringify(conn.config, null, 2) : ""
  };
}
function CredentialsPageView({ labels, credentials, loading, onCreate, onRotate, onDisable }) {
  const [createOpen, setCreateOpen] = useState(false);
  const [rotateFor, setRotateFor] = useState(null);
  const typeOptions = [
    { value: "generic", label: labels.typeGeneric },
    { value: "api_key", label: labels.typeApiKey },
    { value: "oauth", label: labels.typeOAuth },
    { value: "password", label: labels.typePassword }
  ];
  const hero = /* @__PURE__ */ jsx(
    HeroSection,
    {
      icon: /* @__PURE__ */ jsx(KeyIcon, { className: "h-5 w-5" }),
      label: labels.title,
      title: labels.title,
      subtitle: labels.subtitle,
      gradient: "from-rose-500 to-orange-600",
      toolbar: /* @__PURE__ */ jsx(
        CreateActionButton,
        {
          mode: "desktop",
          label: labels.addCredential,
          onClick: () => setCreateOpen(true),
          accent: "rose"
        }
      )
    }
  );
  const mobileAction = /* @__PURE__ */ jsx(
    CreateActionButton,
    {
      mode: "mobile",
      label: labels.addCredential,
      onClick: () => setCreateOpen(true),
      accent: "rose"
    }
  );
  const content = loading ? /* @__PURE__ */ jsx(PageLoadingState, {}) : credentials.length === 0 ? /* @__PURE__ */ jsx(PageEmptyState, { title: labels.empty, message: labels.subtitle, iconName: "folder-open" }) : /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3", children: credentials.map((secret) => /* @__PURE__ */ jsxs(
    EntityCard,
    {
      accentGradient: "from-rose-500 to-orange-700",
      icon: /* @__PURE__ */ jsx("div", { className: "flex h-11 w-11 items-center justify-center rounded-lg bg-rose-500/10 text-rose-600 dark:bg-rose-500/20 dark:text-rose-400", children: /* @__PURE__ */ jsx(KeyIcon, { className: "h-6 w-6" }) }),
      title: secret.name,
      subtitle: secret.secretType,
      status: /* @__PURE__ */ jsx(Badge, { color: secret.disabled ? "zinc" : "emerald", children: secret.disabled ? labels.disable : "Active" }),
      footer: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
        /* @__PURE__ */ jsx(CopyableId, { id: secret.secretId }),
        /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsxs(Button, { type: "button", size: "sm", outline: true, onClick: () => setRotateFor(secret), children: [
            /* @__PURE__ */ jsx(ArrowPathIcon, { className: "mr-1 h-3.5 w-3.5" }),
            labels.rotate
          ] }),
          !secret.disabled && /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              size: "sm",
              color: "rose",
              onClick: () => {
                if (window.confirm(labels.disableConfirm)) onDisable(secret);
              },
              children: [
                /* @__PURE__ */ jsx(TrashIcon, { className: "mr-1 h-3.5 w-3.5" }),
                labels.disable
              ]
            }
          )
        ] })
      ] }),
      children: [
        secret.description && /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-slate-500 dark:text-slate-400", children: secret.description }),
        /* @__PURE__ */ jsxs("dl", { className: "mt-2 grid grid-cols-2 gap-1 text-xs text-slate-500 dark:text-slate-400", children: [
          /* @__PURE__ */ jsx("dt", { children: labels.createdAt }),
          /* @__PURE__ */ jsx("dd", { className: "text-right", children: new Date(secret.createdAt).toLocaleDateString() }),
          /* @__PURE__ */ jsx("dt", { children: labels.expiresAt }),
          /* @__PURE__ */ jsx("dd", { className: "text-right", children: secret.expiresAt ? new Date(secret.expiresAt).toLocaleDateString() : labels.neverExpires })
        ] })
      ]
    },
    secret.secretId
  )) });
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(ManagementPageLayout, { hero, content, mobileAction }),
    /* @__PURE__ */ jsx(
      GlassModal,
      {
        open: createOpen,
        onClose: () => setCreateOpen(false),
        title: labels.createTitle,
        maxWidth: "lg",
        showFormFooter: true,
        submitLabel: labels.save,
        onSubmit: (event) => {
          const formData = new FormData(event.currentTarget);
          const name = String(formData.get("name") ?? "").trim();
          const value = String(formData.get("value") ?? "");
          const secretType = String(formData.get("secretType") ?? "generic");
          const description = String(formData.get("description") ?? "").trim() || void 0;
          if (!name || !value) return;
          onCreate({ name, value, secretType, description });
          setCreateOpen(false);
        },
        children: /* @__PURE__ */ jsxs(FormGrid, { children: [
          /* @__PURE__ */ jsx(FormInput, { name: "name", label: labels.name, placeholder: labels.namePlaceholder, required: true }),
          /* @__PURE__ */ jsx(FormSelect, { name: "secretType", label: labels.type, options: typeOptions, defaultValue: "generic" }),
          /* @__PURE__ */ jsx(FormInput, { name: "value", label: labels.value, placeholder: labels.valuePlaceholder, required: true, type: "password" }),
          /* @__PURE__ */ jsx(FormTextarea, { name: "description", label: labels.description, placeholder: labels.descriptionPlaceholder, rows: 2 })
        ] })
      }
    ),
    /* @__PURE__ */ jsx(
      GlassModal,
      {
        open: rotateFor !== null,
        onClose: () => setRotateFor(null),
        title: `${labels.rotate}: ${rotateFor?.name ?? ""}`,
        maxWidth: "md",
        showFormFooter: true,
        submitLabel: labels.rotate,
        onSubmit: (event) => {
          const formData = new FormData(event.currentTarget);
          const value = String(formData.get("value") ?? "");
          if (!value || !rotateFor) return;
          onRotate(rotateFor, value);
          setRotateFor(null);
        },
        children: /* @__PURE__ */ jsx(FormGrid, { children: /* @__PURE__ */ jsx(FormInput, { name: "value", label: labels.value, placeholder: labels.valuePlaceholder, required: true, type: "password" }) })
      }
    )
  ] });
}

export { AgentsConfigPageView, AgentsIndexPageView, AgentsModelsPageView, AgentsPromptsPageView, AgentsToolDefinitionsPageView, ConnectionsPageView, CredentialsPageView, DashboardPageView, DatasourcesPageView, RulesPageView, RunTimelinePageView, TOOL_TYPES, WorkflowRunsPageView, WorkflowsPageView, jsonSchemaToParameters, parametersToJsonSchema };
//# sourceMappingURL=index.mjs.map
//# sourceMappingURL=index.mjs.map