"use client";
'use strict';

var chunkTIJJHW2Z_js = require('./chunk-TIJJHW2Z.js');
var chunkIJAKZHXX_js = require('./chunk-IJAKZHXX.js');
var chunkDJDZIRM6_js = require('./chunk-DJDZIRM6.js');
var chunkNJFRJ6YD_js = require('./chunk-NJFRJ6YD.js');
var chunkI2NZGVBG_js = require('./chunk-I2NZGVBG.js');
var chunkYXN2K77G_js = require('./chunk-YXN2K77G.js');
var chunkF54Q2YJY_js = require('./chunk-F54Q2YJY.js');
var react = require('react');
var reactRouter = require('react-router');
var outline = require('@heroicons/react/24/outline');
var jsxRuntime = require('react/jsx-runtime');

var WS_ENDPOINT = undefined.VITE_WS_ENDPOINT ?? "";
var useWebSocket = WS_ENDPOINT.length > 0;
function connectSSE(workflowId, runId, callbacks) {
  let eventSource = null;
  let cancelled = false;
  chunkF54Q2YJY_js.buildAuthenticatedApiUrl(
    `/workflows/${encodeURIComponent(workflowId)}/runs/${encodeURIComponent(runId)}/events`,
    { includeAccessToken: true }
  ).then((url) => {
    if (cancelled) return;
    eventSource = new EventSource(url);
    eventSource.addEventListener("connected", () => callbacks.onConnected());
    eventSource.addEventListener("execution", (messageEvent) => {
      try {
        callbacks.onEvent(JSON.parse(messageEvent.data));
      } catch {
      }
    });
    eventSource.addEventListener("done", (messageEvent) => {
      try {
        const data = JSON.parse(messageEvent.data);
        callbacks.onDone(data.status === "run_completed" ? "completed" : "failed");
      } catch {
        callbacks.onDone("completed");
      }
      eventSource?.close();
    });
    eventSource.addEventListener("error", () => {
      eventSource?.close();
      callbacks.onError();
    });
  }).catch(() => callbacks.onError());
  return () => {
    cancelled = true;
    eventSource?.close();
  };
}
function connectWebSocket(_workflowId, runId, callbacks) {
  const ws = new WebSocket(WS_ENDPOINT);
  ws.addEventListener("open", () => {
    ws.send(JSON.stringify({ action: "subscribe", runId }));
    callbacks.onConnected();
  });
  ws.addEventListener("message", (messageEvent) => {
    try {
      const data = JSON.parse(messageEvent.data);
      if (data.type === "run_completed" || data.type === "run_failed") {
        callbacks.onDone(data.type === "run_completed" ? "completed" : "failed");
        ws.send(JSON.stringify({ action: "unsubscribe", runId }));
        ws.close();
        return;
      }
      callbacks.onEvent(data);
    } catch {
    }
  });
  ws.addEventListener("error", () => {
    callbacks.onError();
  });
  ws.addEventListener("close", () => {
  });
  return () => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({ action: "unsubscribe", runId }));
    }
    ws.close();
  };
}
function useRunEvents(workflowId, runId) {
  const [events, setEvents] = react.useState([]);
  const [status, setStatus] = react.useState("idle");
  const [error, setError] = react.useState(null);
  const cleanupRef = react.useRef(null);
  const retriesRef = react.useRef(0);
  const connect = react.useCallback(() => {
    if (!workflowId || !runId) return;
    const connectFn = useWebSocket ? connectWebSocket : connectSSE;
    const callbacks = {
      onConnected: () => {
        setStatus("streaming");
        setError(null);
        retriesRef.current = 0;
      },
      onEvent: (event) => {
        setEvents((prev) => [...prev, event]);
      },
      onDone: (terminalStatus) => {
        setStatus(terminalStatus);
        cleanupRef.current = null;
      },
      onError: () => {
        cleanupRef.current = null;
        if (retriesRef.current < 3) {
          retriesRef.current++;
          const delay = Math.min(1e3 * Math.pow(2, retriesRef.current - 1), 5e3);
          setTimeout(connect, delay);
        } else {
          setStatus("error");
          setError("Connection lost after 3 retries");
        }
      }
    };
    cleanupRef.current = connectFn(workflowId, runId, callbacks);
  }, [workflowId, runId]);
  react.useEffect(() => {
    if (!workflowId || !runId) return;
    setEvents([]);
    setStatus("streaming");
    setError(null);
    retriesRef.current = 0;
    connect();
    return () => {
      if (cleanupRef.current) {
        cleanupRef.current();
        cleanupRef.current = null;
      }
    };
  }, [workflowId, runId, connect]);
  return {
    events,
    isStreaming: status === "streaming",
    status,
    error
  };
}
function resetWorkflowRunPresentation(actions) {
  actions.clearNodeResults();
  actions.setIsRunning(false);
}
function applyWorkflowExecutionEventToStore(actions, event) {
  switch (event.type) {
    case "run_started":
      actions.clearNodeResults();
      actions.setIsRunning(true);
      return;
    case "node_started":
      if (!event.nodeId) return;
      actions.setNodeResult(event.nodeId, {
        status: "running",
        durationMs: event.durationMs
      });
      return;
    case "node_completed":
      if (!event.nodeId) return;
      actions.setNodeResult(event.nodeId, {
        status: "success",
        data: event.outputs,
        durationMs: event.durationMs
      });
      return;
    case "node_error":
      if (!event.nodeId) return;
      actions.setNodeResult(event.nodeId, {
        status: "error",
        error: event.error,
        durationMs: event.durationMs
      });
      return;
    case "run_completed":
    case "run_failed":
      actions.setIsRunning(false);
      return;
    default:
      return;
  }
}
function useWorkflowRunPresentation(events, status) {
  const clearNodeResults = chunkNJFRJ6YD_js.useWorkflowStore((state) => state.clearNodeResults);
  const setIsRunning = chunkNJFRJ6YD_js.useWorkflowStore((state) => state.setIsRunning);
  const setNodeResult = chunkNJFRJ6YD_js.useWorkflowStore((state) => state.setNodeResult);
  react.useEffect(() => {
    if (status === "idle") {
      resetWorkflowRunPresentation({ clearNodeResults, setIsRunning, setNodeResult });
      return;
    }
    clearNodeResults();
    for (const event of events) {
      applyWorkflowExecutionEventToStore({ clearNodeResults, setIsRunning, setNodeResult }, event);
    }
    if (status === "completed" || status === "failed" || status === "error") {
      setIsRunning(false);
    } else if (status === "streaming") {
      setIsRunning(true);
    }
  }, [clearNodeResults, events, setIsRunning, setNodeResult, status]);
}

// src/hooks/use-workflow-execution.ts
function useWorkflowExecution(workflowId) {
  const [activeRunId, setActiveRunId] = react.useState(null);
  const [isLaunching, setIsLaunching] = react.useState(false);
  const stream = useRunEvents(workflowId || null, activeRunId);
  const clearNodeResults = chunkNJFRJ6YD_js.useWorkflowStore((state) => state.clearNodeResults);
  const setIsRunning = chunkNJFRJ6YD_js.useWorkflowStore((state) => state.setIsRunning);
  const setNodeResult = chunkNJFRJ6YD_js.useWorkflowStore((state) => state.setNodeResult);
  useWorkflowRunPresentation(stream.events, activeRunId ? stream.status : "idle");
  react.useEffect(() => {
    if (stream.status === "completed" || stream.status === "failed" || stream.status === "error") {
      setIsLaunching(false);
    }
  }, [stream.status]);
  const run = react.useCallback(async (inputVariables) => {
    if (!workflowId) return;
    setIsLaunching(true);
    try {
      const runRecord = await chunkF54Q2YJY_js.executeWorkflow(workflowId, inputVariables);
      setActiveRunId(runRecord.id);
    } finally {
      setIsLaunching(false);
    }
  }, [workflowId]);
  const stop = react.useCallback(() => {
    setActiveRunId(null);
    setIsLaunching(false);
    resetWorkflowRunPresentation({ clearNodeResults, setIsRunning, setNodeResult });
  }, [clearNodeResults, setIsRunning, setNodeResult]);
  react.useEffect(() => {
    setActiveRunId(null);
    setIsLaunching(false);
    resetWorkflowRunPresentation({ clearNodeResults, setIsRunning, setNodeResult });
  }, [clearNodeResults, setIsRunning, setNodeResult, workflowId]);
  return {
    isRunning: isLaunching || stream.status === "streaming",
    execute: run,
    stop,
    runId: activeRunId,
    runStatus: activeRunId ? stream.status : "idle"
  };
}
function getPublishableKey() {
  return undefined.VITE_WORKFLOW_BUILDER_PUBLISHABLE_KEY ?? "";
}
function useDatasourceLabels() {
  const t = chunkYXN2K77G_js.useTranslations("platform.datasources");
  return react.useMemo(() => {
    const keys = [
      "title",
      "subtitle",
      "addDatasource",
      "createTitle",
      "emptyTitle",
      "emptyDescription",
      "stepSelectType",
      "stepConfigure",
      "categoryRelational",
      "categoryNoSql",
      "categoryWarehouse",
      "categoryTimeSeries",
      "categoryGraph",
      "categoryKeyValue",
      "categorySearch",
      "fieldName",
      "fieldNamePlaceholder",
      "fieldHost",
      "fieldHostPlaceholder",
      "fieldPort",
      "fieldDatabase",
      "fieldDatabasePlaceholder",
      "fieldUsername",
      "fieldUsernamePlaceholder",
      "fieldPassword",
      "fieldPasswordPlaceholder",
      "fieldSchema",
      "fieldSchemaPlaceholder",
      "fieldSsl",
      "fieldReadOnly",
      "fieldReadOnlyHelp",
      "fieldConnectionString",
      "fieldConnectionStringPlaceholder",
      "fieldProjectId",
      "fieldProjectIdPlaceholder",
      "fieldDataset",
      "fieldDatasetPlaceholder",
      "fieldKeyFile",
      "fieldKeyFilePlaceholder",
      "fieldAccount",
      "fieldAccountPlaceholder",
      "fieldWarehouse",
      "fieldWarehousePlaceholder",
      "fieldRegion",
      "fieldRegionPlaceholder",
      "fieldBucket",
      "fieldBucketPlaceholder",
      "fieldToken",
      "fieldTokenPlaceholder",
      "fieldApiKey",
      "fieldApiKeyPlaceholder",
      "fieldEnvironment",
      "fieldEnvironmentPlaceholder",
      "fieldIndex",
      "fieldIndexPlaceholder",
      "fieldUrl",
      "fieldUrlPlaceholder",
      "testConnection",
      "testing",
      "connectionSuccess",
      "connectionFailed",
      "save",
      "saving",
      "cancel",
      "back",
      "enabled",
      "disabled",
      "dialect",
      "created",
      "deleted",
      "deleteConfirm"
    ];
    const labels = {};
    for (const key of keys) labels[key] = t(key);
    return labels;
  }, [t]);
}
function AgentsWorkspace({ workflowId, messages }) {
  const navigate = reactRouter.useNavigate();
  const locale = chunkYXN2K77G_js.useLocale();
  const tWorkflow = chunkYXN2K77G_js.useTranslations("agents.workflow");
  const tCommon = chunkYXN2K77G_js.useTranslations("common");
  const datasourceLabels = useDatasourceLabels();
  const { error: notifyError, success: notifySuccess } = chunkI2NZGVBG_js.useNotifications();
  const showSuccess = react.useCallback((title, message) => {
    notifySuccess(title, message);
  }, [notifySuccess]);
  const showError = react.useCallback((title, message) => {
    notifyError(title, message);
    if (message) {
      console.error("[AgentsWorkspace]", message);
    }
  }, []);
  const [isLoading, setIsLoading] = react.useState(true);
  const [loadError, setLoadError] = react.useState(null);
  const [isLoadingWorkflows, setIsLoadingWorkflows] = react.useState(true);
  const [isPublishing, setIsPublishing] = react.useState(false);
  const [workflows, setWorkflows] = react.useState([]);
  const [workflow, setWorkflow] = react.useState(null);
  const [agents, setAgents] = react.useState([]);
  const [models, setModels] = react.useState([]);
  const [tools, setTools] = react.useState([]);
  const [agentToolDefs, setAgentToolDefs] = react.useState([]);
  const [rules, setRules] = react.useState([]);
  const [datasources, setDatasources] = react.useState([]);
  const [modelConnections, setModelConnections] = react.useState([]);
  const [showDatasourceModal, setShowDatasourceModal] = react.useState(false);
  const openPipelineSettingsModal = chunkNJFRJ6YD_js.useModalStore((s) => s.openPipelineSettingsModal);
  const [showRunInputDialog, setShowRunInputDialog] = react.useState(false);
  const [showPreviewPanel, setShowPreviewPanel] = react.useState(false);
  const [isCreatingAgent, setIsCreatingAgent] = react.useState(false);
  const openSubworkflowModal = chunkIJAKZHXX_js.useSubworkflowStore((s) => s.openModal);
  const closeSubworkflowModal = chunkIJAKZHXX_js.useSubworkflowStore((s) => s.closeModal);
  const [deleteTarget, setDeleteTarget] = react.useState(null);
  const [saveStatus, setSaveStatus] = react.useState("idle");
  const latestGraphRef = react.useRef(null);
  const saveTimerRef = react.useRef(null);
  const skipInitialAutoSaveRef = react.useRef(true);
  const showRunPanel = chunkNJFRJ6YD_js.useWorkflowStore((state) => state.showRunPanel);
  const toggleRunPanel = chunkNJFRJ6YD_js.useWorkflowStore((state) => state.toggleRunPanel);
  const workflowNodes = chunkNJFRJ6YD_js.useWorkflowStore((state) => state.nodes);
  const { execute: executeWorkflowRun, stop: stopWorkflowRun, isRunning } = useWorkflowExecution(workflowId);
  const loadWorkspaceData = react.useCallback(async () => {
    setIsLoading(true);
    setLoadError(null);
    try {
      const [workflowData, agentList, modelList, agentToolDefList, ruleList, datasourceList, connectionList] = await Promise.all([
        chunkF54Q2YJY_js.getWorkflowById(workflowId),
        chunkF54Q2YJY_js.getAgentConfigsWithPrompts(),
        chunkF54Q2YJY_js.getAgentModels(),
        chunkF54Q2YJY_js.getAgentToolDefinitions().catch(() => []),
        chunkF54Q2YJY_js.getAgentRules(),
        chunkF54Q2YJY_js.getDatasources().catch(() => []),
        chunkF54Q2YJY_js.listModelProviderConnections().catch(() => [])
      ]);
      const toolResults = await Promise.all(
        agentList.map((agent) => chunkF54Q2YJY_js.getAgentTools(agent.agentId).catch(() => []))
      );
      const toolList = toolResults.flat();
      setWorkflow(workflowData);
      latestGraphRef.current = workflowData.graph;
      setAgents(agentList);
      setModels(modelList);
      setTools(toolList);
      setAgentToolDefs(agentToolDefList);
      setRules(ruleList);
      setDatasources(datasourceList);
      setModelConnections(connectionList);
    } catch (error) {
      const message = error instanceof Error ? error.message : tCommon("loadWorkspaceFailed");
      setWorkflow(null);
      setAgents([]);
      setModels([]);
      setTools([]);
      setAgentToolDefs([]);
      setRules([]);
      setDatasources([]);
      setModelConnections([]);
      setLoadError(message);
      notifyError(tCommon("serverError"), message);
    } finally {
      setIsLoading(false);
    }
  }, [workflowId]);
  const loadWorkflowList = react.useCallback(async () => {
    setIsLoadingWorkflows(true);
    try {
      const list = await chunkF54Q2YJY_js.getWorkflows();
      setWorkflows(list);
    } catch {
      setWorkflows([]);
    } finally {
      setIsLoadingWorkflows(false);
    }
  }, []);
  react.useEffect(() => {
    void loadWorkspaceData();
  }, [loadWorkspaceData]);
  react.useEffect(() => {
    void loadWorkflowList();
  }, [loadWorkflowList]);
  react.useEffect(() => {
    skipInitialAutoSaveRef.current = true;
  }, [workflowId]);
  react.useEffect(() => {
    return () => {
      if (saveTimerRef.current) {
        clearTimeout(saveTimerRef.current);
      }
    };
  }, []);
  const handleAutoSaveGraph = react.useCallback((graph) => {
    latestGraphRef.current = graph;
    if (isLoading || skipInitialAutoSaveRef.current) {
      skipInitialAutoSaveRef.current = false;
      return;
    }
    if (saveTimerRef.current) {
      clearTimeout(saveTimerRef.current);
    }
    setSaveStatus("saving");
    saveTimerRef.current = setTimeout(() => {
      void chunkF54Q2YJY_js.saveWorkflowDraft(workflowId, graph).then((updatedWorkflow) => {
        setWorkflow(updatedWorkflow);
        setWorkflows((current) => current.map((item) => item.id === updatedWorkflow.id ? updatedWorkflow : item));
        setSaveStatus("saved");
        setTimeout(() => setSaveStatus("idle"), 900);
      }).catch(() => {
        setSaveStatus("idle");
      });
    }, 800);
  }, [workflowId]);
  const handlePublish = react.useCallback(async () => {
    if (!latestGraphRef.current) return;
    const validation = chunkDJDZIRM6_js.validateWorkflowGraph(latestGraphRef.current, { locale });
    if (!validation.valid) {
      showError(tWorkflow("validationError"), validation.errors[0] ?? tWorkflow("validation"));
      return;
    }
    setIsPublishing(true);
    try {
      const published = await chunkF54Q2YJY_js.publishWorkflow(workflowId);
      setWorkflow(published);
      setWorkflows((current) => current.map((item) => item.id === published.id ? published : item));
    } finally {
      setIsPublishing(false);
    }
  }, [locale, showError, tWorkflow, workflowId]);
  const handleSelectWorkflow = react.useCallback((selected) => {
    if (selected.id === workflowId) return;
    navigate(`/workflows/edit?workflowId=${encodeURIComponent(selected.id)}`);
  }, [navigate, workflowId]);
  const handleCreateWorkflow = react.useCallback(async () => {
    const created = await chunkF54Q2YJY_js.createWorkflow({
      name: tWorkflow("defaultWorkflowName")
    });
    navigate(`/workflows/edit?workflowId=${encodeURIComponent(created.id)}`);
  }, [navigate, tWorkflow]);
  const handleDeleteWorkflow = react.useCallback((id, name) => {
    setDeleteTarget({ id, name });
  }, []);
  const confirmDelete = react.useCallback(async () => {
    if (!deleteTarget) return;
    await chunkF54Q2YJY_js.deleteWorkflow(deleteTarget.id);
    const remaining = workflows.filter((item) => item.id !== deleteTarget.id);
    if (remaining.length > 0) {
      navigate(`/workflows/edit?workflowId=${encodeURIComponent(remaining[0].id)}`);
    } else {
      navigate("/workflows");
    }
    setDeleteTarget(null);
  }, [deleteTarget, workflows, navigate]);
  const handleOpenRunDialog = react.useCallback(() => {
    const startNode = workflowNodes.find((node) => node.type === "start");
    const hasEndNode = workflowNodes.some((node) => node.type === "end");
    const hasValidStartConfig = Boolean(
      startNode && typeof startNode.data === "object" && startNode.data !== null && "config" in startNode.data && startNode.data.config && startNode.data.config.type === "start"
    );
    if (!hasValidStartConfig) {
      showError(tWorkflow("validationError"), tWorkflow("startNodeRequired"));
      return;
    }
    if (!hasEndNode) {
      showError(tWorkflow("validationError"), tWorkflow("endNodeRequired"));
      return;
    }
    setShowRunInputDialog(true);
  }, [workflowNodes, showError, tWorkflow]);
  const handleCreateAgent = react.useCallback(() => {
    setIsCreatingAgent(true);
  }, []);
  const handleCancelCreateAgent = react.useCallback(() => {
    setIsCreatingAgent(false);
  }, []);
  const handleAgentSaved = react.useCallback(async () => {
    const nextAgents = await chunkF54Q2YJY_js.getAgentConfigsWithPrompts();
    setAgents(nextAgents);
    setIsCreatingAgent(false);
  }, []);
  const handleToggleTool = react.useCallback(async (tool) => {
    try {
      const updated = await chunkF54Q2YJY_js.updateAgentTool(tool.toolId, { enabled: !tool.enabled });
      setTools((current) => current.map((item) => item.toolId === tool.toolId ? updated : item));
      showSuccess(
        tWorkflow("toolsSection"),
        updated.enabled ? tWorkflow("published") : tWorkflow("draftBadge")
      );
    } catch (error) {
      showError(
        tWorkflow("validationError"),
        error instanceof Error ? error.message : tWorkflow("publishError")
      );
    }
  }, [showError, showSuccess, tWorkflow]);
  const handleToggleRule = react.useCallback(async (rule) => {
    try {
      const updated = await chunkF54Q2YJY_js.updateAgentRule(rule.ruleId, { ...rule, enabled: !rule.enabled });
      setRules((current) => current.map((item) => item.ruleId === rule.ruleId ? updated : item));
      showSuccess(
        tWorkflow("rulesSection"),
        updated.enabled ? tWorkflow("published") : tWorkflow("draftBadge")
      );
    } catch (error) {
      showError(
        tWorkflow("validationError"),
        error instanceof Error ? error.message : tWorkflow("publishError")
      );
    }
  }, [showError, showSuccess, tWorkflow]);
  const handleCreateTool = react.useCallback(() => {
    openSubworkflowModal({ toolId: "", name: "", category: "external", enabled: true });
  }, [openSubworkflowModal]);
  const handleCreateRule = react.useCallback(() => {
  }, []);
  const handleCreateAgentTool = react.useCallback(() => {
  }, []);
  const handleConvertToSubworkflow = react.useCallback((workflow2) => {
    openSubworkflowModal({
      toolId: "",
      name: workflow2.name,
      description: workflow2.description ?? "",
      category: "external",
      enabled: true,
      config: { type: "workflow", graph: workflow2.graph }
    });
  }, [openSubworkflowModal]);
  const handleEditTool = react.useCallback((tool) => {
    openSubworkflowModal(tool);
  }, [openSubworkflowModal]);
  const handleCreateDatasource = react.useCallback(() => {
    setShowDatasourceModal(true);
  }, []);
  const handleSaveDatasource = react.useCallback(async (data) => {
    try {
      const created = await chunkF54Q2YJY_js.createDatasource(data);
      setDatasources((current) => [...current, created]);
      showSuccess(tWorkflow("dataSourcesSection"), tCommon("created") ?? "Created");
    } catch (error) {
      showError(
        tWorkflow("dataSourcesSection"),
        error instanceof Error ? error.message : tCommon("createDatasourceFailed")
      );
    }
  }, [showSuccess, showError, tWorkflow, tCommon]);
  const datasourceEntities = react.useMemo(
    () => datasources.map((ds) => ({
      id: ds.id,
      label: ds.name ?? ds.id,
      description: ds.dialect ?? "",
      defaultLimit: 100,
      fields: []
    })),
    [datasources]
  );
  const datasourceDefinitions = react.useMemo(
    () => datasources.map((ds) => ({
      id: ds.id,
      name: ds.name ?? ds.id,
      dialect: ds.dialect ?? "postgres"
    })),
    [datasources]
  );
  const paletteModelProviders = react.useMemo(() => {
    const toPaletteKey = (slug) => {
      switch (slug) {
        case "anthropic_api":
          return "anthropic";
        case "openai_api":
          return "openai";
        case "aws_bedrock":
          return "amazon";
        case "google_vertex":
          return "google";
        default:
          return slug ?? "custom";
      }
    };
    return modelConnections.map((connection) => ({
      id: connection.id,
      name: connection.name,
      provider: toPaletteKey(connection.providerSlug),
      modelCount: connection.modelFilter?.length ?? 1,
      configured: connection.enabled
    }));
  }, [modelConnections]);
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-[calc(100vh-120px)] flex-col", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "liquid-surface flex h-full flex-col overflow-hidden rounded-2xl", children: [
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-shrink-0 items-center justify-between px-5 py-3", children: [
        /* @__PURE__ */ jsxRuntime.jsx("div", { className: "shimmer h-6 w-40 rounded-lg" }),
        /* @__PURE__ */ jsxRuntime.jsx("div", { className: "shimmer h-8 w-24 rounded-lg" })
      ] }),
      /* @__PURE__ */ jsxRuntime.jsx("div", { className: "liquid-divider border-t" }),
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex min-h-0 flex-1 overflow-hidden", children: [
        /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "w-56 border-r border-white/20 p-4 dark:border-white/10", children: [
          /* @__PURE__ */ jsxRuntime.jsx("div", { className: "shimmer mb-3 h-5 w-24 rounded" }),
          /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-2", children: [1, 2, 3].map((index) => /* @__PURE__ */ jsxRuntime.jsx("div", { className: "shimmer h-10 w-full rounded-lg" }, index)) })
        ] }),
        /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex flex-1 items-center justify-center", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "shimmer h-8 w-48 rounded-lg" }) })
      ] })
    ] }) });
  }
  if (!workflow) {
    return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-[calc(100vh-120px)] items-center justify-center", children: loadError ? /* @__PURE__ */ jsxRuntime.jsx(
      chunkI2NZGVBG_js.PageErrorState,
      {
        statusCode: 500,
        title: tCommon("serverError"),
        message: loadError,
        onRetry: () => {
          void loadWorkspaceData();
        },
        retryLabel: tCommon("retry")
      }
    ) : /* @__PURE__ */ jsxRuntime.jsx(
      chunkI2NZGVBG_js.PageEmptyState,
      {
        title: tWorkflow("emptyTitle"),
        message: tWorkflow("emptyDescription"),
        iconName: "cpu-chip"
      }
    ) });
  }
  return /* @__PURE__ */ jsxRuntime.jsx(chunkNJFRJ6YD_js.WorkflowBuilderProvider, { publishableKey: getPublishableKey(), children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex h-[calc(100vh-120px)] flex-col", "data-testid": "agents-workspace", children: [
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "liquid-surface flex h-full flex-col overflow-hidden rounded-2xl", children: [
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-shrink-0 items-center justify-between px-5 py-3", children: [
        /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ jsxRuntime.jsx(
            "button",
            {
              type: "button",
              onClick: () => openPipelineSettingsModal(
                workflow.name,
                workflow.description ?? "",
                {
                  slug: workflow.slug ?? null,
                  isDraft: workflow.isDraft,
                  isActive: workflow.isActive
                }
              ),
              className: "rounded-lg px-2.5 py-1 text-sm font-semibold text-gray-900 transition-colors hover:bg-gray-100/80 dark:text-white dark:hover:bg-white/10",
              title: tWorkflow("editName"),
              children: workflow.name || tWorkflow("title")
            }
          ),
          /* @__PURE__ */ jsxRuntime.jsx(chunkI2NZGVBG_js.CopyableId, { id: workflowId, className: "text-[10px]" }),
          workflow.isDraft ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "inline-flex items-center rounded-full bg-amber-100 px-2.5 py-0.5 text-[10px] font-semibold text-amber-800 dark:bg-amber-900/30 dark:text-amber-300", children: tWorkflow("draftBadge") }) : /* @__PURE__ */ jsxRuntime.jsx("span", { className: "inline-flex items-center rounded-full bg-green-100 px-2.5 py-0.5 text-[10px] font-semibold text-green-800 dark:bg-green-900/30 dark:text-green-300", children: tWorkflow("published") }),
          /* @__PURE__ */ jsxRuntime.jsx(chunkIJAKZHXX_js.SaveStatusBadge, { status: saveStatus })
        ] }),
        /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntime.jsx(
            chunkI2NZGVBG_js.Button,
            {
              size: "xs",
              plain: true,
              onClick: () => setShowPreviewPanel((previous) => !previous),
              title: tWorkflow("previewPanel.title"),
              children: /* @__PURE__ */ jsxRuntime.jsx(outline.ChartBarIcon, { className: "h-3.5 w-3.5", "data-slot": "icon" })
            }
          ),
          isRunning ? /* @__PURE__ */ jsxRuntime.jsxs(chunkI2NZGVBG_js.Button, { size: "xs", outline: true, onClick: stopWorkflowRun, children: [
            /* @__PURE__ */ jsxRuntime.jsx(outline.StopIcon, { className: "h-3.5 w-3.5", "data-slot": "icon" }),
            tWorkflow("runPanel.stop")
          ] }) : /* @__PURE__ */ jsxRuntime.jsxs(
            chunkI2NZGVBG_js.Button,
            {
              size: "xs",
              outline: true,
              onClick: handleOpenRunDialog,
              disabled: !workflow.publishedGraph && !latestGraphRef.current,
              title: !workflow.publishedGraph && !latestGraphRef.current ? tWorkflow("noPublishedWorkflow") : void 0,
              children: [
                /* @__PURE__ */ jsxRuntime.jsx(outline.PlayIcon, { className: "h-3.5 w-3.5", "data-slot": "icon" }),
                tWorkflow("runPanel.run")
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntime.jsxs(chunkI2NZGVBG_js.Button, { gradient: true, size: "xs", onClick: () => {
            void handlePublish();
          }, disabled: isPublishing, children: [
            /* @__PURE__ */ jsxRuntime.jsx(outline.DocumentCheckIcon, { className: "h-3.5 w-3.5", "data-slot": "icon" }),
            tWorkflow("publish")
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntime.jsx("div", { className: "liquid-divider border-t" }),
      /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-4 pt-3", children: /* @__PURE__ */ jsxRuntime.jsx(
        chunkIJAKZHXX_js.WorkflowListBar,
        {
          workflows,
          activeWorkflowId: workflowId,
          isLoading: isLoadingWorkflows,
          onSelect: handleSelectWorkflow,
          onCreate: () => {
            void handleCreateWorkflow();
          },
          onDelete: handleDeleteWorkflow,
          onConvertToSubworkflow: handleConvertToSubworkflow
        }
      ) }),
      /* @__PURE__ */ jsxRuntime.jsx("div", { className: "liquid-divider border-t" }),
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex min-h-0 flex-1 overflow-hidden", children: [
        /* @__PURE__ */ jsxRuntime.jsx(
          chunkIJAKZHXX_js.NodePalette,
          {
            agents,
            tools,
            agentTools: agentToolDefs,
            rules,
            entities: datasourceEntities,
            modelProviders: paletteModelProviders,
            onCreateAgent: handleCreateAgent,
            onCreateTool: () => {
              void handleCreateTool();
            },
            onCreateAgentTool: () => {
              void handleCreateAgentTool();
            },
            onCreateRule: () => {
              void handleCreateRule();
            },
            onCreateDatasource: handleCreateDatasource
          }
        ),
        /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsxRuntime.jsx(
          chunkIJAKZHXX_js.AutoSaveWorkspace,
          {
            workflowId,
            className: "h-full w-full",
            locale,
            ...messages ? { messages } : {},
            initialGraph: workflow.graph,
            agents,
            models,
            tools,
            agentTools: agentToolDefs,
            rules,
            datasources: datasourceDefinitions,
            onLoadTables: chunkF54Q2YJY_js.getDatasourceTables,
            onLoadSchema: chunkF54Q2YJY_js.getDatasourceSchema,
            onEditTool: handleEditTool,
            onToggleTool: handleToggleTool,
            onToggleRule: handleToggleRule,
            onAgentSaved: () => {
              void handleAgentSaved();
            },
            isCreatingAgent,
            onCancelCreateAgent: handleCancelCreateAgent,
            onAutoSaveGraph: handleAutoSaveGraph,
            onGraphSnapshot: (graph) => {
              latestGraphRef.current = graph;
            },
            renderAgentModal: (props) => /* @__PURE__ */ jsxRuntime.jsx(
              chunkIJAKZHXX_js.AgentModal,
              {
                ...props,
                onSaved: () => {
                  props.onSaved();
                  void handleAgentSaved();
                },
                onPersist: async (payload) => {
                  const body = {
                    name: payload.name,
                    displayName: payload.displayName,
                    description: payload.description,
                    avatar: payload.avatar,
                    modelId: payload.modelId,
                    modelProviderId: payload.connectionId,
                    framework: payload.framework,
                    systemPrompt: payload.systemPrompt,
                    instruction: payload.systemPrompt,
                    temperature: payload.temperature,
                    maxOutputTokens: payload.maxOutputTokens,
                    maxTokens: payload.maxOutputTokens,
                    topP: payload.topP,
                    topK: payload.topK,
                    elo: payload.elo,
                    status: payload.status,
                    tags: payload.tags,
                    agentToolIds: payload.enabledToolIds
                  };
                  if (payload.agentId) {
                    await chunkF54Q2YJY_js.updateAgentConfig(payload.agentId, body);
                  } else {
                    await chunkF54Q2YJY_js.createAgentConfig(body);
                  }
                }
              }
            )
          }
        ) })
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsx(
      chunkIJAKZHXX_js.PipelineSettingsModal,
      {
        onSave: async (changes) => {
          const metadata = {
            name: changes.name,
            description: changes.description
          };
          if (changes.slug !== void 0) metadata.slug = changes.slug;
          if (changes.isDraft !== void 0) metadata.isDraft = changes.isDraft;
          if (changes.isActive !== void 0) metadata.isActive = changes.isActive;
          const updated = latestGraphRef.current ? await chunkF54Q2YJY_js.saveWorkflowDraft(workflowId, latestGraphRef.current, metadata) : await chunkF54Q2YJY_js.updateWorkflowSettings(workflowId, metadata);
          setWorkflow(updated);
          setWorkflows((current) => current.map((item) => item.id === updated.id ? updated : item));
        }
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      chunkIJAKZHXX_js.SubworkflowModal,
      {
        onMaximize: (subworkflowId) => {
          closeSubworkflowModal();
          navigate(`/workflows/edit?workflowId=${encodeURIComponent(subworkflowId)}`);
        },
        onSaved: async (saved) => {
          const isNew = !saved.toolId;
          if (isNew) {
            const created = await chunkF54Q2YJY_js.createWorkflow({
              name: saved.name,
              description: saved.description
            });
            closeSubworkflowModal();
            navigate(`/workflows/edit?workflowId=${encodeURIComponent(created.id)}`);
          } else {
            const updated = await chunkF54Q2YJY_js.updateAgentTool(saved.toolId, saved);
            setTools((current) => current.map((item) => item.toolId === saved.toolId ? updated : item));
            closeSubworkflowModal();
          }
        }
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      chunkIJAKZHXX_js.RunPanel,
      {
        open: showRunPanel,
        onClose: toggleRunPanel,
        onRun: handleOpenRunDialog,
        onStop: stopWorkflowRun
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      chunkIJAKZHXX_js.RunInputDialog,
      {
        open: showRunInputDialog,
        onClose: () => setShowRunInputDialog(false),
        onRun: (inputVariables) => {
          void executeWorkflowRun(inputVariables);
          if (!showRunPanel) {
            toggleRunPanel();
          }
        }
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      chunkIJAKZHXX_js.PreviewPanel,
      {
        open: showPreviewPanel,
        onClose: () => setShowPreviewPanel(false),
        workflowId,
        loadRuns: chunkF54Q2YJY_js.getWorkflowRuns
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      chunkTIJJHW2Z_js.DatasourceFormModal,
      {
        open: showDatasourceModal,
        onClose: () => setShowDatasourceModal(false),
        labels: datasourceLabels,
        onSave: (data) => {
          void handleSaveDatasource(data);
        }
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      chunkI2NZGVBG_js.DynamicIslandConfirm,
      {
        open: deleteTarget !== null,
        onClose: () => setDeleteTarget(null),
        onConfirm: () => {
          void confirmDelete();
        },
        title: `${tWorkflow("deleteWorkflowConfirm")} ${deleteTarget?.name ?? ""}?`
      }
    )
  ] }) });
}

exports.AgentsWorkspace = AgentsWorkspace;
exports.applyWorkflowExecutionEventToStore = applyWorkflowExecutionEventToStore;
exports.resetWorkflowRunPresentation = resetWorkflowRunPresentation;
exports.useRunEvents = useRunEvents;
exports.useWorkflowExecution = useWorkflowExecution;
exports.useWorkflowRunPresentation = useWorkflowRunPresentation;
//# sourceMappingURL=chunk-ZL6C2ZAF.js.map
//# sourceMappingURL=chunk-ZL6C2ZAF.js.map