/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as Le } from "../../chunks/runtime.js";
import { u as $e } from "../../chunks/useT9n.js";
import { LitElement as Fe, createEvent as ne, nothing as ae } from "@arcgis/lumina";
import { css as Re, html as k } from "lit";
import { unsafeHTML as De } from "lit/directives/unsafe-html.js";
import { useContextConsumer as oe } from "@arcgis/lumina/context";
import { c as Ne, b as Me } from "../../chunks/deployAppContexts.js";
import { T as D } from "../../chunks/interfaces.js";
import { m as Be } from "../../chunks/helpers.js";
import z from "@arcgis/core/config.js";
import { createRef as Pe, ref as qe } from "lit-html/directives/ref.js";
import { Annotation as y, StateGraph as Q, START as H, END as I, NodeInterrupt as le } from "@langchain/langgraph/web";
import { createAgentRuntimeState as W, sendTraceMessage as w, invokeStructuredPrompt as C, getEmbeddings as Ue, cosineSimilarity as Oe, invokeTextPrompt as ze } from "@arcgis/ai-orchestrator";
import r, { z as A } from "zod";
import * as K from "@esri/arcgis-rest-portal";
import { applyPatch as je } from "fast-json-patch";
import "@langchain/core/messages";
import { C as ce } from "../../chunks/converter.js";
import { v as j, b as V, S as Ve, g as Je } from "../../chunks/validators.js";
import { t as de, g as P, c as ue, r as pe, d as F } from "../../chunks/templates.js";
import Ge from "@arcgis/core/portal/Portal.js";
import Qe from "@arcgis/core/portal/PortalItem.js";
const He = Re`:host{display:block;height:100%}.margin-lg{margin:var(--calcite-spacing-lg)}.display-flex-row{display:flex;flex-direction:row}.assistant-split-container{display:flex;width:100%;height:calc(100vh - 78px);overflow:hidden;border-radius:10px}.assistant-panel{display:flex;flex-direction:column;height:100%;border:1px solid var(--calcite-color-surface-3);background-color:var(--calcite-color-surface-2);overflow:hidden}.chat-panel{min-width:320px}.builder-panel{min-width:320px;max-width:100%;border-left:1px solid var(--calcite-color-surface-3)}.panel-actions{display:flex;gap:8px;padding:6px;align-items:center}.builder-header,.builder-footer{padding:10px;background:var(--calcite-color-surface-1);border-bottom:1px solid var(--calcite-color-surface-3)}.builder-content{flex:1;overflow:auto;padding:12px}.builder-content pre{white-space:pre-wrap;word-wrap:break-word;max-height:100%;overflow:auto}.builder-actions{display:flex;gap:6px;align-items:center}.padding-left-10{padding-left:10px}.chat-container{display:flex;flex-direction:column;gap:0px;max-width:600px;height:75%;background-color:var(--calcite-color-surface-4);padding:1px}.chat-container_expanded{display:flex;flex-direction:column;gap:0px;max-width:100%;height:95%;background-color:var(--calcite-color-surface-1);border-radius:10px;padding:10px}.chat-panel{--calcite-color-focus: var(--calcite-color-brand);--calcite-panel-border-color: var(--calcite-color-border-2);--calcite-internal-panel-header-vertical-padding: 0px;--calcite-panel-header-content-space: 0px;border:var(--calcite-border-width-sm) solid var(--calcite-color-border-2);height:100%}.header-content{display:flex;align-items:center;gap:var(--calcite-spacing-sm);height:65px;box-sizing:border-box;padding-inline-start:var(--calcite-space-2xl)}.header-title{font-size:var(--calcite-font-size-md);font-weight:var(--calcite-font-weight-medium);color:var(--calcite-color-text-1)}.beta-chip{--calcite-chip-corner-radius: var(--calcite-corner-radius-half)}.chat-panel calcite-card,.chat-panel calcite-text-area,.chat-panel calcite-button,.chat-panel .chat-messages,.chat-panel .chat-input{--calcite-color-focus: var(--calcite-color-brand)}.assistant-followup-chip:focus{outline:2px solid var(--calcite-color-brand)}.chat-panel-heading{font-size:var(--calcite-font-size-0);font-weight:var(--calcite-font-weight-medium);color:var(--calcite-color-surface-1, var(--calcite-color-text-1))}.chat-messages{display:flex;flex-direction:column;gap:20px;padding:4px;height:100%;overflow-y:auto}.user-message{align-self:flex-end;background:var(--calcite-color-brand);border-radius:8px;max-width:90%;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-brand);--calcite-card-border-color: var(--calcite-color-brand);color:var(--calcite-color-text-inverse);text-align:left}.system-message{align-self:flex-start;background:var(--calcite-color-surface-3);border-radius:8px;max-width:90%;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-surface-4);--calcite-card-border-color: var(--calcite-color-surface-4);color:var(--calcite-color-inverse);text-align:left}.loader-message{align-self:flex-start;background:var(--calcite-color-surface-4);border-radius:8px;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-surface-4);--calcite-card-border-color: var(--calcite-color-surface-4)}.message-content{padding:0;font-size:14px}.response-message.message-content>p:first-of-type{margin-top:0}.message-content img{max-width:100%;height:auto;display:block;object-fit:contain}.message-content-pad{padding-bottom:10px;font-size:14px}.message-content-summary{padding-bottom:14px}.message-content-alignment{display:flex;align-items:center;gap:var(--calcite-spacing-md);font-size:var(--calcite-font-size--1);color:var(--calcite-color-text-1)}.padding-top-10{padding-top:10px}.padding-right-8{padding-right:8px}.padding-left-right-5{padding-right:5px;padding-left:5px}.chip-content{padding:5px 5px 5px 0}.chat-input{display:flex;flex-direction:row;flex-grow:1}.table-cell{--calcite-table-cell-background: var(--calcite-color-surface-4)}.cursor-pointer{cursor:pointer}.notice-border-color{--temp-initial-brand: var(--calcite-color-brand)}.notice-border-color calcite-notice{--calcite-color-brand: #ddd;--calcite-icon-color: var(--temp-initial-brand)}.notice-border-color calcite-notice *{--calcite-color-brand: var(--temp-initial-brand)}.solution-card{padding:5px 0;text-decoration:none;display:block;width:100%;cursor:pointer}.solution-card calcite-card{display:flex;flex-direction:column;max-width:520px;overflow:hidden;--calcite-card-corner-radius: var(--calcite-corner-radius-round) !important;--calcite-card-shadow: var(--calcite-shadow-sm);--calcite-card-background-color: var(--calcite-card-background-color) }.solution-card div[slot=thumbnail]{max-height:100%;width:100%;position:relative;&:after{content:"";position:absolute;top:0;left:0;width:100%;height:100%;transition:all .15s ease-in-out}}.solution-card div[slot=thumbnail] img{max-height:100%;width:100%;object-fit:cover}.solution-card span[slot=description]{padding-top:10px}.solution-card calcite-chip{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);visibility:hidden;pointer-events:none;opacity:0;transition:all .15s ease-in-out;z-index:9999}.solution-card:hover calcite-chip{visibility:visible;opacity:1}.solution-card:hover div[slot=thumbnail]:after{background-color:#00000080}.solution-card:hover h3{text-decoration:underline}.solution-card:focus{outline:2px solid var(--calcite-color-brand)}.references-container{padding-top:10px;display:block}.references-container.collapsed{display:none}.width-100{width:100%}.disclaimer-div{display:flex;align-items:center;gap:var(--calcite-spacing-sm);font-size:var(--calcite-font-size--0);color:var(--calcite-color-text-1)}.display-none{display:none}.chat-messages calcite-fab{position:absolute;bottom:16px;left:50%;transform:translate(-50%);z-index:999}.icon-color-background{--calcite-button-icon-color: var(--calcite-color-surface-1)}#closeAssistantButton{--calcite-action-text-color: var(--calcite-color-text-1)}.icon-color-background:focus{--calcite-color-focus: var(--calcite-color-surface-1)}@media(max-width:430px){.solution-card .solution-snippet{display:none}}.height-32-flex-auto{height:32px;flex:0 0 auto}.margin-top-0.message-content>p:first-of-type{margin-top:0}a:not(.solution-card){color:var(--calcite-link-text-color, var(--calcite-color-text-link));cursor:pointer;text-decoration:none;line-height:inherit;background-image:linear-gradient(currentColor,currentColor),linear-gradient(var(--calcite-color-brand-underline),var(--calcite-color-brand-underline));background-position-x:0%,100%;background-position-y:min(1.5em,100%);background-repeat:no-repeat,no-repeat;background-size:0% 1px,100% 1px;transition-property:background-size,color;transition-duration:var(--calcite-animation-timing, .15s);transition-timing-function:ease-in-out;outline-color:transparent;position:relative}a:not(.solution-card):hover{background-size:100% 1px,100% 1px}a:not(.solution-card):focus{outline:2px solid var(--calcite-color-brand);outline-offset:2px;outline-color:var(--calcite-color-brand)}a:not(.solution-card):active{color:var(--calcite-color-brand-press)}`;
async function v(t, e) {
  const s = Object.entries(t).find(
    ([i]) => i.endsWith(`/${e}.md`)
  );
  if (!s)
    throw new Error(
      `Prompt not found: ${e}
Available prompts:
${Object.keys(t).join(`
`)}`
    );
  return await s[1]();
}
function q(t) {
  return t?.configurable?.context?.translations;
}
function me(t) {
  if (typeof window > "u" || t.length <= 1)
    return;
  const e = t.map((i) => i.solution.id), s = t.map((i) => i.solution.title);
  window.dispatchEvent(new CustomEvent("searchTermSet", {
    detail: {
      scope: "all-solutions",
      searchTerm: ""
    }
  })), window.dispatchEvent(new CustomEvent("solutionMatchesFromAssistant", {
    detail: {
      solutionIds: e,
      solutionTitles: s
    },
    bubbles: !0,
    composed: !0
  })), window.dispatchEvent(new CustomEvent("navTabSelected", {
    detail: {
      tabType: "all-solutions"
    }
  }));
}
function ge(t) {
  if (typeof window > "u" || !t)
    return;
  const e = new CustomEvent("solutionIDFromAssistant", {
    detail: t,
    bubbles: !0,
    composed: !0
  });
  window.dispatchEvent(e);
}
const We = A.object({
  needsContext: A.boolean().describe("True when the explorer query requires added context from prior turns."),
  rewrittenQuery: A.string().min(1).describe("The final query to send to doc AI. Keep original query if no context is needed.")
}), he = /* @__PURE__ */ Object.assign({
  "./prompts/solutions_explorer_description.md": () => import("../../chunks/solutions_explorer_description.js").then((t) => t.default),
  "./prompts/transformQuery.md": () => import("../../chunks/transformQuery.js").then((t) => t.default)
});
function Ke(t) {
  return t.replace(/<sup>\[\[(\d+)\]\]\(([^)]+)\)<\/sup>/g, '<sup><a href="$2">&#91;$1&#93;</a></sup>');
}
function Ye(t) {
  return t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (e, s, i) => `<img src="${i}" alt="${s}" style="width: 100%;">`);
}
function Xe(t, e) {
  const s = [];
  return (e?.configurable?.context?.configContext.allCards ?? []).forEach((n) => {
    const o = n.title;
    if (!o)
      return;
    const a = new RegExp(`(?<![\\p{L}\\p{N}])${o}(?![\\p{L}\\p{N}])`, "giu");
    let l = !1;
    t = t.replace(a, (d, c, m) => {
      const h = m.slice(0, c);
      return /<img[^>]*alt\s*=\s*["'][^"']*$/i.test(h) ? d : (l = !0, `<a href="" target="solutionId:${n.deployCommonId}">${o}</a>`);
    }), l && s.push({
      solution: {
        title: n.title,
        id: n.deployCommonId,
        snippet: n.snippet,
        description: n.description
      },
      score: 100
    });
  }), { source: t, allMatches: s };
}
function Ze(t) {
  return t && t.helperServices.aiAssistantServices ? `${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/chat` : null;
}
function fe(t) {
  return t && t.helperServices.aiAssistantServices ? `${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/api/pre-chat` : null;
}
async function G(t, e, s) {
  const i = await fetch(e, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      token: s
    },
    body: JSON.stringify(t)
  });
  if (!i.ok)
    throw new Error(`HTTP ${i.status} calling ${e}`);
  return i.json();
}
const et = (t) => new Promise((e) => setTimeout(e, t));
async function tt(t, e) {
  const s = t.agentExecutionContext.userRequest, i = e?.configurable?.context?.lastTurnAgent, n = t.agentExecutionContext.messages ?? [];
  if (!i || n.length <= 1 || i === "explorer")
    return s;
  try {
    const o = await v(he, "transformQuery"), a = await C({
      promptText: o,
      modelTier: "fast",
      temperature: 0,
      schema: We,
      messages: n.slice(-11),
      inputVariables: { query: s, lastTurnAgent: i }
    });
    if (a.needsContext && a.rewrittenQuery.trim())
      return console.debug(`Rephrased query from "${s}" to "${a.rewrittenQuery.trim()}"`), a.rewrittenQuery.trim();
  } catch {
  }
  return s;
}
const st = y.Root({
  // Provides agentExecutionContext, outputMessage, summary, and status
  // channels with the orchestrator's standard reducers/defaults so the
  // sub-agent reports back through the same shape the orchestrator
  // persists into priorSteps.
  ...W(),
  solutionResponse: y({
    reducer: (t, e) => e ?? null,
    default: () => null
  }),
  documentSkillUrl: y({
    reducer: (t, e) => e ?? null,
    default: () => null
  }),
  // Persisted across turns via the graph checkpointer so follow-up questions
  // continue the same service conversation. Null on the very first interaction
  // or after messages are cleared.
  conversationId: y({
    reducer: (t, e) => e ?? t,
    default: () => null
  })
}), it = () => new Q(st).addNode("initializeAgent", at).addNode("askSolutionsQuestions", nt).addEdge(H, "initializeAgent").addEdge("initializeAgent", "askSolutionsQuestions").addEdge("askSolutionsQuestions", I), be = async (t, e, s, i) => {
  if (!t) return;
  const n = fe(t);
  if (!n) return;
  const a = { context: {
    kind: "DocAIAssistantRequest",
    filters: {
      products: "ArcGIS Solutions",
      persona: { persona: "apps-solutions" },
      pipeline: {
        translation: { allow: !0, language: s, use_llm: !1 }
      }
    }
  } };
  i && (a.conversationId = i), G(a, n, e ?? "");
}, nt = async (t, e) => {
  if (e?.configurable?.abortSignal?.aborted)
    return {};
  const s = q(e), i = t.documentSkillUrl;
  let n = [];
  const o = await tt(t, e);
  await w(
    { text: s.agentProgress.explorerAgentSearching },
    e
  );
  let a = await G(
    {
      message: o,
      conversationId: e?.configurable?.context?.convoId ?? void 0,
      context: {
        kind: "DocAIAssistantRequest",
        filters: {
          products: "ArcGIS Solutions",
          persona: { persona: "apps-solutions" },
          pipeline: {
            translation: { allow: !0, language: e?.configurable?.context?.configContext.locale ?? "en", use_llm: !1 }
          }
        }
      }
    },
    i,
    e?.configurable?.context?.token ?? ""
  );
  a.conversationId && e?.configurable?.context?.setConversationId && e.configurable.context.setConversationId(a.conversationId);
  let l = {
    message: a.message,
    conversationId: a.conversationId,
    hasMore: a.hasMore,
    ackSequenceNumber: a.sequenceNumber,
    inquiryId: a.inquiryId
  }, d = "";
  const c = async (h) => {
    const u = h.context?.results?.[0]?.reply ?? "";
    if (u !== "") {
      const S = Ke(u), $ = Ye(S), T = Xe($, e);
      d = T.source, n = [
        ...n,
        ...T.allMatches.filter(
          (U) => !n.some((_) => _.solution.id === U.solution.id)
        )
      ];
    }
    const f = h.context?.results?.[0]?.status?.currentStatusStep;
    if (f) {
      let S = "";
      f === 1 ? S = s.agentProgress.explorerAgentReading : f === 2 ? S = s.agentProgress.explorerAgentReviewing : f === 3 && (S = s.agentProgress.explorerAgentPreparing), await w({ text: S }, e);
    }
  };
  for (await c(a); l.hasMore; ) {
    if (e?.configurable?.abortSignal?.aborted)
      return {};
    await et(500), a = await G(
      {
        conversationId: l.conversationId,
        ackSequenceNumber: l.ackSequenceNumber,
        inquiryId: l.inquiryId
      },
      i,
      e?.configurable?.context?.token ?? ""
    ), l = {
      message: a.message,
      conversationId: a.conversationId,
      hasMore: a.hasMore,
      ackSequenceNumber: a.sequenceNumber,
      inquiryId: a.inquiryId
    }, await c(a);
  }
  return fe(e?.configurable?.context.portal) && be(
    e?.configurable?.context.portal,
    e?.configurable?.context.token ?? "",
    e?.configurable?.context.configContext.locale ?? "en",
    l.conversationId
  ), n.length && (n.length === 1 ? ge(n[0].solution.id) : me(n)), {
    outputMessage: d,
    summary: d,
    status: "success",
    solutionResponse: l,
    conversationId: l.conversationId
  };
}, at = async (t, e) => {
  let s = null;
  return t.documentSkillUrl === null && e?.configurable?.context?.portal && (s = Ze(e.configurable.context.portal)), {
    documentSkillUrl: s
  };
};
await v(he, "solutions_explorer_description");
const ye = (t) => {
  if (t && Array.isArray(t.id) && t.id.length > 0)
    return t.id[t.id.length - 1].replace("Message", "").toLowerCase();
  if (t && typeof t._getType == "function")
    try {
      return t._getType();
    } catch {
      return "human";
    }
  return "human";
}, ot = (t) => {
  const e = ye(t);
  if (t && t.kwargs)
    return {
      role: e,
      ...t.kwargs
      // Includes content, id, additional_kwargs, response_metadata, etc.
    };
  if (t && typeof t == "object") {
    const s = {
      role: e,
      content: typeof t.content == "string" ? t.content : String(t.content || "")
    };
    return t.id && (s.id = t.id), t.name && (s.name = t.name), t.additional_kwargs && (s.additional_kwargs = t.additional_kwargs), t.response_metadata && (s.response_metadata = t.response_metadata), s;
  }
  return { role: "human", content: String(t) };
}, rt = (t) => ye(t) === "human", lt = (t, e = 3) => t.filter((s) => rt(s)).slice(-e).map(ot), ct = (t, e = " ") => lt(t).map((n) => n.content).join(e).trim(), dt = { understandingRequest: "Understanding your request...", selectTemplatePrompt: "This use case could be supported in a few different ways. Choose the option that best matches what you want to accomplish.", searchingExistingSolutions: "Searching for existing solutions...", existingSolutionMatch: "I found one or more existing solutions that match your use case. These are ready-to-use solutions that may already meet your needs and can be deployed now. Do you want to continue building your own solution?", continueBuildingYes: "Yes, I want to build a new solution", continueBuildingNo: "No, I’ll review existing solutions", continueBuildingDeclined: "Sounds good. We can focus on existing solutions. Let me know if I can help answer any questions or provide more details.", creatingDesign: "Generating solution design...", updatingDesign: "Updating solution design...", applyChangeFailed: "I wasn't able to apply that change. The design was not modified. Please try rephrasing your request.", createDesignFailed: "I wasn't able to create a solution design from that request. Please try rephrasing and try again.", discardMessage: "Are you sure you want to discard your solution?", discardForNewSolution: "I can help you build a new solution, but I will need to discard your current solution design. Do you want to continue?" }, ut = {
  builderMessages: dt
};
class ve {
  constructor(e, s, i = !0) {
    this.isValid = !0, this.issues = [], this.fieldNameRegistry = null, this.response = e, this.template = s, this.newDesign = i, this.validate();
  }
  /**
   * Runs all validation checks on the response.
   */
  validate() {
    this.compareModels(), this.validateResponse();
  }
  /**
   * Compares response models against template models.
   */
  compareModels() {
    this._compareStrings(), this._compareItems(), this._compareFeatureLayers();
  }
  /**
   * Validates response properties and structure.
   */
  validateResponse() {
    this._validateSolutionProps(), this._validateItems(), this._validateFeatureLayer();
  }
  /**
   * Compares string keys and values between response and template.
   */
  _compareStrings() {
    const e = new Set(this.template.solution.strings.map((i) => i.key)), s = new Set(this.response.solution.strings.map((i) => i.key));
    e.size === s.size && [...e].every((i) => s.has(i)) || this._logIssue("String keys in llm response do not match the template.");
    for (const i of this.response.solution.strings)
      i.value || this._logIssue(`String key '${i.key}' has no value in the design. It must be populated.`);
  }
  /**
   * Compares item IDs between response and template.
   */
  _compareItems() {
    const e = new Set(this.template.items.map((i) => i.id)), s = new Set(this.response.items.map((i) => i.id));
    e.size === s.size && [...e].every((i) => s.has(i)) || this._logIssue("Item IDs in design do not match the template.");
  }
  /**
   * Compares feature layer configuration between response and template.
   */
  _compareFeatureLayers() {
    const e = this.template.featureLayer, s = this.response.featureLayer;
    if (e.itemId !== s.itemId) {
      this._logIssue(`Feature Layer itemId '${s.itemId}' does not match template '${e.itemId}'.`);
      return;
    }
    if (!e.addLayers) {
      const i = new Set(e.layers.map((o) => o.id)), n = new Set(s.layers.map((o) => o.id));
      if (!(i.size === n.size && [...i].every((o) => n.has(o))))
        this._logIssue(`Feature Layer '${e.itemId}' had its layer ids altered.`);
      else
        for (const o of e.layers)
          if (o.type) {
            const a = s.layers.find((l) => l.id === o.id);
            a && a.type !== o.type && this._logIssue(`Layer '${o.id}' type '${a.type}' does not match template type '${o.type}'. This layer type is immutable.`);
          }
    }
  }
  /**
   * Validates solution title and description.
   */
  _validateSolutionProps() {
    const e = this.response.solution.title, s = this.response.solution.description, i = j(e ?? "");
    if (i.isValid || this._logIssue(`Solution title is invalid (${i.errorType}).`), s) {
      const n = V(s, 2048, !0);
      n.isValid || this._logIssue(`Solution description is invalid (${n.errorType}).`);
    }
  }
  /**
   * Validates all items in the response.
   */
  _validateItems() {
    const e = /* @__PURE__ */ new Set([
      "Feature Layer (hosted)",
      "Feature Layer (hosted, view)"
    ]);
    for (const s of this.response.items) {
      e.has(s.type) && s.title.length > 100 && this._logIssue(`Service name '${s.title}' exceeds 100 characters.`);
      const i = j(s.title ?? "");
      if (i.isValid || this._logIssue(`Item '${s.id}' title is invalid (${i.errorType}).`), s.description) {
        const n = V(s.description, 2048, !0);
        n.isValid || this._logIssue(`Item '${s.id}' description is invalid (${n.errorType}).`);
      }
    }
  }
  /**
   * Validates feature layer structure and layers.
   */
  _validateFeatureLayer() {
    const e = this.template.featureLayer.layers;
    this.response.featureLayer.layers.length || this._logIssue("Feature layer item must contain at least one layer.");
    const s = this.response.featureLayer.layers.map((i) => i.name.toLowerCase());
    s.length !== new Set(s).size && this._logIssue(`Layer names must be unique (case-insensitive). Layer names in design: ${s}.`);
    for (const i of this.response.featureLayer.layers) {
      this._validateLayer(i, this.response.featureLayer.addLayers);
      const n = e.find((o) => o.id === i.id);
      n && this._validateRequiredFields(i, n);
    }
  }
  /**
   * Validates that all required fields from template are present in layer.
   */
  _validateRequiredFields(e, s) {
    const i = new Set(e.requiredFields.map((n) => n.name));
    for (const n of s.requiredFields)
      i.has(n.name) || this._logIssue(`Layer '${e.name}' is missing required field '${n.name}'.`);
  }
  /**
   * Validates a single layer configuration including name, description, and fields.
   */
  _validateLayer(e, s) {
    !s && e.typeMutable === !0 && e.type === "Table" && this._logIssue(
      `Layer '${e.name}' cannot be a Table. It may be a Point, Line, or Polygon.`
    );
    const i = j(e.name ?? "");
    if (i.isValid || this._logIssue(`Layer '${e.name}' name is invalid (${i.errorType}).`), e.description) {
      const n = V(e.description, 2048, !0);
      n.isValid || this._logIssue(`Layer '${e.name}' description is invalid (${n.errorType}).`);
    }
    this._validateLayerFields(e);
  }
  /**
   * Validates all fields in a layer including custom, required, and system fields.
   */
  _validateLayerFields(e) {
    const s = /* @__PURE__ */ new Set([
      "objectid",
      "globalid",
      "created_date",
      "created_user",
      "last_edited_date",
      "last_edited_user"
    ]), i = e.customFields.map((c) => c.name), n = new Set(e.requiredFields.map((c) => c.name)), o = [...new Set(
      i.filter((c) => s.has(c))
    )];
    for (const c of o)
      this._logIssue(`Layer '${e.name}' field '${c}' collides with a reserved system field name.`);
    const a = [...new Set(
      i.filter((c) => n.has(c))
    )];
    for (const c of a)
      this._logIssue(`Layer '${e.name}' field '${c}' collides with a required field name.`);
    if (!o.length && !a.length) {
      const c = e.systemFields ?? [], m = [
        ...e.customFields,
        ...e.requiredFields,
        ...c
      ].map((h) => h.name);
      m.length !== new Set(m).size && this._logIssue(`Layer '${e.name}' has duplicate fields: ${JSON.stringify(m)}.`);
    }
    const l = e.systemFields ?? [], d = [...e.customFields, ...e.requiredFields, ...l].map((c) => c.name.toLowerCase());
    this.fieldNameRegistry = new Set(d);
    for (const c of [...e.customFields, ...e.requiredFields])
      this._validateField(c);
    this.fieldNameRegistry = null;
  }
  /**
   * Generates a unique truncated field name within the 31-character limit.
   */
  _getUniqueTruncatedFieldName(e) {
    const i = this.fieldNameRegistry;
    if (!i)
      return e.slice(0, 31);
    const n = e.toLowerCase();
    i.delete(n);
    const o = e.slice(0, 31);
    let a = o, l = 1;
    for (; i.has(a.toLowerCase()); ) {
      const d = `_${l}`, c = Math.max(1, 31 - d.length);
      a = `${o.slice(0, c)}${d}`, l += 1;
    }
    return i.add(a.toLowerCase()), a;
  }
  /**
   * Validates a single field including name, type, length, and domain constraints.
   */
  _validateField(e) {
    const s = /^\p{L}/u, i = /^.[\p{L}\p{M}\p{N}_]*$/u;
    if (e.alias || this._logIssue(`Field '${e.name}' has no display name (alias).`), s.test(e.name) || this._logIssue(`Field '${e.name}' does not start with a letter.`), i.test(e.name) || this._logIssue(
      `Field '${e.name}' contains invalid characters (only letters from any writing system, numbers, and underscores are allowed; emojis and punctuation are not allowed).`
    ), e.name.length > 31)
      if (this.newDesign) {
        const n = e.name;
        e.name = this._getUniqueTruncatedFieldName(e.name), console.debug(`Field '${n}' exceeds 31 characters. Auto-fixing to '${e.name}'.`);
      } else
        this._logIssue(`Field '${e.name}' exceeds 31 characters.`);
    if (Ve.has(e.name.toLowerCase()))
      if (this.newDesign) {
        const n = e.name;
        e.name = `${n}_`, console.debug(`Field '${n}' is a SQL reserved keyword. Auto-fixing to '${e.name}'.`);
      } else
        this._logIssue(`Field '${e.name}' is a SQL reserved keyword.`);
    if (e.type === "string" && this._validateStringFieldLength(e), Array.isArray(e.choiceList) && (e.type !== "string" && this._logIssue(`Field '${e.name}' must be of type 'string' to have a domain.`), e.choiceList.length || this._logIssue(`Field '${e.name}' has an empty domain. At least one value is required.`), e.choiceList.some((n) => !n?.trim()) && this._logIssue(`A blank domain value was added to Field '${e.name}'.`), e.choiceList.length !== new Set(e.choiceList).size && this._logIssue(`Field '${e.name}' has duplicate domain values.`), e.length != null)) {
      const n = Math.max(...e.choiceList.map((o) => o.length));
      n > e.length && (this.newDesign ? (console.debug(`The choice provided for field '${e.name}' is too long. It must fit within ${e.length} characters, but the choice requires ${n} characters. Auto-fixing to ${n}.`), e.length = n) : this._logIssue(`The choice provided for field '${e.name}' is too long. It must fit within ${e.length} characters, but the choice requires ${n} characters.`));
    }
  }
  /**
   * Validates the length of a string field, silently migrating 255 -> 256 for new designs,
   * and auto-fixing or logging out-of-range values accordingly.
   */
  _validateStringFieldLength(e) {
    if (this.newDesign && e.length === 255 && (e.length = 256), typeof e.length != "number" || Number.isNaN(e.length)) {
      this._handleInvalidStringFieldLength(e, 256);
      return;
    }
    const s = e.length;
    if (!Je(s).isValid) {
      const n = s > 4e3 ? 4e3 : 256;
      this._handleInvalidStringFieldLength(e, n);
    }
  }
  /**
   * Applies an auto-fix to a string field's length on new designs, or logs an issue on update design.
   */
  _handleInvalidStringFieldLength(e, s) {
    this.newDesign ? (console.debug(`Field '${e.name}' has an invalid length. Auto-fixing to ${s}.`), e.length = s) : this._logIssue(`Field '${e.name}' length is invalid (must be a number between 1 and 4000).`);
  }
  /**
   * Records an issue and marks the validation as invalid.
   */
  _logIssue(e) {
    console.debug(e), this.issues.push(e), this.isValid = !1;
  }
}
const pt = r.object({
  key: r.string().describe("Stable key identifier for the string."),
  value: r.string().describe("Display value for the string."),
  description: r.string().describe("Explanation of where/how the string is used.")
}), mt = r.object({
  id: r.string().describe("ArcGIS item id (32 hex characters)."),
  title: r.string().describe("Item title."),
  description: r.string().describe("Item description."),
  type: r.enum([
    "Feature Layer (hosted)",
    "Feature Layer (hosted, view)",
    "Web Map",
    "Instant App",
    "Dashboard",
    "Web Experience",
    "Form",
    "Table (hosted)",
    "Table (hosted, view)",
    "Hub Site Application",
    "Hub Page",
    "CSV",
    "Data Pipeline",
    "Desktop Application Template",
    "Group",
    "Notebook",
    "QuickCapture Project"
  ]).describe("ArcGIS item type.")
}), re = r.object({
  name: r.string().describe("Field name."),
  type: r.enum(["string", "integer", "double", "date", "oid", "guid", "globalid"]).describe("Field data type."),
  alias: r.string().describe("Field alias for display."),
  description: r.string().describe("Field description."),
  choiceList: r.array(r.string()).nullable().describe(
    "List of allowed values for string fields with a controlled vocabulary. Null if unrestricted or not applicable."
  ),
  length: r.number().int().nullable().describe("Maximum string length for string fields. Null for non-string fields.")
}), gt = r.object({
  id: r.number().int().describe("Layer/table id within the feature service."),
  type: r.enum(["Point", "Polyline", "Polygon", "Table"]).describe("Layer type."),
  typeMutable: r.boolean().describe("Indicates whether the layer type can be changed."),
  name: r.string().describe("Layer/table name."),
  description: r.string().describe("Layer/table description."),
  customFields: r.array(re).describe("User/business fields specific to the solution."),
  requiredFields: r.array(re).describe("Fields required for solution functionality (e.g., relationship keys).")
}), ht = r.object({
  itemId: r.string().describe("ArcGIS item id for the feature layer."),
  addLayers: r.boolean().describe("Indicates whether new layers can be added during solution design."),
  layers: r.array(gt)
}), Y = r.object({
  response: r.string().describe("Conversational response to the user's query."),
  solution: r.object({
    itemId: r.string().nullable().describe("ArcGIS item id of the source Solution template used for deployment. Preserve the existing value exactly when known; otherwise use null."),
    title: r.string().describe("Title of the solution."),
    description: r.string().describe("Description of the solution."),
    tags: r.array(r.string()).describe("Keywords/tags associated with the solution."),
    strings: r.array(pt).describe("Localized strings/labels used by apps (dashboards, forms, etc.).")
  }),
  items: r.array(mt).describe("ArcGIS items that belong to the solution (apps, maps, layers, etc.)."),
  featureLayer: ht.describe("Primary feature layer item and its schema/layers/tables details.")
}), ft = r.object({
  op: r.enum(["add", "remove", "replace", "move", "copy"]).describe("RFC 6902 operation type."),
  path: r.string().describe("RFC 6901 JSON Pointer to the target location."),
  value: r.string().nullable().describe(`JSON-encoded value to apply (required for add and replace). Must be null — not an empty string — for remove, move, and copy operations. Serialize as a JSON string, e.g. '\\"text\\"' for a string, '[\\"a\\",\\"b\\"]' for an array, or '{\\"name\\":\\"x\\"}' for an object.`),
  from: r.string().nullable().describe("RFC 6901 JSON Pointer to the source location (required for move and copy). Must be null — not an empty string — for all other operations.")
}), bt = r.object({
  response: r.string().describe("Conversational response describing the accepted design changes."),
  patches: r.array(ft).describe("Minimal RFC 6902 patch operations needed to update the current design.")
}), yt = r.object({
  response: r.string().describe("Short, user-friendly explanation of why the requested update was not applied.")
}), vt = r.object({
  assistantResponse: r.string().describe("Natural-language response for the user."),
  isValidUpdate: r.boolean().describe("True only when the request is in scope for supported design updates.")
}), xt = r.object({
  matchedTitles: r.array(r.string()).describe("Titles of solutions that match the user's request. Empty array if no strong match.")
}), wt = r.object({
  templateId: r.string().min(1).describe("Template id from the available template list."),
  confidence: r.number().min(0).max(1).describe("Confidence score from 0 to 1 for this template match."),
  templateDescription: r.string().min(1).describe("Short action‑oriented description of the template in the user's use case/workflow, starting with a verb.")
}), St = r.object({
  assistantResponse: r.string().nullable().describe("Natural-language response for the user."),
  isValidUseCase: r.boolean().describe("True only when the request is concrete, appropriate, and has at least one matching template."),
  matchedTemplates: r.array(wt).describe("Ordered list of matching templates, best match first. Empty when no valid match exists.")
}), _t = (t) => t.length ? t.map((e, s) => `${s + 1}. ${e}`).join(`
`) : "No validation errors were provided.", It = async (t) => {
  const {
    query: e,
    validationIssues: s,
    recentMessages: i,
    fallbackMessage: n,
    promptModules: o
  } = t;
  try {
    return (await C({
      promptText: await v(o, "explainValidationFailure"),
      modelTier: "fast",
      temperature: 0,
      schema: yt,
      messages: i,
      inputVariables: {
        query: e,
        validationIssueCount: String(s.length),
        validationIssues: _t(s)
      }
    })).response?.trim() || n;
  } catch (a) {
    return console.warn(
      "Natural language response failed:",
      { error: a }
    ), n;
  }
}, X = (t) => t in F, Ct = 5, Tt = 0.8, kt = 0.15, At = "Web Mapping Application", Et = "Embeddings";
let N = null, J = null, M = null, B = null;
const Lt = "Build", E = /* @__PURE__ */ Object.assign({
  "./prompts/assessBuildRequest.md": () => import("../../chunks/assessBuildRequest.js").then((t) => t.default),
  "./prompts/assessUpdateRequest.md": () => import("../../chunks/assessUpdateRequest.js").then((t) => t.default),
  "./prompts/description.md": () => import("../../chunks/description2.js").then((t) => t.default),
  "./prompts/designSolution.md": () => import("../../chunks/designSolution.js").then((t) => t.default),
  "./prompts/explainValidationFailure.md": () => import("../../chunks/explainValidationFailure.js").then((t) => t.default),
  "./prompts/findExistingSolution.md": () => import("../../chunks/findExistingSolution.js").then((t) => t.default),
  "./prompts/updateDesign.md": () => import("../../chunks/updateDesign.js").then((t) => t.default)
}), $t = ut.builderMessages, g = (t) => t?.configurable?.abortSignal.aborted ?? !1, b = (t, e, s) => q(e)?.builderMessages?.[t] ?? $t[t], xe = (t) => {
  typeof window < "u" && window.dispatchEvent(new CustomEvent("arcgis-solution-design-update", {
    detail: t
  }));
}, Ft = async (t, e, s) => {
  if (!t) return null;
  const i = `type:"${At}" AND typekeywords:${Et} AND group:${t}`;
  return (await K.searchItems({
    q: i,
    params: e ? { token: e } : void 0,
    portal: s,
    num: 1
  }))?.results?.[0] ?? null;
};
async function Rt(t, e, s, i) {
  try {
    const n = await Ft(t, e, s);
    if (!n || g(i))
      return null;
    const o = new Qe({ id: n.id });
    return await o.load(), g(i) ? null : await o.fetchData("json");
  } catch {
    return null;
  }
}
const Dt = async (t, e, s) => {
  if (!t) return [];
  const i = `type:Solution AND typekeywords:${Lt} AND group:${t}`;
  return (await K.searchItems({
    q: i,
    params: e ? { token: e } : void 0,
    portal: s,
    num: 100
  }))?.results ?? [];
}, Nt = async (t, e, s) => {
  try {
    const i = await K.getItemData(t, {
      params: e ? { token: e } : void 0,
      portal: s
    }), n = i?.buildSolution;
    if (!n) return null;
    const o = i?.params, a = o && typeof o == "object" && !Array.isArray(o) ? o : null;
    return { buildSolution: n, params: a };
  } catch {
    return null;
  }
}, L = (t, e = {}) => {
  let s = t;
  return "itemId" in e && (s = {
    ...s,
    solution: {
      ...s.solution,
      itemId: e.itemId ?? null
    }
  }), e.sourceBuildSolution != null && (s = {
    ...s,
    sourceBuildSolution: e.sourceBuildSolution
  }), "params" in e && (s = {
    ...s,
    params: e.params ?? null
  }), "templateId" in e && (s = {
    ...s,
    templateId: e.templateId ?? null
  }), s;
}, we = (t, e) => {
  if (t == null || e == null)
    return { ok: !1, error: "design or sourceBuildSolution is null/undefined" };
  try {
    const s = structuredClone(e);
    return new ce({ buildSolution: s }).applyLlmTemplate(t), { ok: !0 };
  } catch (s) {
    return {
      ok: !1,
      error: s instanceof Error ? s.stack ?? s.message : String(s)
    };
  }
}, Z = async (t) => {
  if (J) {
    Object.entries(J).forEach(([a, l]) => {
      F[a] && (F[a].initialTemplate = l);
    });
    return;
  }
  const e = t?.configurable?.context?.token, s = _e(t), i = Ie(t);
  if (!s) {
    console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping live template hydration.");
    return;
  }
  const n = await Dt(s, e, i), o = {};
  g(t) || (await Promise.all(n.map(async (a) => {
    const l = a.properties?.templateInfo;
    if (!l || typeof l != "object") return;
    const d = l.id;
    if (typeof d != "string" || o[d]) return;
    const c = await Nt(a.id, e, i);
    if (!c || g(t))
      return;
    const { buildSolution: m, params: h } = c;
    if (typeof m == "object" && m !== null && "solution" in m) {
      const f = m.solution;
      f.thumbnailUrl = a.thumbnail ? `${i ?? "https://www.arcgis.com/sharing/rest"}/content/items/${a.id}/info/${a.thumbnail}` : void 0, f.item = a;
    }
    const u = {
      ...l,
      buildSolution: m
    };
    o[d] = L(
      new ce(u).dumpToLlmTemplate(),
      {
        itemId: a.id,
        sourceBuildSolution: structuredClone(m),
        params: h ? structuredClone(h) : null
      }
    ), F[d] = {
      ...l,
      initialTemplate: o[d]
    };
  })), J = o);
}, Se = (t) => {
  const e = t?.configurable?.context?.token;
  return typeof e != "string" || !e.trim() ? null : e;
}, _e = (t) => {
  const e = t?.configurable?.context?.configContext?.primarySolutionsGroupId;
  return typeof e != "string" || !e.trim() ? null : e;
}, Ie = (t) => {
  const e = t?.configurable?.context?.configContext?.portalURL;
  if (!(typeof e != "string" || !e.trim()))
    return `${e.replace(/\/+$/, "")}/sharing/rest`;
}, Mt = async (t) => {
  await Promise.all([
    Te(t),
    Z(t)
  ]);
}, Ce = async (t) => {
  const e = Se(t);
  (!M || e && e !== B) && (B = e ?? B, M = Mt(t).catch((i) => {
    throw M = null, B = null, i;
  })), await M;
};
async function Te(t) {
  if (N) return N;
  const e = _e(t);
  if (!e)
    return console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping embeddings load."), null;
  const s = Ie(t), i = t?.configurable?.context?.configContext?.portalURL;
  if (await new Ge(i ? { url: i } : void 0).load(), g(t))
    return null;
  const o = Se(t) ?? void 0, a = await Rt(e, o, s, t);
  return g(t) ? null : a ? (N = a.items, N) : null;
}
const Bt = () => Object.entries(F).map(([t, e]) => `ID: ${t}
Label: ${e.label}
Description: ${e.description}`).join(`

`), Pt = (t) => {
  const e = t?.configurable?.context?.solutionDesignJson;
  if (typeof e != "string" || !e.trim())
    return null;
  try {
    const s = JSON.parse(e), i = L(
      { response: "", ...s },
      { itemId: s?.solution?.itemId ?? null }
    ), n = Y.safeParse(i);
    if (!n.success)
      return null;
    const { response: o, ...a } = n.data, l = s.templateId, d = typeof l == "string" && X(l) ? l : null;
    return L(
      a,
      {
        sourceBuildSolution: s.sourceBuildSolution,
        templateId: d,
        params: s.params ?? null
      }
    );
  } catch {
    return null;
  }
}, qt = y.Root({
  ...W(),
  /** Optional human-readable template description retained for UI use. */
  templateDescription: y({
    reducer: (t, e) => typeof e == "string" || e === null ? e : t ?? null,
    default: () => null
  }),
  /** Current editable design payload being refined across turns. */
  currentDesign: y({
    reducer: (t = null, e) => e === void 0 ? t : e ?? null,
    default: () => null
  }),
  /** Initial request assessment produced by the intake prompt. */
  assessment: y({
    reducer: (t = null, e) => e === void 0 ? t : e ?? null,
    default: () => null
  }),
  /** Template selected automatically or by human-in-the-loop choice. */
  selectedTemplate: y({
    reducer: (t = null, e) => e === void 0 ? t : e ?? null,
    default: () => null
  }),
  /** Update request assessment produced when an active design exists. */
  updateAssessment: y({
    reducer: (t = null, e) => e === void 0 ? t : e ?? null,
    default: () => null
  }),
  /** Existing solution matches surfaced before building a new solution. */
  existingMatches: y({
    reducer: (t = [], e) => e === void 0 ? t : e ?? [],
    default: () => []
  }),
  /** User decision for whether to continue building after existing matches are shown. */
  continueBuilding: y({
    reducer: (t = null, e) => e === void 0 ? t : e ?? null,
    default: () => null
  })
}), Ut = (t, e) => {
  if (g(e))
    return {};
  const s = Pt(e), i = s?.templateId ?? null, n = {};
  return JSON.stringify(t.currentDesign) !== JSON.stringify(s) && (n.currentDesign = s), i && t.selectedTemplate !== i && (n.selectedTemplate = i), n;
}, Ot = async (t, e) => {
  if (g(e))
    return {};
  await w({ text: b("understandingRequest", e) }, e), await Ce(e);
  const s = t.agentExecutionContext.userRequest, i = Bt(), n = t.agentExecutionContext.messages.slice(-11), o = await C({
    promptText: await v(E, "assessBuildRequest"),
    modelTier: "advanced",
    temperature: 0,
    schema: St,
    messages: n,
    inputVariables: { query: s, availableTemplates: i }
  }), a = o.matchedTemplates.filter(
    (u) => X(u.templateId)
  ), l = {
    ...o,
    matchedTemplates: a
  }, [d, c] = a, h = !!d && d.confidence >= Tt && (c === void 0 || d.confidence - c.confidence >= kt) ? d.templateId : null;
  return {
    assessment: l,
    selectedTemplate: h,
    existingMatches: [],
    continueBuilding: null
  };
}, zt = (t) => {
  const e = t.assessment?.assistantResponse ?? "";
  return {
    outputMessage: e,
    summary: e,
    status: "success"
  };
}, jt = async (t, e) => {
  if (g(e))
    return {};
  const { currentDesign: s } = t;
  if (!s)
    return {
      updateAssessment: {
        assistantResponse: "",
        isValidUpdate: !0
      }
    };
  await w({ text: b("understandingRequest", e) }, e);
  const i = t.agentExecutionContext.userRequest, n = t.agentExecutionContext.messages.slice(-11);
  return {
    updateAssessment: await C({
      promptText: await v(E, "assessUpdateRequest"),
      modelTier: "advanced",
      temperature: 0,
      schema: vt,
      messages: n,
      inputVariables: {
        currentDesign: JSON.stringify(de(s)),
        query: i
      }
    })
  };
}, Vt = (t, e) => {
  const s = t.updateAssessment?.assistantResponse ?? b("applyChangeFailed", e);
  return {
    outputMessage: s,
    summary: s,
    status: "success"
  };
}, Jt = (t, e) => {
  if (g(e))
    return {};
  const { hitlResponse: s } = e.configurable, i = "selectTemplate", n = t.assessment?.matchedTemplates.filter(
    (c) => X(c.templateId)
  ) ?? [], o = n.map((c) => `${c.templateDescription}`);
  if (s?.agentId !== "solutionBuilder" || s.id !== i) {
    const c = {
      agentId: "solutionBuilder",
      id: i,
      kind: "singleSelection",
      message: b("selectTemplatePrompt", e),
      metadata: [...o]
    };
    throw new le(c);
  }
  const a = String(s.payload ?? ""), l = o.findIndex((c) => c === a);
  return {
    selectedTemplate: (l >= 0 ? n[l] : void 0)?.templateId ?? n[0]?.templateId ?? null
  };
}, Gt = async (t, e) => {
  if (g(e))
    return {};
  await w({ text: b("searchingExistingSolutions", e) }, e);
  const s = t.agentExecutionContext.userRequest, i = ct(t.agentExecutionContext.messages) || s, n = await Te(e);
  if (g(e))
    return {};
  if (!n)
    return console.warn("Solutions Search: failed to load solution embeddings cache; skipping search."), { existingMatches: [] };
  if (!n.length)
    return { existingMatches: [] };
  const [o] = await Ue([i]);
  if (g(e))
    return {};
  const a = n.map((u) => ({
    solution: u,
    score: Oe(o, u.embedding)
  }));
  a.sort((u, f) => f.score - u.score);
  const l = a.slice(0, Ct);
  if (!l.length)
    return { existingMatches: [] };
  const d = l.map(({ solution: u }) => `${u.title}
Snippet: ${u.snippet}
Description: ${u.description}`).join(`

`), c = t.agentExecutionContext.messages.slice(-11);
  return { existingMatches: (await C({
    promptText: await v(E, "findExistingSolution"),
    modelTier: "fast",
    temperature: 0,
    schema: xt,
    messages: c,
    inputVariables: { query: s, candidates: d }
  })).matchedTitles.map((u) => l.find(({ solution: f }) => f.title === u)).filter((u) => u !== void 0) };
}, Qt = (t, e) => {
  if (g(e))
    return {};
  const { existingMatches: s } = t, { hitlResponse: i } = e.configurable, n = `confirmExistingSolution:${s[0].solution.id}`;
  if (i?.agentId !== "solutionBuilder" || i.id !== n) {
    s.length === 1 ? ge(s[0].solution.id) : me(s);
    const d = b("existingSolutionMatch", e), c = [
      b("continueBuildingYes", e),
      b("continueBuildingNo", e)
    ], m = {
      agentId: "solutionBuilder",
      id: n,
      kind: "singleSelection",
      message: d,
      metadata: c
    };
    throw new le(m);
  }
  const o = String(i.payload ?? "").trim(), a = b("continueBuildingNo", e);
  return { continueBuilding: o !== a };
}, Ht = (t, e) => {
  const s = b("continueBuildingDeclined", e);
  return {
    outputMessage: s,
    summary: s,
    status: "success"
  };
}, ke = async (t, e) => {
  if (g(e))
    return {};
  if (await Ce(e), g(e))
    return {};
  const { currentDesign: s } = t, i = t.agentExecutionContext.userRequest;
  await w({ text: b("creatingDesign", e) }, e);
  let n = P(t.selectedTemplate);
  if (n?.initialTemplate || (await Z(e), n = P(t.selectedTemplate)), g(e))
    return {};
  if (!n?.initialTemplate)
    throw new Error("No hydrated templates are available for solution design.");
  const o = L(
    s ?? n.initialTemplate,
    {
      itemId: (s ?? n.initialTemplate)?.solution?.itemId ?? null,
      sourceBuildSolution: s?.sourceBuildSolution ?? n.initialTemplate.sourceBuildSolution,
      params: s?.params ?? n.initialTemplate.params ?? null
    }
  ), a = t.agentExecutionContext.messages.slice(-11), l = await C({
    promptText: await v(E, "designSolution"),
    modelTier: "advanced",
    temperature: 0,
    schema: Y,
    messages: a,
    inputVariables: {
      currentDesign: JSON.stringify(ue(o)),
      templateInstructions: n.instructions,
      query: i
    }
  });
  if (await w({ text: " of design solution 1" }, e), g(e))
    return {};
  const { response: d, featureLayer: c, ...m } = l, h = pe(
    c,
    o.featureLayer
  ), u = L(
    { ...m, featureLayer: h },
    {
      itemId: o?.solution?.itemId,
      sourceBuildSolution: o.sourceBuildSolution,
      templateId: t.selectedTemplate ?? null,
      params: o.params ?? null
    }
  ), f = new ve(u, n.initialTemplate);
  if (!f.isValid)
    return console.warn(
      "[SolutionBuilder] designSolution validation failed:",
      { issues: f.issues, llmResponse: l }
    ), {
      outputMessage: b("createDesignFailed", e)
    };
  const S = u.sourceBuildSolution, $ = we(u, S);
  if (!$.ok) {
    console.warn(
      "[SolutionBuilder] designSolution Esri JSON conversion failed:",
      { error: $.error, llmResponse: l, design: u }
    );
    const T = b("createDesignFailed", e);
    return {
      outputMessage: T,
      summary: T,
      status: "success"
    };
  }
  return g(e) ? {} : (xe(u), {
    outputMessage: d,
    summary: d,
    status: "success",
    currentDesign: u
  });
}, Wt = async (t, e) => {
  if (g(e))
    return {};
  const { currentDesign: s } = t;
  if (!s)
    return ke(t, e);
  const i = t.agentExecutionContext.userRequest, n = t.agentExecutionContext.messages.slice(-11);
  await w({ text: b("updatingDesign", e) }, e);
  let o;
  try {
    o = await C({
      promptText: await v(E, "updateDesign"),
      modelTier: "advanced",
      temperature: 0,
      schema: bt,
      messages: n,
      inputVariables: {
        currentDesign: JSON.stringify(de(s)),
        query: i
      }
    });
  } catch (p) {
    console.warn("[SolutionBuilder] updateDesign structured prompt failed:", p);
    const x = b("applyChangeFailed", e);
    return {
      outputMessage: x,
      summary: x,
      status: "success"
    };
  }
  const { response: a, patches: l } = o;
  if (!l || l.length === 0)
    return {
      outputMessage: a,
      summary: a,
      status: "success"
    };
  const d = (p) => {
    try {
      return JSON.parse(p);
    } catch {
      const x = p.replace(/[\u0000-\u001F]/g, (ie) => {
        switch (ie) {
          case "\b":
            return "\\b";
          case "\f":
            return "\\f";
          case `
`:
            return "\\n";
          case "\r":
            return "\\r";
          case "	":
            return "\\t";
          default:
            return "\\u" + ie.charCodeAt(0).toString(16).padStart(4, "0");
        }
      });
      try {
        return JSON.parse(x);
      } catch {
        return p;
      }
    }
  }, m = [...l.map((p) => ({
    op: p.op,
    path: p.path.replace(/\/+$/, ""),
    ...p.value != null && p.value !== "" ? { value: d(p.value) } : {},
    ...p.from != null && p.from !== "" ? { from: p.from } : {}
  }))].sort((p, x) => p.op !== "remove" || x.op !== "remove" ? 0 : x.path.localeCompare(p.path, void 0, { numeric: !0 })), h = structuredClone(
    ue(s)
  );
  try {
    je(h, m, !0);
  } catch (p) {
    console.warn(
      "[SolutionBuilder] updateDesign JSON patch failed:",
      { error: p, llmResponse: o, patches: m, patchTarget: h }
    );
    const x = b("applyChangeFailed", e);
    return {
      outputMessage: x,
      summary: x,
      status: "success"
    };
  }
  const u = L(
    { response: "", ...h },
    { itemId: s.solution?.itemId ?? null }
  ), f = Y.safeParse(u);
  if (!f.success) {
    console.warn(
      "[SolutionBuilder] updateDesign schema validation failed:",
      { errors: f.error.issues, llmResponse: o, patchedDesign: u }
    );
    const p = b("applyChangeFailed", e);
    return {
      outputMessage: p,
      summary: p,
      status: "success"
    };
  }
  const { response: S, featureLayer: $, ...T } = f.data, U = pe(
    $,
    s.featureLayer
  ), _ = L(
    { ...T, featureLayer: U },
    {
      itemId: s.solution?.itemId,
      sourceBuildSolution: s.sourceBuildSolution,
      templateId: s.templateId ?? t.selectedTemplate ?? null,
      params: s.params ?? null
    }
  );
  let R = P(t.selectedTemplate);
  if (R?.initialTemplate || (await Z(e), R = P(t.selectedTemplate)), g(e))
    return {};
  if (!R?.initialTemplate)
    throw new Error("No hydrated templates are available for solution design.");
  const O = new ve(_, R.initialTemplate, !1);
  if (!O.isValid) {
    console.warn(
      "[SolutionBuilder] updateDesign validation failed:",
      { issues: O.issues, llmResponse: o, patchedDesign: _ }
    );
    const p = await It({
      query: i,
      validationIssues: O.issues,
      recentMessages: n,
      fallbackMessage: b("applyChangeFailed", e),
      promptModules: E
    });
    return {
      outputMessage: p,
      summary: p,
      status: "success"
    };
  }
  const Ee = _.sourceBuildSolution, se = we(_, Ee);
  if (!se.ok) {
    console.warn(
      "[SolutionBuilder] updateDesign Esri JSON conversion failed:",
      { error: se.error, llmResponse: o, design: _ }
    );
    const p = b("applyChangeFailed", e);
    return {
      outputMessage: p,
      summary: p,
      status: "success"
    };
  }
  return g(e) ? {} : (xe(_), {
    outputMessage: a,
    summary: a,
    status: "success",
    currentDesign: _
  });
}, Kt = (t) => t.currentDesign !== null ? "assessUpdateRequest" : "assessBuildRequest", Yt = (t) => !t.updateAssessment || !t.updateAssessment.isValidUpdate ? "invalidUpdateExit" : "updateDesign", Xt = (t) => !t.assessment || !t.assessment.isValidUseCase ? "invalidBuildExit" : !t.selectedTemplate && t.assessment.matchedTemplates.length > 1 ? "selectTemplateHIL" : "findExistingSolutions", Zt = (t) => t.existingMatches.length > 0 ? "confirmContinueBuildingHIL" : "designSolution", es = (t) => t.continueBuilding === !1 ? "declineContinueBuildingExit" : "designSolution", ts = () => new Q(qt).addNode("syncCurrentDesignFromContext", Ut).addNode("assessBuildRequest", Ot).addNode("assessUpdateRequest", jt).addNode("invalidBuildExit", zt).addNode("invalidUpdateExit", Vt).addNode("selectTemplateHIL", Jt).addNode("findExistingSolutions", Gt).addNode("confirmContinueBuildingHIL", Qt).addNode("declineContinueBuildingExit", Ht).addNode("designSolution", ke).addNode("updateDesign", Wt).addEdge(H, "syncCurrentDesignFromContext").addConditionalEdges("syncCurrentDesignFromContext", Kt, {
  assessUpdateRequest: "assessUpdateRequest",
  assessBuildRequest: "assessBuildRequest"
}).addConditionalEdges("assessUpdateRequest", Yt, {
  invalidUpdateExit: "invalidUpdateExit",
  updateDesign: "updateDesign"
}).addConditionalEdges("assessBuildRequest", Xt, {
  invalidBuildExit: "invalidBuildExit",
  selectTemplateHIL: "selectTemplateHIL",
  findExistingSolutions: "findExistingSolutions"
}).addEdge("invalidBuildExit", I).addEdge("invalidUpdateExit", I).addEdge("selectTemplateHIL", "findExistingSolutions").addConditionalEdges("findExistingSolutions", Zt, {
  confirmContinueBuildingHIL: "confirmContinueBuildingHIL",
  designSolution: "designSolution"
}).addConditionalEdges("confirmContinueBuildingHIL", es, {
  declineContinueBuildingExit: "declineContinueBuildingExit",
  designSolution: "designSolution"
}).addEdge("declineContinueBuildingExit", I).addEdge("designSolution", I).addEdge("updateDesign", I);
await v(E, "description");
const ss = A.object({
  tool: A.enum(["explorer", "builder", "other"]).describe("The selected tool based on the user's query."),
  confidence: A.number().min(0).max(1).describe("A confidence score (0.00–1.00)."),
  rationale: A.string().min(1).describe("A brief rationale for the tool choice (≤140 characters)")
}), ee = /* @__PURE__ */ Object.assign({
  "./prompts/assistantResponse.md": () => import("../../chunks/assistantResponse.js").then((t) => t.default),
  "./prompts/classifyIntent.md": () => import("../../chunks/classifyIntent.js").then((t) => t.default),
  "./prompts/description.md": () => import("../../chunks/description.js").then((t) => t.default)
}), te = (t, e) => {
  const s = t?.configurable?.context?.setLastTurnAgent;
  typeof s == "function" && s(e);
  const i = new CustomEvent("assistantProcessing", {
    detail: { finished: !0, agent: e }
  });
  window.dispatchEvent(i);
}, Ae = y.Root({
  ...W(),
  selectedTool: y({
    reducer: (t, e) => e ?? null,
    default: () => null
  }),
  intentRationale: y({
    reducer: (t, e) => e ?? null,
    default: () => null
  })
}), is = async (t, e) => {
  if (e?.configurable?.abortSignal?.aborted)
    return {};
  const s = q(e);
  await w(
    { text: s?.builderMessages.understandingRequest },
    e
  );
  const i = t.agentExecutionContext.userRequest, n = t.agentExecutionContext.messages.slice(-11), o = e?.configurable?.context?.solutionDesignJson;
  let a = !1;
  if (typeof o == "string" && o.trim())
    try {
      a = JSON.parse(o).solution != null;
    } catch {
      a = !1;
    }
  const l = await v(ee, "classifyIntent"), d = await C({
    promptText: l,
    modelTier: "advanced",
    temperature: 0,
    schema: ss,
    messages: n,
    inputVariables: { query: i, activeSolutionDesign: a }
  });
  return {
    selectedTool: d.tool,
    intentRationale: d.rationale
  };
}, ns = async (t, e) => {
  if (e?.configurable?.abortSignal?.aborted)
    return {};
  const i = await it().compile().invoke(t, e);
  return te(e, "explorer"), i;
}, as = async (t, e) => {
  if (e?.configurable?.abortSignal?.aborted)
    return {};
  const i = await ts().compile().invoke(t, e);
  return te(e, "builder"), i;
}, os = async (t, e) => {
  if (e?.configurable?.abortSignal?.aborted)
    return {};
  const s = q(e), i = t.agentExecutionContext.userRequest, n = t.intentRationale ?? "No rationale available.";
  await w(
    { text: s?.executingSolutionsAssistantAgent },
    e
  );
  const o = await v(ee, "assistantResponse"), a = t.agentExecutionContext.messages.slice(-11), l = await ze({
    promptText: o,
    modelTier: "advanced",
    temperature: 0,
    messages: a,
    inputVariables: { query: i, rationale: n }
  });
  return te(e, "assistant"), {
    outputMessage: l,
    summary: l,
    status: "success"
  };
}, rs = (t) => t.selectedTool ?? "other", ls = () => new Q(Ae).addNode("classifyIntent", is).addNode("routeToExplorer", ns).addNode("routeToBuilder", as).addNode("assistantResponse", os).addEdge(H, "classifyIntent").addConditionalEdges("classifyIntent", rs, {
  explorer: "routeToExplorer",
  builder: "routeToBuilder",
  other: "assistantResponse"
}).addEdge("routeToExplorer", I).addEdge("routeToBuilder", I).addEdge("assistantResponse", I), cs = await v(ee, "description"), ds = {
  id: "solutionsAssistant",
  name: "Solutions Assistant Agent",
  description: cs,
  createGraph: ls,
  workspace: Ae
}, us = "https://links.esri.com/solutions/agol-organizational-account", ps = "https://links.esri.com/solutions/configure-assistants";
class ms extends Fe {
  constructor() {
    super(), this.open = !1, this.userFirstName = "", this.builderVisible = !1, this.hasActiveBuilderDesign = !1, this._conversationId = void 0, this._lastTurnAgent = void 0, this._orgSettings = {
      aiAssistantsEnabled: !1,
      blockBetaApps: !0,
      colocateCompute: !1
    }, this._suggestedPrompts = [], this._hasInteracted = !1, this._isMobile = window.innerWidth <= 800, this._translations = $e({ name: "arcgis-solutions-assistant", blocking: !0 }), this._builderWidth = 48, this._solutionDesignJson = '{ "solution": null }', this._isAssistantBusy = !1, this._isBuilderBusy = !1, this._preChatCheck = !1, this._showNewChatConfirm = !1, this._assistantRef = Pe(), this._configContextConsumer = oe({
      context: Ne,
      subscribe: !0,
      callback: (e) => {
        e?.portalURL && (z.portalUrl = e.portalURL), e?.userSession && !this.userFirstName && this._loadUserFirstName(), e?.authentication?.PortalSubset?.orgSettings && (this._orgSettings = e?.authentication?.PortalSubset?.orgSettings);
      }
    }), this._builderDesignContextConsumer = oe({
      context: Me,
      subscribe: !0,
      callback: (e) => {
        e?.design && (this._solutionDesignJson = JSON.stringify(e.design, null, 2));
      }
    }), this._handleResize = () => {
      this._isMobile = window.innerWidth <= 800;
    }, this._chatStartTime = null, this._handleAssistantProcessingFinished = (e) => {
      const s = e;
      if (s.detail?.finished && this._chatStartTime !== null) {
        const i = Be(this._chatStartTime);
        this._telemetry?.logEvent({
          category: D.ASSISTANT,
          action: "Chat",
          dimensions: [s.detail.agent],
          metrics: [i]
        }), this._chatStartTime = null, this.assistantProcessing.emit(!1);
      }
    }, this.closeAssistant = ne(), this.assistantProcessing = ne(), this._handleAssistantLinkClick = (e) => {
      const s = e.composedPath().find((i) => i instanceof HTMLAnchorElement);
      if (s?.href)
        if (e.preventDefault(), s.target.indexOf("solutionId:") > -1) {
          const i = s.target.split("solutionId:")[1];
          this._emitItemIdFromAI(i);
        } else
          window.open(s.href, "_blank", "noopener,noreferrer");
    }, this._onSolutionDesignUpdate = (e) => {
      const i = e.detail;
      this._solutionDesignJson = i ? JSON.stringify(i, null, 2) : '{ "solution": null }';
    }, this._handleSignIn = () => {
      this._configContextConsumer.value?.authentication?.signIn("aiOpen");
    }, this._checkURLOpenParameter = () => {
      this.open = this._configContextConsumer.value?.authentication?.SignInParam === "aiOpen" || this.open;
    }, this.listenOn(window, "arcgisFeedback", (e) => {
      const s = e.detail, { agentPicked: i, taskAssigned: n, userMessage: o } = this._parseAgentPickedAndTask(s);
      this._sendFeedback(s.content, o ?? n ?? "", s.feedback?.positive ? "Good" : s.feedback?.positive == "Bad" ? "Bad" : "N/A", i ?? "");
    }), this.listenOn(window, "clearAssistantConversation", () => {
      this._clearConversation();
    });
  }
  static {
    this.properties = { open: 5, userFirstName: 1, builderVisible: 5, hasActiveBuilderDesign: 5, _conversationId: 16, _lastTurnAgent: 16, _orgSettings: 16, _suggestedPrompts: 16, _hasInteracted: 16, _isMobile: 16, _translations: 16, _builderWidth: 16, _solutionDesignJson: 16, _isAssistantBusy: 16, _isBuilderBusy: 16, _preChatCheck: 16, _showNewChatConfirm: 16 };
  }
  static {
    this.styles = He;
  }
  get _telemetry() {
    return this._configContextConsumer.value?.telemetrySession;
  }
  connectedCallback() {
    super.connectedCallback(), window.addEventListener("arcgis-solution-design-update", this._onSolutionDesignUpdate), this.el.addEventListener("click", this._handleAssistantLinkClick), window.addEventListener("resize", this._handleResize), window.addEventListener("assistantProcessing", this._handleAssistantProcessingFinished), this._builderDesignContextConsumer;
  }
  disconnectedCallback() {
    window.removeEventListener("arcgis-solution-design-update", this._onSolutionDesignUpdate), this.el.removeEventListener("click", this._handleAssistantLinkClick), window.removeEventListener("resize", this._handleResize), window.removeEventListener("assistantProcessing", this._handleAssistantProcessingFinished), super.disconnectedCallback();
  }
  loaded() {
    this._checkURLOpenParameter();
  }
  load() {
    z.applicationName = "Solutions", this._configContextConsumer.value?.portalURL && (z.portalUrl = this._configContextConsumer.value.portalURL);
  }
  firstUpdated(e) {
    this._loadUserFirstName();
  }
  willUpdate(e) {
    e.has("open") && this.open && window.dispatchEvent(new CustomEvent("openAssistant")), this._configContextConsumer.value?.authentication && this._configContextConsumer.value?.userSession?.token && (this._preChatCheck || (be(this._configContextConsumer.value?.authentication.Portal, this._configContextConsumer.value?.userSession?.token, this._configContextConsumer.value?.locale ?? "en"), this._preChatCheck = !0)), this._configContextConsumer.value?.userSession?.token && this._configContextConsumer.value?.authentication?.CanUseAI;
  }
  _renderNoSign() {
    return k`<calcite-notice class="margin-lg" open scale=m icon=effects kind=info><div slot=message>${this._translations.signInMessage}</div><calcite-link @click=${this._handleSignIn} slot=link title=${this._translations.signInMessage ?? ae} class="padding-top-10">${this._translations.signIn}</calcite-link></calcite-notice>`;
  }
  _renderNoPermission() {
    return k`<calcite-notice class="margin-lg" open scale=m icon=effects kind=info><div slot=title>${this._translations.noPermissionTitle}</div><div slot=message class="padding-top-10">${De(this._translations.noPermissionMessage.replace("{{orgUrl}}", us).replace("{{configAI}}", ps))}</div></calcite-notice>`;
  }
  render() {
    let e = this._suggestedPrompts.length > 0 ? this._suggestedPrompts : this._hasInteracted ? [] : Object.values(this._translations.defaultFollowUpQuestions);
    return this._suggestedPrompts.length > 0 ? e = this._suggestedPrompts : this._hasInteracted || (e = [...Object.values(this._translations.defaultFollowUpQuestions)]), k`<calcite-panel class="chat-panel"><div class="header-content" slot=header-content><span class="header-title">${this._translations.solutionAssistantTitle}</span></div>${this._configContextConsumer.value?.userSession?.token ? this._configContextConsumer.value?.authentication?.CanUseAI ? k`${!this._isMobile && k`<calcite-action id=solutionBuilderAction icon=pencil-square .text=${this._translations.tooltips.builder} text-enabled .indicator=${this.hasActiveBuilderDesign} .disabled=${!this.hasActiveBuilderDesign} .active=${this.builderVisible} selection-appearance=highlight @click=${() => {
      this._telemetry?.logEvent({
        category: D.ASSISTANT,
        action: "Toggle Builder Panel",
        dimensions: [this.builderVisible ? "Close" : "Open"]
      }), window.dispatchEvent(new CustomEvent("toggleSolutionBuilder"));
    }} scale=m slot=header-actions-end></calcite-action>` || ""}${!this._isMobile && k`<calcite-tooltip placement=bottom reference-element=solutionBuilderAction><span>${this._translations.tooltips.solutionBuilder}</span></calcite-tooltip>` || ""}<arcgis-assistant reference-element copy-enabled feedback-enabled heading description entry-message=${this._translations.defaultStartUpMessage ?? ae} .suggestedPrompts=${e} @arcgisSubmit=${(s) => {
      console.log("arcgis submit: ", s.detail), this._suggestedPrompts = [], e = [], this._hasInteracted = !0, this._chatStartTime = Date.now(), this.assistantProcessing.emit(!0);
    }} @arcgisFeedback=${(s) => {
      s.detail;
    }} ${qe(this._assistantRef)}><calcite-button appearance=transparent id=newChatButton icon-start=speech-bubble-plus kind=neutral .label=${this._translations.tooltips.newChat} @click=${() => {
      this.hasActiveBuilderDesign ? this._showNewChatConfirm = !0 : (this._telemetry?.logEvent({
        category: D.ASSISTANT,
        action: "New Chat",
        dimensions: ["No Active Design"]
      }), this._clearConversation());
    }} round scale=m slot=entry-actions-start>${this._translations.tooltips.newChat}</calcite-button><arcgis-assistant-agent .agent=${ds} .context=${{
      token: this._configContextConsumer.value?.userSession?.token,
      configContext: this._configContextConsumer.value,
      convoId: this._conversationId,
      portal: this._configContextConsumer.value?.authentication.Portal,
      assistantRef: this._assistantRef,
      translations: this._translations,
      solutionDesignJson: this._solutionDesignJson,
      lastTurnAgent: this._lastTurnAgent,
      setConversationId: (s) => {
        this._conversationId = s;
      },
      setLastTurnAgent: (s) => {
        this._lastTurnAgent = s;
      },
      clearSuggestedPrompts: () => {
        this._suggestedPrompts = [];
      }
    }}></arcgis-assistant-agent></arcgis-assistant><div slot=footer class="disclaimer-div width-100"><calcite-chip class="beta-chip" appearance=solid kind=neutral .label=${this._translations.betaTag} scale=s>${this._translations.betaTag}</calcite-chip><span>${this._translations.disclaimerMessage} <a href=https://links.esri.com/solutions/security-concern rel="noopener noreferrer" target=_blank>${this._translations.reportConcern}</a></span></div>` : this._renderNoPermission() : this._renderNoSign()}${this._showNewChatConfirm && k`<calcite-dialog close-disabled escape-disabled .heading=${this._translations.newConversationConfirmTitle} modal open outside-close-disabled>${this._translations.builderMessages.discardMessage}<calcite-button appearance=outline @click=${() => {
      this._showNewChatConfirm = !1;
    }} slot=footer-end>${this._translations.cancel}</calcite-button><calcite-button appearance=solid kind=danger @click=${() => {
      this._telemetry?.logEvent({
        category: D.ASSISTANT,
        action: "New Chat",
        dimensions: ["With Design Discard"]
      }), this._showNewChatConfirm = !1, window.dispatchEvent(new CustomEvent("requestBuilderDiscard"));
    }} slot=footer-end>${this._translations.discard}</calcite-button></calcite-dialog>` || ""}<calcite-action icon=x id=closeAssistantButton .label=${this._translations.tooltips.close} @click=${() => {
      this.closeAssistant.emit(!0);
    }} slot=header-actions-end .text=${this._translations.tooltips.close}></calcite-action><calcite-tooltip placement=bottom reference-element=closeAssistantButton><span>${this._translations.tooltips.close}</span></calcite-tooltip></calcite-panel>`;
  }
  _clearConversation() {
    this._conversationId = void 0, this._lastTurnAgent = void 0, this._suggestedPrompts = [], this._hasInteracted = !1, this._assistantRef.value?.clearChatHistory();
  }
  _sendFeedback(e, s, i, n) {
    const o = `https://survey123.arcgis.com/share/6e349a50b4504ca6b6107216d568db5f?field:_source=${encodeURIComponent("Solutions Assistant")}&field:user_evaluation=${encodeURIComponent(i)}&field:question=${encodeURIComponent(s)}&field:answer=${encodeURIComponent(e)}&field:context=${encodeURIComponent(JSON.stringify({ agent: n }))}&field:version=${encodeURIComponent("v2")}`;
    window.open(o, "_blank");
  }
  async _loadUserFirstName() {
    try {
      const e = await this._configContextConsumer.value?.userSession?.getUser();
      if (e?.fullName) {
        const s = e.fullName.split(" ")[0];
        this.userFirstName = s;
      }
    } catch {
    }
  }
  _parseAgentPickedAndTask(e) {
    const s = Array.from(this._assistantRef.value?.messages || []), i = e.log || [], a = [...s].sort((u, f) => f.id - u.id).find((u) => u.role === "user" && u.id <= e.id)?.content || null, l = i.find((u) => typeof u == "string" && u.includes("Agent picked:")) ?? null;
    if (!l)
      return { agentPicked: null, taskAssigned: null, userMessage: a };
    const d = /Agent picked:\s*(.*?)\s*(?:\\n|\r?\n)\s*Task Assigned:\s*([\s\S]*)$/i, c = l.match(d);
    if (!c)
      return { agentPicked: null, taskAssigned: null, userMessage: a };
    const m = c[1].trim(), h = c[2].trim();
    return { agentPicked: m, taskAssigned: h, userMessage: a };
  }
  _emitItemIdFromAI(e) {
    const s = new CustomEvent("solutionIDFromAssistant", {
      detail: e,
      bubbles: !0,
      composed: !0
    });
    window.dispatchEvent(s);
  }
}
Le("arcgis-solutions-assistant", ms);
export {
  ms as ArcgisSolutionsAssistant
};
