@geoscene/ai-components 5.1.15 → 5.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
1
  /* COPYRIGHT GeoScene - https://js.geoscene.cn/5.1/LICENSE.txt */
2
2
  import{a as Y}from"./4EALV6QJ.js";var X=globalThis,Z=X.ShadowRoot&&(X.ShadyCSS===void 0||X.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,gt=Symbol(),It=new WeakMap,I=class{constructor(t,e,s){if(this._$cssResult$=!0,s!==gt)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o,e=this.t;if(Z&&t===void 0){let s=e!==void 0&&e.length===1;s&&(t=It.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&It.set(e,t))}return t}toString(){return this.cssText}},kt=o=>new I(typeof o=="string"?o:o+"",void 0,gt),be=(o,...t)=>{let e=o.length===1?o[0]:t.reduce((s,r,i)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+o[i+1],o[0]);return new I(e,o,gt)},jt=(o,t)=>{if(Z)o.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let e of t){let s=document.createElement("style"),r=X.litNonce;r!==void 0&&s.setAttribute("nonce",r),s.textContent=e.cssText,o.appendChild(s)}},vt=Z?o=>o:o=>o instanceof CSSStyleSheet?(t=>{let e="";for(let s of t.cssRules)e+=s.cssText;return kt(e)})(o):o;var{is:_e,defineProperty:Ae,getOwnPropertyDescriptor:Ce,getOwnPropertyNames:we,getOwnPropertySymbols:Oe,getPrototypeOf:Te}=Object,et=globalThis,Ht=et.trustedTypes,Se=Ht?Ht.emptyScript:"",Pe=et.reactiveElementPolyfillSupport,k=(o,t)=>o,tt={toAttribute(o,t){switch(t){case Boolean:o=o?Se:null;break;case Object:case Array:o=o==null?o:JSON.stringify(o)}return o},fromAttribute(o,t){let e=o;switch(t){case Boolean:e=o!==null;break;case Number:e=o===null?null:Number(o);break;case Object:case Array:try{e=JSON.parse(o)}catch{e=null}}return e}},j=(o,t)=>!_e(o,t),Vt={attribute:!0,type:String,converter:tt,reflect:!1,useDefault:!1,hasChanged:j};Symbol.metadata??=Symbol("metadata"),et.litPropertyMetadata??=new WeakMap;var _=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=Vt){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){let s=Symbol(),r=this.getPropertyDescriptor(t,s,e);r!==void 0&&Ae(this.prototype,t,r)}}static getPropertyDescriptor(t,e,s){let{get:r,set:i}=Ce(this.prototype,t)??{get(){return this[e]},set(n){this[e]=n}};return{get:r,set(n){let a=r?.call(this);i?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Vt}static _$Ei(){if(this.hasOwnProperty(k("elementProperties")))return;let t=Te(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(k("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(k("properties"))){let e=this.properties,s=[...we(e),...Oe(e)];for(let r of s)this.createProperty(r,e[r])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[s,r]of e)this.elementProperties.set(s,r)}this._$Eh=new Map;for(let[e,s]of this.elementProperties){let r=this._$Eu(e,s);r!==void 0&&this._$Eh.set(r,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let s=new Set(t.flat(1/0).reverse());for(let r of s)e.unshift(vt(r))}else t!==void 0&&e.push(vt(t));return e}static _$Eu(t,e){let s=e.attribute;return s===!1?void 0:typeof s=="string"?s:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let s of e.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return jt(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,e,s){this._$AK(t,s)}_$ET(t,e){let s=this.constructor.elementProperties.get(t),r=this.constructor._$Eu(t,s);if(r!==void 0&&s.reflect===!0){let i=(s.converter?.toAttribute!==void 0?s.converter:tt).toAttribute(e,s.type);this._$Em=t,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(t,e){let s=this.constructor,r=s._$Eh.get(t);if(r!==void 0&&this._$Em!==r){let i=s.getPropertyOptions(r),n=typeof i.converter=="function"?{fromAttribute:i.converter}:i.converter?.fromAttribute!==void 0?i.converter:tt;this._$Em=r;let a=n.fromAttribute(e,i.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(t,e,s,r=!1,i){if(t!==void 0){let n=this.constructor;if(r===!1&&(i=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??j)(i,e)||s.useDefault&&s.reflect&&i===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,e,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,e,{useDefault:s,reflect:r,wrapped:i},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??e??this[t]),i!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(e=void 0),this._$AL.set(t,e)),r===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[r,i]of this._$Ep)this[r]=i;this._$Ep=void 0}let s=this.constructor.elementProperties;if(s.size>0)for(let[r,i]of s){let{wrapped:n}=i,a=this[r];n!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,i,a)}}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(e)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(t){}firstUpdated(t){}};_.elementStyles=[],_.shadowRootOptions={mode:"open"},_[k("elementProperties")]=new Map,_[k("finalized")]=new Map,Pe?.({ReactiveElement:_}),(et.reactiveElementVersions??=[]).push("2.1.2");var $t=globalThis,zt=o=>o,st=$t.trustedTypes,Bt=st?st.createPolicy("lit-html",{createHTML:o=>o}):void 0,bt="$lit$",A=`lit$${Math.random().toFixed(9).slice(2)}$`,_t="?"+A,Ne=`<${_t}>`,T=document,V=()=>T.createComment(""),z=o=>o===null||typeof o!="object"&&typeof o!="function",At=Array.isArray,Jt=o=>At(o)||typeof o?.[Symbol.iterator]=="function",Et=`[
3
3
  \f\r]`,H=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Wt=/-->/g,Ft=/>/g,w=RegExp(`>|${Et}(?:([^\\s"'>=/]+)(${Et}*=${Et}*(?:[^
4
- \f\r"'\`<>=]|("|')|))|$)`,"g"),qt=/'/g,Gt=/"/g,Qt=/^(?:script|style|textarea|title)$/i,Ct=o=>(t,...e)=>({_$litType$:o,strings:t,values:e}),ds=Ct(1),ps=Ct(2),us=Ct(3),f=Symbol.for("lit-noChange"),d=Symbol.for("lit-nothing"),Kt=new WeakMap,O=T.createTreeWalker(T,129);function Yt(o,t){if(!At(o)||!o.hasOwnProperty("raw"))throw Error("invalid template strings array");return Bt!==void 0?Bt.createHTML(t):t}var Xt=(o,t)=>{let e=o.length-1,s=[],r,i=t===2?"<svg>":t===3?"<math>":"",n=H;for(let a=0;a<e;a++){let l=o[a],h,u,c=-1,m=0;for(;m<l.length&&(n.lastIndex=m,u=n.exec(l),u!==null);)m=n.lastIndex,n===H?u[1]==="!--"?n=Wt:u[1]!==void 0?n=Ft:u[2]!==void 0?(Qt.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=w):u[3]!==void 0&&(n=w):n===w?u[0]===">"?(n=r??H,c=-1):u[1]===void 0?c=-2:(c=n.lastIndex-u[2].length,h=u[1],n=u[3]===void 0?w:u[3]==='"'?Gt:qt):n===Gt||n===qt?n=w:n===Wt||n===Ft?n=H:(n=w,r=void 0);let v=n===w&&o[a+1].startsWith("/>")?" ":"";i+=n===H?l+Ne:c>=0?(s.push(h),l.slice(0,c)+bt+l.slice(c)+A+v):l+A+(c===-2?a:v)}return[Yt(o,i+(o[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]},B=class o{constructor({strings:t,_$litType$:e},s){let r;this.parts=[];let i=0,n=0,a=t.length-1,l=this.parts,[h,u]=Xt(t,e);if(this.el=o.createElement(h,s),O.currentNode=this.el.content,e===2||e===3){let c=this.el.content.firstChild;c.replaceWith(...c.childNodes)}for(;(r=O.nextNode())!==null&&l.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(let c of r.getAttributeNames())if(c.endsWith(bt)){let m=u[n++],v=r.getAttribute(c).split(A),C=/([.?@])?(.*)/.exec(m);l.push({type:1,index:i,name:C[2],strings:v,ctor:C[1]==="."?rt:C[1]==="?"?it:C[1]==="@"?nt:P}),r.removeAttribute(c)}else c.startsWith(A)&&(l.push({type:6,index:i}),r.removeAttribute(c));if(Qt.test(r.tagName)){let c=r.textContent.split(A),m=c.length-1;if(m>0){r.textContent=st?st.emptyScript:"";for(let v=0;v<m;v++)r.append(c[v],V()),O.nextNode(),l.push({type:2,index:++i});r.append(c[m],V())}}}else if(r.nodeType===8)if(r.data===_t)l.push({type:2,index:i});else{let c=-1;for(;(c=r.data.indexOf(A,c+1))!==-1;)l.push({type:7,index:i}),c+=A.length-1}i++}}static createElement(t,e){let s=T.createElement("template");return s.innerHTML=t,s}};function S(o,t,e=o,s){if(t===f)return t;let r=s!==void 0?e._$Co?.[s]:e._$Cl,i=z(t)?void 0:t._$litDirective$;return r?.constructor!==i&&(r?._$AO?.(!1),i===void 0?r=void 0:(r=new i(o),r._$AT(o,e,s)),s!==void 0?(e._$Co??=[])[s]=r:e._$Cl=r),r!==void 0&&(t=S(o,r._$AS(o,t.values),r,s)),t}var ot=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:e},parts:s}=this._$AD,r=(t?.creationScope??T).importNode(e,!0);O.currentNode=r;let i=O.nextNode(),n=0,a=0,l=s[0];for(;l!==void 0;){if(n===l.index){let h;l.type===2?h=new L(i,i.nextSibling,this,t):l.type===1?h=new l.ctor(i,l.name,l.strings,this,t):l.type===6&&(h=new at(i,this,t)),this._$AV.push(h),l=s[++a]}n!==l?.index&&(i=O.nextNode(),n++)}return O.currentNode=T,r}p(t){let e=0;for(let s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,e),e+=s.strings.length-2):s._$AI(t[e])),e++}},L=class o{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,s,r){this.type=2,this._$AH=d,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=s,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=S(this,t,e),z(t)?t===d||t==null||t===""?(this._$AH!==d&&this._$AR(),this._$AH=d):t!==this._$AH&&t!==f&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Jt(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==d&&z(this._$AH)?this._$AA.nextSibling.data=t:this.T(T.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:s}=t,r=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=B.createElement(Yt(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(e);else{let i=new ot(r,this),n=i.u(this.options);i.p(e),this.T(n),this._$AH=i}}_$AC(t){let e=Kt.get(t.strings);return e===void 0&&Kt.set(t.strings,e=new B(t)),e}k(t){At(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,s,r=0;for(let i of t)r===e.length?e.push(s=new o(this.O(V()),this.O(V()),this,this.options)):s=e[r],s._$AI(i),r++;r<e.length&&(this._$AR(s&&s._$AB.nextSibling,r),e.length=r)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t!==this._$AB;){let s=zt(t).nextSibling;zt(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},P=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,s,r,i){this.type=1,this._$AH=d,this._$AN=void 0,this.element=t,this.name=e,this._$AM=r,this.options=i,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=d}_$AI(t,e=this,s,r){let i=this.strings,n=!1;if(i===void 0)t=S(this,t,e,0),n=!z(t)||t!==this._$AH&&t!==f,n&&(this._$AH=t);else{let a=t,l,h;for(t=i[0],l=0;l<i.length-1;l++)h=S(this,a[s+l],e,l),h===f&&(h=this._$AH[l]),n||=!z(h)||h!==this._$AH[l],h===d?t=d:t!==d&&(t+=(h??"")+i[l+1]),this._$AH[l]=h}n&&!r&&this.j(t)}j(t){t===d?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},rt=class extends P{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===d?void 0:t}},it=class extends P{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==d)}},nt=class extends P{constructor(t,e,s,r,i){super(t,e,s,r,i),this.type=5}_$AI(t,e=this){if((t=S(this,t,e,0)??d)===f)return;let s=this._$AH,r=t===d&&s!==d||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,i=t!==d&&(s===d||r);r&&this.element.removeEventListener(this.name,this,s),i&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},at=class{constructor(t,e,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){S(this,t)}},Zt={M:bt,P:A,A:_t,C:1,L:Xt,R:ot,D:Jt,V:S,I:L,H:P,N:it,U:nt,B:rt,F:at},De=$t.litHtmlPolyfillSupport;De?.(B,L),($t.litHtmlVersions??=[]).push("3.3.2");var wt=(o,t,e)=>{let s=e?.renderBefore??t,r=s._$litPart$;if(r===void 0){let i=e?.renderBefore??null;s._$litPart$=r=new L(t.insertBefore(V(),i),i,void 0,e??{})}return r._$AI(o),r};var Ot=globalThis,E=class extends _{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){let e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=wt(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return f}};E._$litElement$=!0,E.finalized=!0,Ot.litElementHydrateSupport?.({LitElement:E});var xe=Ot.litElementPolyfillSupport;xe?.({LitElement:E});(Ot.litElementVersions??=[]).push("4.2.2");var te=new Set,ee;var se=o=>typeof o=="string"?o:"el"in o?o.el.localName:"localName"in o?o.localName:o.declaredClass,Os=(o,t,e,s)=>{let r=se(t);if(s?.once){let n=`${o}${r}${e}`;if(te.has(n))return;te.add(n)}let i;if(s?.detail){i={};for(let[n,a]of Object.entries(s.detail))if((typeof a=="object"||typeof a=="function")&&a!==null){let l=new WeakRef(a);Object.defineProperty(i,n,{enumerable:!0,get(){return l.deref()}})}else i[n]=a;ee?.log.interceptors?.forEach(n=>n(o,r,e,i)),console[o](`[${r}]: ${e}`,i)}else ee?.log.interceptors?.forEach(n=>n(o,r,e)),console[o](`[${r}]: ${e}`)},oe=o=>{let t=`[${se(o)}] `;return e=>{let s=e instanceof Error&&e.message?e:new Error(String(e));s.message=`${t}${s.message}`,setTimeout(()=>{throw e})}};var p=(o,t,...e)=>{try{return o?.call(t,...e)}catch(s){console.error(s,o)}},W=async(o,t,...e)=>{try{return await o?.call(t,...e)}catch(s){console.error(s,o)}};var q=Symbol.for("controller"),Le=o=>typeof o=="object"&&o!==null&&(q in o||"hostConnected"in o||"hostDisconnected"in o||"hostUpdate"in o||"hostUpdated"in o),Ps=o=>typeof o?.then=="function";var F,D=o=>{F!==o&&(F=o,queueMicrotask(()=>F===o?F=void 0:0))},G=o=>F,N=[],re=o=>{if(o===void 0){N=[];return}let t=N.indexOf(o);N=t===-1?[...N,o]:N.slice(0,t+1),queueMicrotask(()=>N=[])},ie=()=>N,U,Ns=o=>{U!==o&&(U=o,queueMicrotask(()=>U===o?U=void 0:0))},Ue=()=>{let o=U;return U=void 0,o},ne=async(o,t)=>{let e=ct(o);if(e===void 0)return o;if(await e.ready,typeof t=="function"){let s=e.watchExports(r=>t(r,s))}return e.exports},ae=async o=>{let t=ct(o);return await t.ready,t},ct=o=>{let e=G().manager.X(o);if(e!==void 0)return e;if(Le(o))return o;let s=Ue();if(s!==void 0)return s},lt=!1,Ds=o=>{lt=!0;try{return o()}finally{lt=!1}};var b=class{constructor(){this.promise=new Promise((t,e)=>{this.resolve=t,this.reject=e})}};var le=(o,t)=>{let e=t>Re?Me:t/Ie,s=0,r=setInterval(()=>{s+=e,s>=t&&(clearInterval(r),o())},e);return r},Re=4e3,Me=2e3,Ie=4;var ke=(o,t,e)=>{let s=Object.keys(o),r=s.length;R===void 0&&queueMicrotask(M),R??=new Map;let i=R.get(o);return i===void 0&&(i={callbacks:[],keyCount:r},R.set(o,i)),i.keyCount!==r&&(i.callbacks.forEach(n=>n(s)),i.callbacks=[],i.keyCount=r),i.callbacks.push(n=>{let a=h=>p(t,null,h),l=n[r];l===void 0?a(void 0):o[l]===e?a(l):a(void 0)}),e},R,M=()=>{R?.forEach(({callbacks:o},t)=>{let e=Object.keys(t);o.forEach(s=>s(e))}),R=void 0},je=(o,t,e)=>{let s=o.manager;return s.V!==d&&s.V!==e&&s.S(void 0,void 0),s.T.length===0&&queueMicrotask(()=>s.S(void 0,void 0)),s.V=e,s.T.push((r,i)=>p(t,void 0,e===i?r:void 0)),e},He=(o=[G(),...ie()],t,e)=>{let s=Array.isArray(o)?o:[o],r=s.length+1,i=n=>{r-=1,n!==void 0&&(r=Math.min(r,0)),r===0&&t(n)};s.forEach(n=>ke(n,a=>i(a===void 0?void 0:{key:a,host:n,isReactive:!1}),e));for(let n of s)if("manager"in n&&n.manager.component===n){je(n,a=>i(a===void 0?void 0:{key:a,host:n,isReactive:!0}),e);break}return e},Ve=(o="",t={},e=G())=>{let s={emit:r=>{o===""&&M();let i=new CustomEvent(o,{detail:r,cancelable:!0,bubbles:!0,composed:!0,...t});return e.el.dispatchEvent(i),i}};return o===""&&He(void 0,r=>o=r.key,s),s},ze=Ve.bind(null,""),de;de=q;var Tt=class{constructor(t){this.#t=[],this.#e=[],this.#s=[],this.#r=[],this.#i=[],this.#l=[],this.#c=[],this.#d=[],this.#n=[],this.#p=!1,this.P=new b,this.connectedCalled=!1,this.loadedCalled=!1,this[de]=!0,this.#h=[];let e=this,s=t??G(new.target.name);e.#o=s,e.ready=e.P.promise,e.#a=he(e),e.component=s,e.#o.addController(e),e.#o.manager===void 0||(re(e),queueMicrotask(()=>e.catchUpLifecycle()))}#t;#e;#s;#r;#i;#l;#c;#d;#n;#p;#o;catchUpLifecycle(){let{manager:t}=this.#o;t.connectedCalled&&!this.connectedCalled&&this.triggerConnected(),t.#p&&this.triggerLoad().then(()=>t.loadedCalled&&this.triggerLoaded()).catch(oe(this.#o))}#a;get exports(){return this.#a}set exports(t){let e=this.#a;e!==t&&(this.#a=t,this.#h.forEach(p),this.connectedCalled&&this.O!==!1&&this.#o.requestUpdate(this.O,e)),this.P.resolve(t)}setProvisionalExports(t,e=!0){this.#a=e?he(t):t,this.#h.forEach(p)}#h;watchExports(t){let e=()=>t(this.#a);return this.#h.push(e),()=>{this.#h.splice(this.#h.indexOf(e),1)}}get use(){return D(this.#o),ne}get useRef(){return D(this.#o),ae}get useRefSync(){return D(this.#o),ct}controllerRemoved(){this.#o.el.isConnected&&this.triggerDisconnected(),this.triggerDestroy()}onConnected(t){this.#t.push(t)}onDisconnected(t){this.#e.push(t)}onLoad(t){this.#s.push(t)}onLoaded(t){this.#r.push(t)}onUpdate(t){this.#i.push(t)}onUpdated(t){this.#l.push(t)}onDestroy(t){this.#c.push(t)}onLifecycle(t){this.#d.push(t),this.connectedCalled&&this.#o.el.isConnected&&this.#u(t)}triggerConnected(){let t=this;t.hostConnected&&p(t.hostConnected,t),t.#t.forEach(p),t.triggerLifecycle(),t.connectedCalled=!0}triggerDisconnected(){let t=this;t.hostDisconnected&&p(t.hostDisconnected,t),t.#e.forEach(p),t.#n.forEach(p),t.#n=[]}async triggerLoad(){if(this.#p)return;this.#p=!0;let t=this;t.hostLoad&&await W(t.hostLoad,t),this.#s.length>0&&await Promise.allSettled(this.#s.map(W)),this.P.resolve(this.#a)}triggerLoaded(){this.loadedCalled||(this.hostLoaded&&p(this.hostLoaded,this),this.#r.forEach(p),this.loadedCalled=!0)}triggerUpdate(t){this.hostUpdate&&p(this.hostUpdate,this,t),this.#i.forEach(ce,t)}triggerUpdated(t){this.hostUpdated&&p(this.hostUpdated,this,t),this.#l.forEach(ce,t)}triggerDestroy(){this.hostDestroy&&p(this.hostDestroy,this),this.#c.forEach(p)}triggerLifecycle(){this.hostLifecycle&&this.#u(()=>this.hostLifecycle()),this.#d.forEach(this.#u,this)}#u(t){D(this.#o);let e=p(t);(Array.isArray(e)?e:[e]).forEach(r=>{typeof r=="function"?this.#n.push(r):typeof r=="object"&&typeof r.remove=="function"&&this.#n.push(r.remove)})}};function ce(o){p(o,void 0,this)}var pe=Tt,he=o=>{if(typeof o!="object"&&typeof o!="function"||o===null)return o;let t={get(s,r,i){if(!((r==="exports"||r==="_exports")&&r in s&&s[r]===e)&&(r in s||r in Promise.prototype||typeof r=="symbol"))return typeof s=="function"?s[r]:Reflect.get(s,r,i)}},e=new Proxy(o,t);return e};var{I:zs}=Zt;var ht=o=>o.strings===void 0;var Be={},ue=(o,t=Be)=>o._$AH=t;var y={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},$=o=>(...t)=>({_$litDirective$:o,values:t}),g=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,s){this._$Ct=t,this._$AM=e,this._$Ci=s}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}};var K=(o,t)=>{let e=o._$AN;if(e===void 0)return!1;for(let s of e)s._$AO?.(t,!1),K(s,t);return!0},dt=o=>{let t,e;do{if((t=o._$AM)===void 0)break;e=t._$AN,e.delete(o),o=t}while(e?.size===0)},fe=o=>{for(let t;t=o._$AM;o=t){let e=t._$AN;if(e===void 0)t._$AN=e=new Set;else if(e.has(o))break;e.add(o),qe(t)}};function We(o){this._$AN!==void 0?(dt(this),this._$AM=o,fe(this)):this._$AM=o}function Fe(o,t=!1,e=0){let s=this._$AH,r=this._$AN;if(r!==void 0&&r.size!==0)if(t)if(Array.isArray(s))for(let i=e;i<s.length;i++)K(s[i],!1),dt(s[i]);else s!=null&&(K(s,!1),dt(s));else K(this,o)}var qe=o=>{o.type==y.CHILD&&(o._$AP??=Fe,o._$AQ??=We)},pt=class extends g{constructor(){super(...arguments),this._$AN=void 0}_$AT(t,e,s){super._$AT(t,e,s),fe(this),this.isConnected=t._$AU}_$AO(t,e=!0){t!==this.isConnected&&(this.isConnected=t,t?this.reconnected?.():this.disconnected?.()),e&&(K(this,t),dt(this))}setValue(t){if(ht(this._$Ct))this._$Ct._$AI(t,this);else{let e=[...this._$Ct._$AH];e[this._$Ci]=t,this._$Ct._$AI(e,this,0)}}disconnected(){}reconnected(){}};var Xs=()=>new Pt,Pt=class{},St=new WeakMap,Nt=$(class extends pt{render(o){return d}update(o,[t]){let e=t!==this.G;return e&&this.G!==void 0&&this.rt(void 0),(e||this.lt!==this.ct)&&(this.G=t,this.ht=o.options?.host,this.rt(this.ct=o.element)),d}rt(o){if(this.isConnected||(o=void 0),typeof this.G=="function"){let t=this.ht??globalThis,e=St.get(t);e===void 0&&(e=new WeakMap,St.set(t,e)),e.get(this.G)!==void 0&&this.G.call(this.ht,void 0),e.set(this.G,o),o!==void 0&&this.G.call(this.ht,o)}else this.G.value=o}get lt(){return typeof this.G=="function"?St.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var xt=o=>{let t=o;for(;t=t.parentNode??t.host;)if(t?.constructor?.lumina){let e=t;return e.manager?.loadedCalled||(e.J??e._offspring).push(o),(e.I??e._postLoad).promise}return!1},Lt={};function Ut(){}function Rt(o){for(let t of["Associated","Disabled","Reset","StateRestore"]){let e=`orm${t}Callback`;o.prototype["f"+e]=async function(...s){await this.componentOnReady(),(this.el??this).dispatchEvent(new CustomEvent(`luminaF${e}`,{detail:s}))}}}var Ke=(o,t)=>function(s,r){if(!globalThis.customElements)return;let n=(r??s??{}).resourcesUrl;n&&o.setAssetPath(n);for(let[a,[l,h="",u=0]]of Object.entries(t)){if(customElements.get(a))continue;let[c,m,v]=h.split(";"),C=c?c?.split(",").map(Je):void 0,yt=C?.map(([x])=>x),Q=class extends Dt{static{this.formAssociated=u===1}static{this.observedAttributes=C?.map(([,x])=>x).filter(x=>x!=="")}static{this.C=yt}static{this.E=m?m?.split(","):void 0}static{this.D=v?.split(",")}static{this.L=a}static{this.K=o}constructor(){!Q.B&&(Q.B=l(),Q.F()),super()}};customElements.define(a,Q)}},ut=Object.defineProperty,Je=o=>{let t=o.split(":");return t.length===1?[t[0],Y(t[0])]:t},Qe=globalThis.HTMLElement??Ut,Dt=class extends Qe{constructor(){super(),this.#e={},this.#s=[],this.I=new b,this.H=new b,this.J=[];let t=this,e=t.constructor;t._offspring=t.J,t._postLoad=t.I,e.C?.forEach(s=>{Object.hasOwn(t,s)&&(t.#e[s]=t[s],delete t[s])}),e.A?t.#r({a:e.A}):e.B.then(async s=>{await e.K.p,t.#r(await(s.default?.then(r=>typeof r=="function"?{a:r}:r)??s))}).catch(s=>{t.H.reject(s),setTimeout(()=>{throw s})})}static{this.lumina=!0}static F(){for(let t of this.C??[])ut(this.prototype,t,{configurable:!0,enumerable:!0,get(){return this.#e[t]},set(e){this.#e[t]=e}});for(let t of this.E??[])ut(this.prototype,t,{async value(...e){return this.#t||await this.H.promise,await this.#t[t](...e)},configurable:!0});for(let t of this.D??[])ut(this.prototype,t,{value(...e){return this.#t[t](...e)},configurable:!0})}static{Rt(this)}#t;#e;#s;get manager(){return this.#t?.manager}attributeChangedCallback(t,e,s){this.#t?.attributeChangedCallback(t,e,s),this.#t||this.#s.push(t)}connectedCallback(){this.#t?this.#t.connectedCallback?.():queueMicrotask(()=>this.G=xt(this))}disconnectedCallback(){this.#t?.disconnectedCallback?.()}async componentOnReady(){return await this.H.promise,this}#r(t){let e=this.constructor,s=e.L,r=this.#e,i=Object.values(t).find(c=>c.L===s),n=`${s}--lazy`,a=i;for(;a&&!Object.hasOwn(a,"lumina");)a=Object.getPrototypeOf(a);Xe(a),!e.A&&(e.A=i,customElements.define(n,i)),i.N=this;let h=document.createElement(n);i.N=void 0,this.#t=h,this.#e=h,this.#s.forEach(c=>h.attributeChangedCallback(c,null,this.getAttribute(c))),Object.entries(r).forEach(Ye,h);let u=this.isConnected;(u||this.G)&&(h.connectedCallback?.(),u||h.disconnectedCallback())}addController(){}requestUpdate(){this.#t?.requestUpdate()}};function Ye([o,t]){this[o]=t}var Xe=o=>{let t=o.prototype,e=Element.prototype;Object.hasOwn(t,"isConnected")||(t.setAttribute=function(r,i){e.setAttribute.call(this.el,r,i)},t.removeAttribute=function(r){e.removeAttribute.call(this.el,r)},t.hasAttribute=function(r){return e.hasAttribute.call(this.el,r)},ut(t,"isConnected",{get(){return Reflect.get(e,"isConnected",this.el)}}))};var ft=class extends pe{constructor(t){super(t),this.destroyed=!1,this.R=!1,this.V=d,this.T=[],this.#s=new WeakMap,this.#e=t,this.exports=void 0,this.hasDestroy=mt in t&&typeof t.destroy=="function",E.prototype.addController.call(t,{hostConnected:()=>{if(this.destroyed){let e=t.el.localName;throw t.el.remove(),new Error(`The ${e} component has already been destroyed. It cannot be used again. If you meant to disconnect and reconnect a component without automatic destroy, set the ${mt} prop.`)}this.#t!==void 0&&clearTimeout(this.#t),M();for(let e of t.M)"triggerConnected"in e?e.triggerConnected():p(e.hostConnected,e)},hostDisconnected:()=>{for(let e of t.M)"triggerDisconnected"in e?e.triggerDisconnected():p(e.hostDisconnected,e);this.hasDestroy&&!this.destroyed&&this.U()},hostUpdate:()=>{for(let e of t.M)"triggerUpdate"in e?e.triggerUpdate(this.Q):p(e.hostUpdate,e,this.Q)},hostUpdated:()=>{for(let e of t.M)"triggerUpdated"in e?e.triggerUpdated(this.Q):p(e.hostUpdated,e,this.Q);this.Q=void 0}}),queueMicrotask(()=>this.R=!0),D(t)}#t;#e;async destroy(){if(!this.destroyed){this.#e.el.isConnected&&(this.hasDestroy=!1,this.#e.el.remove()),this.#t=void 0,this.destroyed=!0;for(let t of this.#e.M)"triggerDestroy"in t?t.triggerDestroy():p(t.hostDestroy,t);this.#e.M.splice(0)}}U(){if(this.#t!==void 0&&clearTimeout(this.#t),!this.#e.el.isConnected&&!this.#e.autoDestroyDisabled){let t=()=>{this.#e.destroy()};this.#t=le(t,Ze)}}S(t,e){let s=this.T;this.V=d,this.T=[],s.forEach(r=>r(t,e))}#s;W(t,e){(typeof e=="object"&&e!==null||typeof e=="function")&&this.#s.set(e,t)}X(t){if(typeof t=="object"&&t!==null||typeof t=="function")return this.#s.get(t)}},Ze=1e3,mt="autoDestroyDisabled";var ye=$(class extends g{constructor(o){if(super(o),o.type!==y.ATTRIBUTE||o.name!=="class"||o.strings?.length>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(o){return" "+Object.keys(o).filter(t=>o[t]).join(" ")+" "}update(o,[t]){if(this.st===void 0){this.st=new Set,o.strings!==void 0&&(this.nt=new Set(o.strings.join(" ").split(/\s/).filter(s=>s!=="")));for(let s in t)t[s]&&!this.nt?.has(s)&&this.st.add(s);return this.render(t)}let e=o.element.classList;for(let s of this.st)s in t||(e.remove(s),this.st.delete(s));for(let s in t){let r=!!t[s];r===this.st.has(s)||this.nt?.has(s)||(r?(e.add(s),this.st.add(s)):(e.remove(s),this.st.delete(s)))}return f}});var ge="important",ts=" !"+ge,es=$(class extends g{constructor(o){if(super(o),o.type!==y.ATTRIBUTE||o.name!=="style"||o.strings?.length>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(o){return Object.keys(o).reduce((t,e)=>{let s=o[e];return s==null?t:t+`${e=e.includes("-")?e:e.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,"-$&").toLowerCase()}:${s};`},"")}update(o,[t]){let{style:e}=o.element;if(this.ft===void 0)return this.ft=new Set(Object.keys(t)),this.render(t);for(let s of this.ft)t[s]==null&&(this.ft.delete(s),s.includes("-")?e.removeProperty(s):e[s]=null);for(let s in t){let r=t[s];if(r!=null){this.ft.add(s);let i=typeof r=="string"&&r.endsWith(ts);s.includes("-")||i?e.setProperty(s,i?r.slice(0,-11):r,i?ge:""):e[s]=r}}return f}});var ss=$(class extends g{constructor(o){if(super(o),o.type!==y.PROPERTY&&o.type!==y.ATTRIBUTE&&o.type!==y.BOOLEAN_ATTRIBUTE)throw Error("The `live` directive is not allowed on child or event bindings");if(!ht(o))throw Error("`live` bindings can only contain a single expression")}render(o){return o}update(o,[t]){if(t===f||t===d)return t;let e=o.element,s=o.name;if(o.type===y.PROPERTY){if(t===e[s])return f}else if(o.type===y.BOOLEAN_ATTRIBUTE){if(!!t===e.hasAttribute(s))return f}else if(o.type===y.ATTRIBUTE&&e.getAttribute(s)===t+"")return f;return ue(o),t}});var ve=class o extends E{constructor(){super(),this.M=[],this.manager=new ft(this);let t=this,e=t.constructor,s=e.N,r=e.K.o,i=o.prototype.shouldUpdate;t.#r=s?.H??new b,t.I=s?.I??new b,t.J=s?.J??[],t._offspring=t.J,t._postLoad=t.I,t.el=s??t,t.#s=t.enableUpdating,t.enableUpdating=Ut,t.shouldUpdate!==i&&(t.#e=t.shouldUpdate,t.shouldUpdate=i),r&&(t.#t=new Map,e.elementProperties.forEach((n,a)=>t.#t.set(a,r()))),!1}static finalizeStyles(t){let e=super.finalizeStyles(t),s=this.shadowRootOptions===Lt;return this.K?.commonStyles===void 0||s?e:[this.K.commonStyles,...e]}static createProperty(t,e){let s=typeof e=="number"?e:Array.isArray(e)?e[0]:0,r=Array.isArray(e)?e[1]:void 0,i=r?.hasChanged??j,n={attribute:s&1&&typeof t=="string"?Y(t):!1,reflect:!!(s&2),type:s&4?Boolean:s&8?Number:void 0,state:!!(s&16),readOnly:!!(s&32),noAccessor:!!(s&64),useDefault:!!(s&128),c:!1,...r,hasChanged(a,l){let h=i(a,l);return n.c=h,h}};super.createProperty(t,n)}static getPropertyDescriptor(t,e,s){let r=this.K,i=super.getPropertyDescriptor(t,e,s);return s.d=i,{...i,get(){return r.t?.(this.#t.get(t)),i.get?.call(this)},set(n){let a=this.manager;if(s.readOnly&&!lt&&(a.R||a.connectedCalled))throw Error(`Cannot assign to read-only property "${t}" of ${this.el.localName}. Trying to assign "${n}"`);i.set.call(this,n??void 0),s.c&&this.#t?.get(t)?.notify(),a.T.length>0&&(M(),a?.S(t,n))}}}static{this.lumina=!0}static{Rt(this)}#t;#e;#s;#r;#i;#l;get elementInternals(){return this.#l??=this.el.attachInternals(),this.#l}connectedCallback(){this.hasAttribute("defer-hydration")||this.#c(!0)}#c(t){let e=this.constructor.K.c?.(()=>this.requestUpdate());this.#i=e;let s=!this.manager.connectedCalled;t&&super.connectedCallback(),s?queueMicrotask(()=>this.#n().catch(r=>{this.#r.reject(r),setTimeout(()=>{throw r})})):e&&this.requestUpdate()}#d(t){try{this.#i.clear(),this.constructor.K.r(this.#i,()=>super.update(t))}catch(e){throw this.#i.clear(),e}}disconnectedCallback(){super.disconnectedCallback(),this.#i?.destroy(),this.#i=void 0}createRenderRoot(){let t=this.el.shadowRoot,e=this.constructor,s=e.shadowRootOptions,i=t??(s===Lt?this.el:this.el.attachShadow(s));if(t)return this.manager.connectedCalled||this.#c(!1),E.prototype.createRenderRoot.call(this),t;if(this.isConnected){let n=i.getRootNode();n.adoptedStyleSheets=[...n.adoptedStyleSheets,...e.elementStyles.map(a=>"styleSheet"in a?a.styleSheet:a)]}return i}async#n(){let t=this.el.G??xt(this.el);t&&await t;let e=[];for(let r of this.M)"triggerLoad"in r?e.push(r.triggerLoad()):e.push(W(r.hostLoad,r));await Promise.all(e),await this.load?.(),this.manager.hasDestroy&&this.manager.onUpdate(r=>r.has(mt)&&this.manager.U()),this.#s(!0),this.performUpdate(),this.I.resolve(),await 0;let s=this.J.filter(r=>!r.manager?.loadedCalled);s.length&&await Promise.allSettled(s.map(async r=>await r.componentOnReady())),this.J.length=0,this.el.setAttribute(this.constructor.K.hydratedAttribute,"");for(let r of this.M)"triggerLoaded"in r?r.triggerLoaded():p(r.hostLoaded,r);this.loaded?.(),this.#r.resolve()}shouldUpdate(t){return this.manager.Q=t,this.#e?.(t)??!0}update(t){this.#i?this.#d(t):super.update(t)}listen(t,e,s){let r=e?.bind(this)??e;this.manager.onLifecycle(()=>(this.el.addEventListener(t,r,s),()=>this.el.removeEventListener(t,r,s)))}listenOn(t,e,s,r){let i=s?.bind(this)??s;this.manager.onLifecycle(()=>(t.addEventListener(e,i,r),()=>t.removeEventListener(e,i,r)))}async componentOnReady(){return await this.#r.promise,this}addController(t){this.M.push(t),!(q in t)&&this.renderRoot&&this.el.isConnected&&t.hostConnected?.()}removeController(t){this.M.splice(this.M.indexOf(t),1),t.controllerRemoved?.()}};var $e=o=>{let t,e=r=>{t=new URL(r,globalThis.location?.href||void 0).href},s={...o,getAssetPath(r){let i=new URL(r,t);return i.origin!==globalThis.location?.origin?i.href:i.pathname},setAssetPath:e,customElement(r,i){i.K=s,i.L=r,customElements.get(r)||customElements.define(r,i)}};return e(o.defaultAssetPath),s};var $r=o=>typeof o=="object"&&o!=null?ye(o):o;var Mt=class extends g{#t;#e;constructor(t){super(t);let e=this;this.#e=function(r){return e.#t.call(this,r)}}render(t){return typeof t=="function"?(this.#t=t,Nt(this.#e)):Nt(t)}},br=$(Mt);var _r=d;var J=$e({defaultAssetPath:"https://js.geoscene.com/5.1/ai-components/",hydratedAttribute:"hydrated"}),{customElement:Tr,getAssetPath:Sr,setAssetPath:Pr}=J;J.t=void 0;J.o=void 0;J.c=void 0;J.r=void 0;export{Ps as a,D as b,re as c,ie as d,Ns as e,Ds as f,be as g,ds as h,f as i,d as j,Os as k,oe as l,He as m,ze as n,Tt as o,Ke as p,y as q,$ as r,g as s,Xs as t,Nt as u,ve as v,$r as w,_r as x,J as y,Tr as z,Sr as A};
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),qt=/'/g,Gt=/"/g,Qt=/^(?:script|style|textarea|title)$/i,Ct=o=>(t,...e)=>({_$litType$:o,strings:t,values:e}),ds=Ct(1),ps=Ct(2),us=Ct(3),f=Symbol.for("lit-noChange"),d=Symbol.for("lit-nothing"),Kt=new WeakMap,O=T.createTreeWalker(T,129);function Yt(o,t){if(!At(o)||!o.hasOwnProperty("raw"))throw Error("invalid template strings array");return Bt!==void 0?Bt.createHTML(t):t}var Xt=(o,t)=>{let e=o.length-1,s=[],r,i=t===2?"<svg>":t===3?"<math>":"",n=H;for(let a=0;a<e;a++){let l=o[a],h,u,c=-1,m=0;for(;m<l.length&&(n.lastIndex=m,u=n.exec(l),u!==null);)m=n.lastIndex,n===H?u[1]==="!--"?n=Wt:u[1]!==void 0?n=Ft:u[2]!==void 0?(Qt.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=w):u[3]!==void 0&&(n=w):n===w?u[0]===">"?(n=r??H,c=-1):u[1]===void 0?c=-2:(c=n.lastIndex-u[2].length,h=u[1],n=u[3]===void 0?w:u[3]==='"'?Gt:qt):n===Gt||n===qt?n=w:n===Wt||n===Ft?n=H:(n=w,r=void 0);let v=n===w&&o[a+1].startsWith("/>")?" ":"";i+=n===H?l+Ne:c>=0?(s.push(h),l.slice(0,c)+bt+l.slice(c)+A+v):l+A+(c===-2?a:v)}return[Yt(o,i+(o[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]},B=class o{constructor({strings:t,_$litType$:e},s){let r;this.parts=[];let i=0,n=0,a=t.length-1,l=this.parts,[h,u]=Xt(t,e);if(this.el=o.createElement(h,s),O.currentNode=this.el.content,e===2||e===3){let c=this.el.content.firstChild;c.replaceWith(...c.childNodes)}for(;(r=O.nextNode())!==null&&l.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(let c of r.getAttributeNames())if(c.endsWith(bt)){let m=u[n++],v=r.getAttribute(c).split(A),C=/([.?@])?(.*)/.exec(m);l.push({type:1,index:i,name:C[2],strings:v,ctor:C[1]==="."?rt:C[1]==="?"?it:C[1]==="@"?nt:P}),r.removeAttribute(c)}else c.startsWith(A)&&(l.push({type:6,index:i}),r.removeAttribute(c));if(Qt.test(r.tagName)){let c=r.textContent.split(A),m=c.length-1;if(m>0){r.textContent=st?st.emptyScript:"";for(let v=0;v<m;v++)r.append(c[v],V()),O.nextNode(),l.push({type:2,index:++i});r.append(c[m],V())}}}else if(r.nodeType===8)if(r.data===_t)l.push({type:2,index:i});else{let c=-1;for(;(c=r.data.indexOf(A,c+1))!==-1;)l.push({type:7,index:i}),c+=A.length-1}i++}}static createElement(t,e){let s=T.createElement("template");return s.innerHTML=t,s}};function S(o,t,e=o,s){if(t===f)return t;let r=s!==void 0?e._$Co?.[s]:e._$Cl,i=z(t)?void 0:t._$litDirective$;return r?.constructor!==i&&(r?._$AO?.(!1),i===void 0?r=void 0:(r=new i(o),r._$AT(o,e,s)),s!==void 0?(e._$Co??=[])[s]=r:e._$Cl=r),r!==void 0&&(t=S(o,r._$AS(o,t.values),r,s)),t}var ot=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:e},parts:s}=this._$AD,r=(t?.creationScope??T).importNode(e,!0);O.currentNode=r;let i=O.nextNode(),n=0,a=0,l=s[0];for(;l!==void 0;){if(n===l.index){let h;l.type===2?h=new L(i,i.nextSibling,this,t):l.type===1?h=new l.ctor(i,l.name,l.strings,this,t):l.type===6&&(h=new at(i,this,t)),this._$AV.push(h),l=s[++a]}n!==l?.index&&(i=O.nextNode(),n++)}return O.currentNode=T,r}p(t){let e=0;for(let s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,e),e+=s.strings.length-2):s._$AI(t[e])),e++}},L=class o{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,s,r){this.type=2,this._$AH=d,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=s,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=S(this,t,e),z(t)?t===d||t==null||t===""?(this._$AH!==d&&this._$AR(),this._$AH=d):t!==this._$AH&&t!==f&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Jt(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==d&&z(this._$AH)?this._$AA.nextSibling.data=t:this.T(T.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:s}=t,r=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=B.createElement(Yt(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(e);else{let i=new ot(r,this),n=i.u(this.options);i.p(e),this.T(n),this._$AH=i}}_$AC(t){let e=Kt.get(t.strings);return e===void 0&&Kt.set(t.strings,e=new B(t)),e}k(t){At(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,s,r=0;for(let i of t)r===e.length?e.push(s=new o(this.O(V()),this.O(V()),this,this.options)):s=e[r],s._$AI(i),r++;r<e.length&&(this._$AR(s&&s._$AB.nextSibling,r),e.length=r)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t!==this._$AB;){let s=zt(t).nextSibling;zt(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},P=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,s,r,i){this.type=1,this._$AH=d,this._$AN=void 0,this.element=t,this.name=e,this._$AM=r,this.options=i,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=d}_$AI(t,e=this,s,r){let i=this.strings,n=!1;if(i===void 0)t=S(this,t,e,0),n=!z(t)||t!==this._$AH&&t!==f,n&&(this._$AH=t);else{let a=t,l,h;for(t=i[0],l=0;l<i.length-1;l++)h=S(this,a[s+l],e,l),h===f&&(h=this._$AH[l]),n||=!z(h)||h!==this._$AH[l],h===d?t=d:t!==d&&(t+=(h??"")+i[l+1]),this._$AH[l]=h}n&&!r&&this.j(t)}j(t){t===d?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},rt=class extends P{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===d?void 0:t}},it=class extends P{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==d)}},nt=class extends P{constructor(t,e,s,r,i){super(t,e,s,r,i),this.type=5}_$AI(t,e=this){if((t=S(this,t,e,0)??d)===f)return;let s=this._$AH,r=t===d&&s!==d||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,i=t!==d&&(s===d||r);r&&this.element.removeEventListener(this.name,this,s),i&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},at=class{constructor(t,e,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){S(this,t)}},Zt={M:bt,P:A,A:_t,C:1,L:Xt,R:ot,D:Jt,V:S,I:L,H:P,N:it,U:nt,B:rt,F:at},De=$t.litHtmlPolyfillSupport;De?.(B,L),($t.litHtmlVersions??=[]).push("3.3.2");var wt=(o,t,e)=>{let s=e?.renderBefore??t,r=s._$litPart$;if(r===void 0){let i=e?.renderBefore??null;s._$litPart$=r=new L(t.insertBefore(V(),i),i,void 0,e??{})}return r._$AI(o),r};var Ot=globalThis,E=class extends _{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){let e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=wt(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return f}};E._$litElement$=!0,E.finalized=!0,Ot.litElementHydrateSupport?.({LitElement:E});var xe=Ot.litElementPolyfillSupport;xe?.({LitElement:E});(Ot.litElementVersions??=[]).push("4.2.2");var te=new Set,ee;var se=o=>typeof o=="string"?o:"el"in o?o.el.localName:"localName"in o?o.localName:o.declaredClass,Os=(o,t,e,s)=>{let r=se(t);if(s?.once){let n=`${o}${r}${e}`;if(te.has(n))return;te.add(n)}let i;if(s?.detail){i={};for(let[n,a]of Object.entries(s.detail))if((typeof a=="object"||typeof a=="function")&&a!==null){let l=new WeakRef(a);Object.defineProperty(i,n,{enumerable:!0,get(){return l.deref()}})}else i[n]=a;ee?.log.interceptors?.forEach(n=>n(o,r,e,i)),console[o](`[${r}]: ${e}`,i)}else ee?.log.interceptors?.forEach(n=>n(o,r,e)),console[o](`[${r}]: ${e}`)},oe=o=>{let t=`[${se(o)}] `;return e=>{let s=e instanceof Error&&e.message?e:new Error(String(e));s.message=`${t}${s.message}`,setTimeout(()=>{throw e})}};var p=(o,t,...e)=>{try{return o?.call(t,...e)}catch(s){console.error(s,o)}},W=async(o,t,...e)=>{try{return await o?.call(t,...e)}catch(s){console.error(s,o)}};var q=Symbol.for("controller"),Le=o=>typeof o=="object"&&o!==null&&(q in o||"hostConnected"in o||"hostDisconnected"in o||"hostUpdate"in o||"hostUpdated"in o),Ps=o=>typeof o?.then=="function";var F,D=o=>{F!==o&&(F=o,queueMicrotask(()=>F===o?F=void 0:0))},G=o=>F,N=[],re=o=>{if(o===void 0){N=[];return}let t=N.indexOf(o);N=t===-1?[...N,o]:N.slice(0,t+1),queueMicrotask(()=>N=[])},ie=()=>N,U,Ns=o=>{U!==o&&(U=o,queueMicrotask(()=>U===o?U=void 0:0))},Ue=()=>{let o=U;return U=void 0,o},ne=async(o,t)=>{let e=ct(o);if(e===void 0)return o;if(await e.ready,typeof t=="function"){let s=e.watchExports(r=>t(r,s))}return e.exports},ae=async o=>{let t=ct(o);return await t.ready,t},ct=o=>{let e=G().manager.X(o);if(e!==void 0)return e;if(Le(o))return o;let s=Ue();if(s!==void 0)return s},lt=!1,Ds=o=>{lt=!0;try{return o()}finally{lt=!1}};var b=class{constructor(){this.promise=new Promise((t,e)=>{this.resolve=t,this.reject=e})}};var le=(o,t)=>{let e=t>Re?Me:t/Ie,s=0,r=setInterval(()=>{s+=e,s>=t&&(clearInterval(r),o())},e);return r},Re=4e3,Me=2e3,Ie=4;var ke=(o,t,e)=>{let s=Object.keys(o),r=s.length;R===void 0&&queueMicrotask(M),R??=new Map;let i=R.get(o);return i===void 0&&(i={callbacks:[],keyCount:r},R.set(o,i)),i.keyCount!==r&&(i.callbacks.forEach(n=>n(s)),i.callbacks=[],i.keyCount=r),i.callbacks.push(n=>{let a=h=>p(t,null,h),l=n[r];l===void 0?a(void 0):o[l]===e?a(l):a(void 0)}),e},R,M=()=>{R?.forEach(({callbacks:o},t)=>{let e=Object.keys(t);o.forEach(s=>s(e))}),R=void 0},je=(o,t,e)=>{let s=o.manager;return s.V!==d&&s.V!==e&&s.S(void 0,void 0),s.T.length===0&&queueMicrotask(()=>s.S(void 0,void 0)),s.V=e,s.T.push((r,i)=>p(t,void 0,e===i?r:void 0)),e},He=(o=[G(),...ie()],t,e)=>{let s=Array.isArray(o)?o:[o],r=s.length+1,i=n=>{r-=1,n!==void 0&&(r=Math.min(r,0)),r===0&&t(n)};s.forEach(n=>ke(n,a=>i(a===void 0?void 0:{key:a,host:n,isReactive:!1}),e));for(let n of s)if("manager"in n&&n.manager.component===n){je(n,a=>i(a===void 0?void 0:{key:a,host:n,isReactive:!0}),e);break}return e},Ve=(o="",t={},e=G())=>{let s={emit:r=>{o===""&&M();let i=new CustomEvent(o,{detail:r,cancelable:!0,bubbles:!0,composed:!0,...t});return e.el.dispatchEvent(i),i}};return o===""&&He(void 0,r=>o=r.key,s),s},ze=Ve.bind(null,""),de;de=q;var Tt=class{constructor(t){this.#t=[],this.#e=[],this.#s=[],this.#r=[],this.#i=[],this.#l=[],this.#c=[],this.#d=[],this.#n=[],this.#p=!1,this.P=new b,this.connectedCalled=!1,this.loadedCalled=!1,this[de]=!0,this.#h=[];let e=this,s=t??G(new.target.name);e.#o=s,e.ready=e.P.promise,e.#a=he(e),e.component=s,e.#o.addController(e),e.#o.manager===void 0||(re(e),queueMicrotask(()=>e.catchUpLifecycle()))}#t;#e;#s;#r;#i;#l;#c;#d;#n;#p;#o;catchUpLifecycle(){let{manager:t}=this.#o;t.connectedCalled&&!this.connectedCalled&&this.triggerConnected(),t.#p&&this.triggerLoad().then(()=>t.loadedCalled&&this.triggerLoaded()).catch(oe(this.#o))}#a;get exports(){return this.#a}set exports(t){let e=this.#a;e!==t&&(this.#a=t,this.#h.forEach(p),this.connectedCalled&&this.O!==!1&&this.#o.requestUpdate(this.O,e)),this.P.resolve(t)}setProvisionalExports(t,e=!0){this.#a=e?he(t):t,this.#h.forEach(p)}#h;watchExports(t){let e=()=>t(this.#a);return this.#h.push(e),()=>{this.#h.splice(this.#h.indexOf(e),1)}}get use(){return D(this.#o),ne}get useRef(){return D(this.#o),ae}get useRefSync(){return D(this.#o),ct}controllerRemoved(){this.#o.el.isConnected&&this.triggerDisconnected(),this.triggerDestroy()}onConnected(t){this.#t.push(t)}onDisconnected(t){this.#e.push(t)}onLoad(t){this.#s.push(t)}onLoaded(t){this.#r.push(t)}onUpdate(t){this.#i.push(t)}onUpdated(t){this.#l.push(t)}onDestroy(t){this.#c.push(t)}onLifecycle(t){this.#d.push(t),this.connectedCalled&&this.#o.el.isConnected&&this.#u(t)}triggerConnected(){let t=this;t.hostConnected&&p(t.hostConnected,t),t.#t.forEach(p),t.triggerLifecycle(),t.connectedCalled=!0}triggerDisconnected(){let t=this;t.hostDisconnected&&p(t.hostDisconnected,t),t.#e.forEach(p),t.#n.forEach(p),t.#n=[]}async triggerLoad(){if(this.#p)return;this.#p=!0;let t=this;t.hostLoad&&await W(t.hostLoad,t),this.#s.length>0&&await Promise.allSettled(this.#s.map(W)),this.P.resolve(this.#a)}triggerLoaded(){this.loadedCalled||(this.hostLoaded&&p(this.hostLoaded,this),this.#r.forEach(p),this.loadedCalled=!0)}triggerUpdate(t){this.hostUpdate&&p(this.hostUpdate,this,t),this.#i.forEach(ce,t)}triggerUpdated(t){this.hostUpdated&&p(this.hostUpdated,this,t),this.#l.forEach(ce,t)}triggerDestroy(){this.hostDestroy&&p(this.hostDestroy,this),this.#c.forEach(p)}triggerLifecycle(){this.hostLifecycle&&this.#u(()=>this.hostLifecycle()),this.#d.forEach(this.#u,this)}#u(t){D(this.#o);let e=p(t);(Array.isArray(e)?e:[e]).forEach(r=>{typeof r=="function"?this.#n.push(r):typeof r=="object"&&typeof r.remove=="function"&&this.#n.push(r.remove)})}};function ce(o){p(o,void 0,this)}var pe=Tt,he=o=>{if(typeof o!="object"&&typeof o!="function"||o===null)return o;let t={get(s,r,i){if(!((r==="exports"||r==="_exports")&&r in s&&s[r]===e)&&(r in s||r in Promise.prototype||typeof r=="symbol"))return typeof s=="function"?s[r]:Reflect.get(s,r,i)}},e=new Proxy(o,t);return e};var{I:zs}=Zt;var ht=o=>o.strings===void 0;var Be={},ue=(o,t=Be)=>o._$AH=t;var y={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},$=o=>(...t)=>({_$litDirective$:o,values:t}),g=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,s){this._$Ct=t,this._$AM=e,this._$Ci=s}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}};var K=(o,t)=>{let e=o._$AN;if(e===void 0)return!1;for(let s of e)s._$AO?.(t,!1),K(s,t);return!0},dt=o=>{let t,e;do{if((t=o._$AM)===void 0)break;e=t._$AN,e.delete(o),o=t}while(e?.size===0)},fe=o=>{for(let t;t=o._$AM;o=t){let e=t._$AN;if(e===void 0)t._$AN=e=new Set;else if(e.has(o))break;e.add(o),qe(t)}};function We(o){this._$AN!==void 0?(dt(this),this._$AM=o,fe(this)):this._$AM=o}function Fe(o,t=!1,e=0){let s=this._$AH,r=this._$AN;if(r!==void 0&&r.size!==0)if(t)if(Array.isArray(s))for(let i=e;i<s.length;i++)K(s[i],!1),dt(s[i]);else s!=null&&(K(s,!1),dt(s));else K(this,o)}var qe=o=>{o.type==y.CHILD&&(o._$AP??=Fe,o._$AQ??=We)},pt=class extends g{constructor(){super(...arguments),this._$AN=void 0}_$AT(t,e,s){super._$AT(t,e,s),fe(this),this.isConnected=t._$AU}_$AO(t,e=!0){t!==this.isConnected&&(this.isConnected=t,t?this.reconnected?.():this.disconnected?.()),e&&(K(this,t),dt(this))}setValue(t){if(ht(this._$Ct))this._$Ct._$AI(t,this);else{let e=[...this._$Ct._$AH];e[this._$Ci]=t,this._$Ct._$AI(e,this,0)}}disconnected(){}reconnected(){}};var Xs=()=>new Pt,Pt=class{},St=new WeakMap,Nt=$(class extends pt{render(o){return d}update(o,[t]){let e=t!==this.G;return e&&this.G!==void 0&&this.rt(void 0),(e||this.lt!==this.ct)&&(this.G=t,this.ht=o.options?.host,this.rt(this.ct=o.element)),d}rt(o){if(this.isConnected||(o=void 0),typeof this.G=="function"){let t=this.ht??globalThis,e=St.get(t);e===void 0&&(e=new WeakMap,St.set(t,e)),e.get(this.G)!==void 0&&this.G.call(this.ht,void 0),e.set(this.G,o),o!==void 0&&this.G.call(this.ht,o)}else this.G.value=o}get lt(){return typeof this.G=="function"?St.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var xt=o=>{let t=o;for(;t=t.parentNode??t.host;)if(t?.constructor?.lumina){let e=t;return e.manager?.loadedCalled||(e.J??e._offspring).push(o),(e.I??e._postLoad).promise}return!1},Lt={};function Ut(){}function Rt(o){for(let t of["Associated","Disabled","Reset","StateRestore"]){let e=`orm${t}Callback`;o.prototype["f"+e]=async function(...s){await this.componentOnReady(),(this.el??this).dispatchEvent(new CustomEvent(`luminaF${e}`,{detail:s}))}}}var Ke=(o,t)=>function(s,r){if(!globalThis.customElements)return;let n=(r??s??{}).resourcesUrl;n&&o.setAssetPath(n);for(let[a,[l,h="",u=0]]of Object.entries(t)){if(customElements.get(a))continue;let[c,m,v]=h.split(";"),C=c?c?.split(",").map(Je):void 0,yt=C?.map(([x])=>x),Q=class extends Dt{static{this.formAssociated=u===1}static{this.observedAttributes=C?.map(([,x])=>x).filter(x=>x!=="")}static{this.C=yt}static{this.E=m?m?.split(","):void 0}static{this.D=v?.split(",")}static{this.L=a}static{this.K=o}constructor(){!Q.B&&(Q.B=l(),Q.F()),super()}};customElements.define(a,Q)}},ut=Object.defineProperty,Je=o=>{let t=o.split(":");return t.length===1?[t[0],Y(t[0])]:t},Qe=globalThis.HTMLElement??Ut,Dt=class extends Qe{constructor(){super(),this.#e={},this.#s=[],this.I=new b,this.H=new b,this.J=[];let t=this,e=t.constructor;t._offspring=t.J,t._postLoad=t.I,e.C?.forEach(s=>{Object.hasOwn(t,s)&&(t.#e[s]=t[s],delete t[s])}),e.A?t.#r({a:e.A}):e.B.then(async s=>{await e.K.p,t.#r(await(s.default?.then(r=>typeof r=="function"?{a:r}:r)??s))}).catch(s=>{t.H.reject(s),setTimeout(()=>{throw s})})}static{this.lumina=!0}static F(){for(let t of this.C??[])ut(this.prototype,t,{configurable:!0,enumerable:!0,get(){return this.#e[t]},set(e){this.#e[t]=e}});for(let t of this.E??[])ut(this.prototype,t,{async value(...e){return this.#t||await this.H.promise,await this.#t[t](...e)},configurable:!0});for(let t of this.D??[])ut(this.prototype,t,{value(...e){return this.#t[t](...e)},configurable:!0})}static{Rt(this)}#t;#e;#s;get manager(){return this.#t?.manager}attributeChangedCallback(t,e,s){this.#t?.attributeChangedCallback(t,e,s),this.#t||this.#s.push(t)}connectedCallback(){this.#t?this.#t.connectedCallback?.():queueMicrotask(()=>this.G=xt(this))}disconnectedCallback(){this.#t?.disconnectedCallback?.()}async componentOnReady(){return await this.H.promise,this}#r(t){let e=this.constructor,s=e.L,r=this.#e,i=Object.values(t).find(c=>c.L===s),n=`${s}--lazy`,a=i;for(;a&&!Object.hasOwn(a,"lumina");)a=Object.getPrototypeOf(a);Xe(a),!e.A&&(e.A=i,customElements.define(n,i)),i.N=this;let h=document.createElement(n);i.N=void 0,this.#t=h,this.#e=h,this.#s.forEach(c=>h.attributeChangedCallback(c,null,this.getAttribute(c))),Object.entries(r).forEach(Ye,h);let u=this.isConnected;(u||this.G)&&(h.connectedCallback?.(),u||h.disconnectedCallback())}addController(){}requestUpdate(){this.#t?.requestUpdate()}};function Ye([o,t]){this[o]=t}var Xe=o=>{let t=o.prototype,e=Element.prototype;Object.hasOwn(t,"isConnected")||(t.setAttribute=function(r,i){e.setAttribute.call(this.el,r,i)},t.removeAttribute=function(r){e.removeAttribute.call(this.el,r)},t.hasAttribute=function(r){return e.hasAttribute.call(this.el,r)},ut(t,"isConnected",{get(){return Reflect.get(e,"isConnected",this.el)}}))};var ft=class extends pe{constructor(t){super(t),this.destroyed=!1,this.R=!1,this.V=d,this.T=[],this.#s=new WeakMap,this.#e=t,this.exports=void 0,this.hasDestroy=mt in t&&typeof t.destroy=="function",E.prototype.addController.call(t,{hostConnected:()=>{if(this.destroyed){let e=t.el.localName;throw t.el.remove(),new Error(`The ${e} component has already been destroyed. It cannot be used again. If you meant to disconnect and reconnect a component without automatic destroy, set the ${mt} prop.`)}this.#t!==void 0&&clearTimeout(this.#t),M();for(let e of t.M)"triggerConnected"in e?e.triggerConnected():p(e.hostConnected,e)},hostDisconnected:()=>{for(let e of t.M)"triggerDisconnected"in e?e.triggerDisconnected():p(e.hostDisconnected,e);this.hasDestroy&&!this.destroyed&&this.U()},hostUpdate:()=>{for(let e of t.M)"triggerUpdate"in e?e.triggerUpdate(this.Q):p(e.hostUpdate,e,this.Q)},hostUpdated:()=>{for(let e of t.M)"triggerUpdated"in e?e.triggerUpdated(this.Q):p(e.hostUpdated,e,this.Q);this.Q=void 0}}),queueMicrotask(()=>this.R=!0),D(t)}#t;#e;async destroy(){if(!this.destroyed){this.#e.el.isConnected&&(this.hasDestroy=!1,this.#e.el.remove()),this.#t=void 0,this.destroyed=!0;for(let t of this.#e.M)"triggerDestroy"in t?t.triggerDestroy():p(t.hostDestroy,t);this.#e.M.splice(0)}}U(){if(this.#t!==void 0&&clearTimeout(this.#t),!this.#e.el.isConnected&&!this.#e.autoDestroyDisabled){let t=()=>{this.#e.destroy()};this.#t=le(t,Ze)}}S(t,e){let s=this.T;this.V=d,this.T=[],s.forEach(r=>r(t,e))}#s;W(t,e){(typeof e=="object"&&e!==null||typeof e=="function")&&this.#s.set(e,t)}X(t){if(typeof t=="object"&&t!==null||typeof t=="function")return this.#s.get(t)}},Ze=1e3,mt="autoDestroyDisabled";var ye=$(class extends g{constructor(o){if(super(o),o.type!==y.ATTRIBUTE||o.name!=="class"||o.strings?.length>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(o){return" "+Object.keys(o).filter(t=>o[t]).join(" ")+" "}update(o,[t]){if(this.st===void 0){this.st=new Set,o.strings!==void 0&&(this.nt=new Set(o.strings.join(" ").split(/\s/).filter(s=>s!=="")));for(let s in t)t[s]&&!this.nt?.has(s)&&this.st.add(s);return this.render(t)}let e=o.element.classList;for(let s of this.st)s in t||(e.remove(s),this.st.delete(s));for(let s in t){let r=!!t[s];r===this.st.has(s)||this.nt?.has(s)||(r?(e.add(s),this.st.add(s)):(e.remove(s),this.st.delete(s)))}return f}});var ge="important",ts=" !"+ge,es=$(class extends g{constructor(o){if(super(o),o.type!==y.ATTRIBUTE||o.name!=="style"||o.strings?.length>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(o){return Object.keys(o).reduce((t,e)=>{let s=o[e];return s==null?t:t+`${e=e.includes("-")?e:e.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,"-$&").toLowerCase()}:${s};`},"")}update(o,[t]){let{style:e}=o.element;if(this.ft===void 0)return this.ft=new Set(Object.keys(t)),this.render(t);for(let s of this.ft)t[s]==null&&(this.ft.delete(s),s.includes("-")?e.removeProperty(s):e[s]=null);for(let s in t){let r=t[s];if(r!=null){this.ft.add(s);let i=typeof r=="string"&&r.endsWith(ts);s.includes("-")||i?e.setProperty(s,i?r.slice(0,-11):r,i?ge:""):e[s]=r}}return f}});var ss=$(class extends g{constructor(o){if(super(o),o.type!==y.PROPERTY&&o.type!==y.ATTRIBUTE&&o.type!==y.BOOLEAN_ATTRIBUTE)throw Error("The `live` directive is not allowed on child or event bindings");if(!ht(o))throw Error("`live` bindings can only contain a single expression")}render(o){return o}update(o,[t]){if(t===f||t===d)return t;let e=o.element,s=o.name;if(o.type===y.PROPERTY){if(t===e[s])return f}else if(o.type===y.BOOLEAN_ATTRIBUTE){if(!!t===e.hasAttribute(s))return f}else if(o.type===y.ATTRIBUTE&&e.getAttribute(s)===t+"")return f;return ue(o),t}});var ve=class o extends E{constructor(){super(),this.M=[],this.manager=new ft(this);let t=this,e=t.constructor,s=e.N,r=e.K.o,i=o.prototype.shouldUpdate;t.#r=s?.H??new b,t.I=s?.I??new b,t.J=s?.J??[],t._offspring=t.J,t._postLoad=t.I,t.el=s??t,t.#s=t.enableUpdating,t.enableUpdating=Ut,t.shouldUpdate!==i&&(t.#e=t.shouldUpdate,t.shouldUpdate=i),r&&(t.#t=new Map,e.elementProperties.forEach((n,a)=>t.#t.set(a,r()))),!1}static finalizeStyles(t){let e=super.finalizeStyles(t),s=this.shadowRootOptions===Lt;return this.K?.commonStyles===void 0||s?e:[this.K.commonStyles,...e]}static createProperty(t,e){let s=typeof e=="number"?e:Array.isArray(e)?e[0]:0,r=Array.isArray(e)?e[1]:void 0,i=r?.hasChanged??j,n={attribute:s&1&&typeof t=="string"?Y(t):!1,reflect:!!(s&2),type:s&4?Boolean:s&8?Number:void 0,state:!!(s&16),readOnly:!!(s&32),noAccessor:!!(s&64),useDefault:!!(s&128),c:!1,...r,hasChanged(a,l){let h=i(a,l);return n.c=h,h}};super.createProperty(t,n)}static getPropertyDescriptor(t,e,s){let r=this.K,i=super.getPropertyDescriptor(t,e,s);return s.d=i,{...i,get(){return r.t?.(this.#t.get(t)),i.get?.call(this)},set(n){let a=this.manager;if(s.readOnly&&!lt&&(a.R||a.connectedCalled))throw Error(`Cannot assign to read-only property "${t}" of ${this.el.localName}. Trying to assign "${n}"`);i.set.call(this,n??void 0),s.c&&this.#t?.get(t)?.notify(),a.T.length>0&&(M(),a?.S(t,n))}}}static{this.lumina=!0}static{Rt(this)}#t;#e;#s;#r;#i;#l;get elementInternals(){return this.#l??=this.el.attachInternals(),this.#l}connectedCallback(){this.hasAttribute("defer-hydration")||this.#c(!0)}#c(t){let e=this.constructor.K.c?.(()=>this.requestUpdate());this.#i=e;let s=!this.manager.connectedCalled;t&&super.connectedCallback(),s?queueMicrotask(()=>this.#n().catch(r=>{this.#r.reject(r),setTimeout(()=>{throw r})})):e&&this.requestUpdate()}#d(t){try{this.#i.clear(),this.constructor.K.r(this.#i,()=>super.update(t))}catch(e){throw this.#i.clear(),e}}disconnectedCallback(){super.disconnectedCallback(),this.#i?.destroy(),this.#i=void 0}createRenderRoot(){let t=this.el.shadowRoot,e=this.constructor,s=e.shadowRootOptions,i=t??(s===Lt?this.el:this.el.attachShadow(s));if(t)return this.manager.connectedCalled||this.#c(!1),E.prototype.createRenderRoot.call(this),t;if(this.isConnected){let n=i.getRootNode();n.adoptedStyleSheets=[...n.adoptedStyleSheets,...e.elementStyles.map(a=>"styleSheet"in a?a.styleSheet:a)]}return i}async#n(){let t=this.el.G??xt(this.el);t&&await t;let e=[];for(let r of this.M)"triggerLoad"in r?e.push(r.triggerLoad()):e.push(W(r.hostLoad,r));await Promise.all(e),await this.load?.(),this.manager.hasDestroy&&this.manager.onUpdate(r=>r.has(mt)&&this.manager.U()),this.#s(!0),this.performUpdate(),this.I.resolve(),await 0;let s=this.J.filter(r=>!r.manager?.loadedCalled);s.length&&await Promise.allSettled(s.map(async r=>await r.componentOnReady())),this.J.length=0,this.el.setAttribute(this.constructor.K.hydratedAttribute,"");for(let r of this.M)"triggerLoaded"in r?r.triggerLoaded():p(r.hostLoaded,r);this.loaded?.(),this.#r.resolve()}shouldUpdate(t){return this.manager.Q=t,this.#e?.(t)??!0}update(t){this.#i?this.#d(t):super.update(t)}listen(t,e,s){let r=e?.bind(this)??e;this.manager.onLifecycle(()=>(this.el.addEventListener(t,r,s),()=>this.el.removeEventListener(t,r,s)))}listenOn(t,e,s,r){let i=s?.bind(this)??s;this.manager.onLifecycle(()=>(t.addEventListener(e,i,r),()=>t.removeEventListener(e,i,r)))}async componentOnReady(){return await this.#r.promise,this}addController(t){this.M.push(t),!(q in t)&&this.renderRoot&&this.el.isConnected&&t.hostConnected?.()}removeController(t){this.M.splice(this.M.indexOf(t),1),t.controllerRemoved?.()}};var $e=o=>{let t,e=r=>{t=new URL(r,globalThis.location?.href||void 0).href},s={...o,getAssetPath(r){let i=new URL(r,t);return i.origin!==globalThis.location?.origin?i.href:i.pathname},setAssetPath:e,customElement(r,i){i.K=s,i.L=r,customElements.get(r)||customElements.define(r,i)}};return e(o.defaultAssetPath),s};var $r=o=>typeof o=="object"&&o!=null?ye(o):o;var Mt=class extends g{#t;#e;constructor(t){super(t);let e=this;this.#e=function(r){return e.#t.call(this,r)}}render(t){return typeof t=="function"?(this.#t=t,Nt(this.#e)):Nt(t)}},br=$(Mt);var _r=d;var J=$e({defaultAssetPath:"https://js.geoscene.cn/5.1/ai-components/",hydratedAttribute:"hydrated"}),{customElement:Tr,getAssetPath:Sr,setAssetPath:Pr}=J;J.t=void 0;J.o=void 0;J.c=void 0;J.r=void 0;export{Ps as a,D as b,re as c,ie as d,Ns as e,Ds as f,be as g,ds as h,f as i,d as j,Os as k,oe as l,He as m,ze as n,Tt as o,Ke as p,y as q,$ as r,g as s,Xs as t,Nt as u,ve as v,$r as w,_r as x,J as y,Tr as z,Sr as A};
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT GeoScene - https://js.geoscene.cn/5.1/LICENSE.txt */
2
- import c from"./7WSTR3WA.js";import b from"./ZGUVZMYR.js";import a from"./PFW7KXCP.js";import{a as n}from"./KGYSBUFO.js";import{a as I,b as S,ta as N}from"./H3EEFM4A.js";import{Z as $}from"./4ASZF5I2.js";export default $geoscene.t(([,,,,,,P,U,{p:k,r:T},{C:M,D:z,E:L,F:D,G:F,H:O,a:A,m:w,n:R,o:y,p:V},b])=>{var W=async(e,t)=>(await n({text:"退出数据探索 Agent"},t),e),B=async(e,t)=>{await n({text:"正在请求模型生成图层过滤操作"},t);let a=await w("data_explore_filter_prompt");if(!t?.configurable)throw new Error("图层过滤工具需要 config.configurable");let{userTimezone:d,userTimezoneOffset:o}=L(),s={layerFieldInfo:e.layerFieldInfo,userTimezone:d,userTimezoneOffset:o,queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},i=await T({promptText:a,modelTier:"advanced",config:t,messages:e.dataExplorationMessages,inputVariables:s,tools:F}),r=[...e.dataExplorationMessages,i];if(!((i.tool_calls?.length??0)>0))return await n({text:"模型判断无需修改过滤条件"},t),{...e,dataExplorationMessages:r};let c=r,l=i.content.toString();return await b(i,t),{...e,dataExplorationMessages:c,outputMessage:l}},H=async(e,t)=>{await n({text:"正在请求模型规划图层查询"},t);let a=await w("data_explore_query_prompt");if(!t?.configurable)throw new Error("图层查询工具需要 config.configurable");let{userTimezone:d,userTimezoneOffset:o}=L(),s=e.agentExecutionContext.sharedState,i=s.lastNavigatedFeatures?.value,r=s.lastResolvedLocation?.value,c="none";if(i!=null)try{c=JSON.stringify(i)}catch{c="none"}let l="none";if(r!=null)try{l=JSON.stringify({address:r.address,location:r.location})}catch{l="none"}let g={layerFieldInfo:e.layerFieldInfo,userTimezone:d,userTimezoneOffset:o,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,lastNavigatedFeatures:c,lastResolvedLocation:l},m=await T({promptText:a,modelTier:"advanced",config:t,messages:e.dataExplorationMessages,inputVariables:g,tools:D}),h=(m.tool_calls?.length??0)>0,f=m.content.toString();return await b(m,t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,m],...h?{}:{outputMessage:f},status:"success",summary:f&&!h?R(f):"查询规划完成。"}},J=async(e,t)=>{try{await n({text:"正在请求模型汇总查询结果"},t);let a=await w("summarize_query_response_prompt"),d={queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},o=await k({promptText:a,modelTier:"fast",config:t,messages:e.dataExplorationMessages,inputVariables:d}),s=typeof o=="string"?o:o.content,i=new $(s);await n({text:`收到模型响应:${s}`},t);let r=s;return{...e,outputMessage:r,status:"success",summary:r?R(r):"摘要已生成。",dataExplorationMessages:[...e.dataExplorationMessages,i]}}catch(a){throw await n({text:"请求过滤模型时出错"},t),new Error(`请求过滤模型时出错:${a instanceof Error?a.message:String(a)}`)}};async function K(e,t){if((e.queryResponse??[]).some(d=>{let o=d.details;return typeof o=="object"&&o!==null&&"error"in o}))return await n({text:"查询结果包含错误,跳过图层过滤工具。"},t),{...e};let a=await new A(F,{handleToolErrors:!1}).invoke({messages:e.dataExplorationMessages},t);return await n({text:`图层过滤工具执行完成:${a.messages.map(d=>d.content).join(", ")}`},t),{...e}}var X=10,Y=["string","small-integer","integer"],Z=async(e,t,{includeSummaryStatistics:a=!0,includeUniqueValues:d=!0}={})=>{let o=null,s=null;try{if(t.type!=="geometry"&&t.type!=="oid"&&t.type!=="global-id"){a&&(o=await P({layer:e,field:t.name}));let i=t.domain?.type==="coded-value"?t.domain:null;d&&(Y.includes(t.type)||i)&&(s=(await U({layer:e,field:t.name})).uniqueValueInfos.sort((r,c)=>c.count-r.count).slice(0,X),i&&(s=s.map(r=>({...r,value:i.getName(r.value)??r.value}))))}}catch(i){console.error(`获取字段统计信息失败,字段:${t.name}:`,i)}return{summaryStatistics:o,uniqueValues:s}};function ee(e,t){return["string","small-integer","integer"].includes(e)||t==="coded-value"}async function te(e,t,a,d=!0){let o=[],s=[],i=[];for(let r of e){let c=function(p){let u=t.get(p)?.layerItem;return u?[u.name&&`名称:${u.name}`,u.title&&`标题:${u.title}`,u.description&&`说明:${u.description}`].filter(Boolean).join(" | "):p},{layerId:l,results:g}=r,m=a.map?.allLayers.find(p=>p.id===l),h=t.get(l)?.fieldRegistry;if(!h)continue;let f=o.find(p=>p.layerId===l);f||(f={layerId:l,layerSummary:c(l),fieldInfos:[]},o.push(f));for(let p of g){let u=h.get(p.name);if(!u)continue;let x=u.statistics,v=d&&!x?.summaryStatistics,q=ee(u.type,u.domain?.type)&&!x?.uniqueValues,_=v||q;if(i.push({layerId:l,fieldName:u.name,didFetchStatistics:_}),_){let G=Z(m,u,{includeSummaryStatistics:v,includeUniqueValues:q}).then(C=>{let E={summaryStatistics:x?.summaryStatistics??null,uniqueValues:x?.uniqueValues??null};v&&(E.summaryStatistics=C.summaryStatistics),q&&(E.uniqueValues=C.uniqueValues),h.set(u.name,{...u,statistics:E}),u.statistics=E});s.push(G)}f.fieldInfos.push(u)}}return await Promise.all(s),{layerFieldInfo:o,didFetchStatistics:s.length>0,fieldStatisticsFetchStatus:i}}var j=/\b(average|avg|mean|median|max(?:imum)?|min(?:imum)?|sum|total|count|std(?:dev|\s*deviation)|variance|null\s*count|missing\s*values?|range)\b/iu;function ae(e,t){return j.test(e)||j.test(t)}var se=async(e,t)=>{try{await n({text:"正在为向量搜索结果准备字段信息"},t);let a=y(t,"layersAndFieldsRegistry"),{mapView:d}=z(t),{assignedTask:o,userRequest:s}=e.agentExecutionContext,i=ae(o,s),{layerFieldInfo:r,didFetchStatistics:c,fieldStatisticsFetchStatus:l}=await te(e.vectorSearchFieldResults,a,d,i);c?await n({text:"已获取统计信息"},t):await n({text:"跳过统计"},t);for(let g of l)await n({text:` - ${g.fieldName}——统计状态:${g.didFetchStatistics?"已获取":"已跳过"}`},t);return await n({text:"字段信息准备完成"},t),{...e,layerFieldInfo:r}}catch(a){throw await n({text:"获取统计信息失败"},t),new Error(`获取统计信息失败:${a instanceof Error?a.message:String(a)}`)}},Q=.5,re=10,ie=async(e,t)=>{try{await n({text:"正在通过相似度搜索字段"},t);let a=y(t,"fieldSearch"),d=y(t,"layersAndFieldsRegistry"),o=y(t,"embeddingCache"),s=await a.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:Q,topResults:re,embeddingCache:o}),i=s.map(({layerId:c,results:l})=>{let g=l.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
2
+ import c from"./7WSTR3WA.js";import b from"./ZGUVZMYR.js";import a from"./PFW7KXCP.js";import{a as n}from"./KGYSBUFO.js";import{a as I,b as S,ta as N}from"./H3EEFM4A.js";import{Z as $}from"./4ASZF5I2.js";export default $geoscene.t(([,,,,,,P,U,{p:k,r:T},{C:M,D:z,E:L,F:D,G:F,H:O,a:A,m:w,n:R,o:y,p:V},b])=>{var W=async(e,t)=>(await n({text:"退出数据探索 Agent"},t),e),B=async(e,t)=>{await n({text:"正在请求模型生成图层过滤操作"},t);let a=await w("data_explore_filter_prompt");if(!t?.configurable)throw new Error("图层过滤工具需要 config.configurable");let{userTimezone:d,userTimezoneOffset:o}=L(),s={layerFieldInfo:e.layerFieldInfo,userTimezone:d,userTimezoneOffset:o,queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},i=await T({promptText:a,modelTier:"advanced",config:t,messages:e.dataExplorationMessages,inputVariables:s,tools:F}),r=[...e.dataExplorationMessages,i];if(!((i.tool_calls?.length??0)>0))return await n({text:"模型判断无需修改过滤条件"},t),{...e,dataExplorationMessages:r};let c=r,l=i.content.toString();return await b(i,t),{...e,dataExplorationMessages:c,outputMessage:l}},H=async(e,t)=>{await n({text:"正在请求模型规划图层查询"},t);let a=await w("data_explore_query_prompt");if(!t?.configurable)throw new Error("图层查询工具需要 config.configurable");let{userTimezone:d,userTimezoneOffset:o}=L(),s=e.agentExecutionContext.sharedState,i=s.lastNavigatedFeatures?.value,r=s.lastResolvedLocation?.value,c="none";if(i!=null)try{c=JSON.stringify(i)}catch{c="none"}let l="none";if(r!=null)try{l=JSON.stringify({address:r.address,location:r.location})}catch{l="none"}let g={layerFieldInfo:e.layerFieldInfo,userTimezone:d,userTimezoneOffset:o,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,lastNavigatedFeatures:c,lastResolvedLocation:l},m=await T({promptText:a,modelTier:"advanced",config:t,messages:e.dataExplorationMessages,inputVariables:g,tools:D}),h=(m.tool_calls?.length??0)>0,f=m.content.toString();return await b(m,t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,m],...h?{}:{outputMessage:f},status:"success",summary:f&&!h?R(f):"查询规划完成。"}},J=async(e,t)=>{try{await n({text:"正在请求模型汇总查询结果"},t);let a=await w("summarize_query_response_prompt"),d={queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},o=await k({promptText:a,modelTier:"fast",config:t,messages:e.dataExplorationMessages,inputVariables:d}),s=typeof o=="string"?o:o.content,i=new $(s);await n({text:`收到模型响应:${s}`},t);let r=s;return{...e,outputMessage:r,status:"success",summary:r?R(r):"摘要已生成。",dataExplorationMessages:[...e.dataExplorationMessages,i]}}catch(a){throw await n({text:"请求过滤模型时出错"},t),new Error(`请求过滤模型时出错:${a instanceof Error?a.message:String(a)}`)}};async function K(e,t){if((e.queryResponse??[]).some(d=>{let o=d.details;return typeof o=="object"&&o!==null&&"error"in o}))return await n({text:"查询结果包含错误,跳过图层过滤工具。"},t),{...e};let a=await new A(F,{handleToolErrors:!1}).invoke({messages:e.dataExplorationMessages},t);return await n({text:`图层过滤工具执行完成:${a.messages.map(d=>d.content).join(", ")}`},t),{...e}}var X=10,Y=["string","small-integer","integer"],Z=async(e,t,{includeSummaryStatistics:a=!0,includeUniqueValues:d=!0}={})=>{let o=null,s=null;try{if(t.type!=="geometry"&&t.type!=="oid"&&t.type!=="global-id"){a&&(o=await P({layer:e,field:t.name}));let i=t.domain?.type==="coded-value"?t.domain:null;d&&(Y.includes(t.type)||i)&&(s=(await U({layer:e,field:t.name})).uniqueValueInfos.sort((r,c)=>c.count-r.count).slice(0,X),i&&(s=s.map(r=>({...r,value:i.getName(r.value)??r.value}))))}}catch(i){console.error(`获取字段统计信息失败,字段:${t.name}:`,i)}return{summaryStatistics:o,uniqueValues:s}};function ee(e,t){return["string","small-integer","integer"].includes(e)||t==="coded-value"}async function te(e,t,a,d=!0){let o=[],s=[],i=[];for(let r of e){let c=function(p){let u=t.get(p)?.layerItem;return u?[u.name&&`名称:${u.name}`,u.title&&`标题:${u.title}`,u.description&&`说明:${u.description}`].filter(Boolean).join(" | "):p},{layerId:l,results:g}=r,m=a.map?.allLayers.find(p=>p.id===l),h=t.get(l)?.fieldRegistry;if(!h)continue;let f=o.find(p=>p.layerId===l);f||(f={layerId:l,layerSummary:c(l),fieldInfos:[]},o.push(f));for(let p of g){let u=h.get(p.name);if(!u)continue;let x=u.statistics,v=d&&!x?.summaryStatistics,q=ee(u.type,u.domain?.type)&&!x?.uniqueValues,_=v||q;if(i.push({layerId:l,fieldName:u.name,didFetchStatistics:_}),_){let G=Z(m,u,{includeSummaryStatistics:v,includeUniqueValues:q}).then(C=>{let E={summaryStatistics:x?.summaryStatistics??null,uniqueValues:x?.uniqueValues??null};v&&(E.summaryStatistics=C.summaryStatistics),q&&(E.uniqueValues=C.uniqueValues),h.set(u.name,{...u,statistics:E}),u.statistics=E});s.push(G)}f.fieldInfos.push(u)}}return await Promise.all(s),{layerFieldInfo:o,didFetchStatistics:s.length>0,fieldStatisticsFetchStatus:i}}var j=/\b(average|avg|mean|median|max(?:imum)?|min(?:imum)?|sum|total|count|std(?:dev|\s*deviation)|variance|null\s*count|missing\s*values?|range)\b/iu;function ae(e,t){return j.test(e)||j.test(t)}var se=async(e,t)=>{try{await n({text:"正在为向量搜索结果准备字段信息"},t);let a=y(t,"layersAndFieldsRegistry"),{mapView:d}=z(t),{assignedTask:o,userRequest:s}=e.agentExecutionContext,i=ae(o,s),{layerFieldInfo:r,didFetchStatistics:c,fieldStatisticsFetchStatus:l}=await te(e.vectorSearchFieldResults,a,d,i);c?await n({text:"已获取统计信息"},t):await n({text:"跳过统计"},t);for(let g of l)await n({text:` - ${g.fieldName}——统计状态:${g.didFetchStatistics?"已获取":"已跳过"}`},t);return await n({text:"字段信息准备完成"},t),{...e,layerFieldInfo:r}}catch(a){throw await n({text:"获取统计信息失败"},t),new Error(`获取统计信息失败:${a instanceof Error?a.message:String(a)}`)}},Q=.4,re=50,ie=async(e,t)=>{try{await n({text:"正在通过相似度搜索字段"},t);let a=y(t,"fieldSearch"),d=y(t,"layersAndFieldsRegistry"),o=y(t,"embeddingCache"),s=await a.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:Q,topResults:re,embeddingCache:o}),i=s.map(({layerId:c,results:l})=>{let g=l.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
3
3
  `);return`${d.get(c)?.layerItem.name??c}:
4
4
  ${g}`}).join(`
5
5
  `),r;return s.length>0?r=`向量搜索完成,匹配的图层、字段及得分:
@@ -32,7 +32,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
32
32
  ]))`;continue}else if(n[u]==="$"){o+=`($|(?=[\r
33
33
  ]))`;continue}}if(s.s&&n[u]==="."){o+=a?`${n[u]}\r
34
34
  `:`[${n[u]}\r
35
- ]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{let u=new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return o};function fn(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===C.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((s,n)=>({...s,[n]:v(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:v(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===C.ZodString&&t.keyType._def.checks?.length){let s=Object.entries(mn(t.keyType._def,e)).reduce((n,[o,i])=>o==="type"?n:{...n,[o]:i},{});return{...r,propertyNames:s}}else if(t.keyType?._def.typeName===C.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function qa(t,e){if(e.mapStrategy==="record")return fn(t,e);let r=v(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=v(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,s],minItems:2,maxItems:2}}}function Wa(t){let e=t.values,s=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),n=Array.from(new Set(s.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:s}}function Ha(){return{not:{}}}function Za(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var bs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ja(t,e){if(e.target==="openApi3")return Va(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(s=>s._def.typeName in bs&&(!s._def.checks||!s._def.checks.length))){let s=r.reduce((n,o)=>{let i=bs[o._def.typeName];return i&&!n.includes(i)?[...n,i]:n},[]);return{type:s.length>1?s:s[0]}}else if(r.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){let s=r.reduce((n,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...n,i];case"bigint":return[...n,"integer"];case"object":if(o._def.value===null)return[...n,"null"];default:return n}},[]);if(s.length===r.length){let n=s.filter((o,i,a)=>a.indexOf(o)===i);return{type:n.length>1?n:n[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(s=>s._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((s,n)=>[...s,...n._def.values.filter(o=>!s.includes(o))],[])};return Va(t,e)}var Va=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,n)=>v(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return r.length?{anyOf:r}:void 0};function Ga(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:bs[t.innerType._def.typeName],nullable:!0}:{type:[bs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let s=v(t.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}let r=v(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Xa(t,e){let r={type:"number"};if(!t.checks)return r;for(let s of t.checks)switch(s.kind){case"int":r.type="integer",Io(r,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?R(r,"minimum",s.value,s.message,e):R(r,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(r.exclusiveMinimum=!0),R(r,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?R(r,"maximum",s.value,s.message,e):R(r,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(r.exclusiveMaximum=!0),R(r,"maximum",s.value,s.message,e));break;case"multipleOf":R(r,"multipleOf",s.value,s.message,e);break}return r}function Lc(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":v(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":v(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Ya(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((s,[n,o])=>{if(o===void 0||o._def===void 0)return s;let i=[...e.currentPath,"properties",n],a=v(o._def,{...e,currentPath:i,propertyPath:i});if(a===void 0)return s;if(e.openaiStrictMode&&o.isOptional()&&!o.isNullable()&&typeof o._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...s.properties,[n]:a},required:o.isOptional()&&!e.openaiStrictMode?s.required:[...s.required,n]}},{properties:{},required:[]}),additionalProperties:Lc(t,e)};return r.required.length||delete r.required,r}var Qa=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return v(t.innerType._def,{...e,currentPath:e.currentPath});let r=v(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}};var eu=(t,e)=>{if(e.pipeStrategy==="input")return v(t.in._def,e);if(e.pipeStrategy==="output")return v(t.out._def,e);let r=v(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=v(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,s].filter(n=>n!==void 0)}};function tu(t,e){return v(t.type._def,e)}function ru(t,e){let s={type:"array",uniqueItems:!0,items:v(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&R(s,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&R(s,"maxItems",t.maxSize.value,t.maxSize.message,e),s}function su(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,s)=>v(r._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[]),additionalItems:v(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,s)=>v(r._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[])}}function nu(){return{not:{}}}function ou(){return{}}var iu=(t,e)=>v(t.innerType._def,e);function v(t,e,r=!1){let s=e.seen.get(t);if(e.override){let i=e.override?.(t,e,s,r);if(i!==Ta)return i}if(s&&!r){let i=Uc(s,e);if(i!==void 0)return"$ref"in i&&e.seenRefs.add(i.$ref),i}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);let o=Fc(t,t.typeName,e,r);return o&&Kc(t,e,o),n.jsonSchema=o,o}var Uc=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:Dc(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((s,n)=>e.currentPath[n]===s)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Dc=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},Fc=(t,e,r,s)=>{switch(e){case C.ZodString:return mn(t,r);case C.ZodNumber:return Xa(t,r);case C.ZodObject:return Ya(t,r);case C.ZodBigInt:return Na(t,r);case C.ZodBoolean:return Ma();case C.ZodDate:return bo(t,r);case C.ZodUndefined:return nu();case C.ZodNull:return Za(r);case C.ZodArray:return $a(t,r);case C.ZodUnion:case C.ZodDiscriminatedUnion:return Ja(t,r);case C.ZodIntersection:return Fa(t,r);case C.ZodTuple:return su(t,r);case C.ZodRecord:return fn(t,r);case C.ZodLiteral:return Ka(t,r);case C.ZodEnum:return Da(t);case C.ZodNativeEnum:return Wa(t);case C.ZodNullable:return Ga(t,r);case C.ZodOptional:return Qa(t,r);case C.ZodMap:return qa(t,r);case C.ZodSet:return ru(t,r);case C.ZodLazy:return v(t.getter()._def,r);case C.ZodPromise:return tu(t,r);case C.ZodNaN:case C.ZodNever:return Ha();case C.ZodEffects:return Ua(t,r,s);case C.ZodAny:return Sa();case C.ZodUnknown:return ou();case C.ZodDefault:return La(t,r);case C.ZodBranded:return za(t,r);case C.ZodReadonly:return iu(t,r);case C.ZodCatch:return ja(t,r);case C.ZodPipeline:return eu(t,r);case C.ZodFunction:case C.ZodVoid:case C.ZodSymbol:return;default:return(n=>{})(e)}},Kc=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var wo=(t,e)=>{let r=Ea(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,n=v(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??{},o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(n.title=o);let i=(()=>{if(Ra(r.definitions))return;let l={},u=new Set;for(let f=0;f<500;f++){let d=Object.entries(r.definitions).filter(([y])=>!u.has(y));if(d.length===0)break;for(let[y,_]of d)l[y]=v(Is(_),{...r,currentPath:[...r.basePath,r.definitionPath,y]},!0)??{},u.add(y)}return l})(),a=s===void 0?i?{...n,[r.definitionPath]:i}:n:r.nameStrategy==="duplicate-ref"?{...n,...i||r.seenRefs.size?{[r.definitionPath]:{...i,...r.seenRefs.size?{[s]:n}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...i,[s]:n}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function au(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);let e=structuredClone(t);return ze(e,[],e)}function Oo(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Oo(e))return!0;for(let e of t.anyOf??[])if(Oo(e))return!0;return!1}function ze(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!Et(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let s=t.$defs;if(Et(s))for(let[y,_]of Object.entries(s))ze(_,[...e,"$defs",y],r);let n=t.definitions;if(Et(n))for(let[y,_]of Object.entries(n))ze(_,[...e,"definitions",y],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let i=t.required??[],a=t.properties;if(Et(a)){for(let[y,_]of Object.entries(a))if(!Oo(_)&&!i.includes(y))throw new Error(`Zod field at \`${[...e,"properties",y].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(a),t.properties=Object.fromEntries(Object.entries(a).map(([y,_])=>[y,ze(_,[...e,"properties",y],r)]))}let l=t.items;Et(l)&&(t.items=ze(l,[...e,"items"],r));let u=t.anyOf;Array.isArray(u)&&(t.anyOf=u.map((y,_)=>ze(y,[...e,"anyOf",String(_)],r)));let f=t.allOf;if(Array.isArray(f))if(f.length===1){let y=ze(f[0],[...e,"allOf","0"],r);Object.assign(t,y),delete t.allOf}else t.allOf=f.map((y,_)=>ze(y,[...e,"allOf",String(_)],r));t.default===null&&delete t.default;let d=t.$ref;if(d&&qc(t,1)){if(typeof d!="string")throw new TypeError(`Received non-string $ref - ${d}; path=${e.join("/")}`);let y=Bc(r,d);if(typeof y=="boolean")throw new Error(`Expected \`$ref: ${d}\` to resolve to an object schema but got boolean`);if(!Et(y))throw new Error(`Expected \`$ref: ${d}\` to resolve to an object but got ${JSON.stringify(y)}`);return Object.assign(t,{...y,...t}),delete t.$ref,ze(t,e,r)}return t}function Bc(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),s=t;for(let n of r){if(!Et(s))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(s)}`);let o=s[n];if(o===void 0)throw new Error(`Key ${n} not found while resolving ${e}`);s=o}return s}function Et(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qc(t,e){let r=0;for(let s in t)if(r++,r>e)return!0;return!1}function Wc(t,e){return wo(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Hc(t){return au(Zo(t,{target:"draft-7"}))}function Zc(t){return"_zod"in t}function uu(t,e,r){return Di({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Zc(t)?Hc(t):Wc(t,{name:e})}},s=>t.parse(JSON.parse(s)))}var lu=["jsonSchema","functionCalling","jsonMode"];function cu(t,e){if(typeof e<"u"&&!lu.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${lu.join(", ")}`);let r=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(r&&!e)return"jsonSchema";if(!r&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function Vc(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function pu(t,e,r){if(Jo(t))return uu(t,e,r);if(Vo(t))return Vc({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Nt(t,{cycles:"ref",reused:"ref",override(s){s.jsonSchema.title=e}})}},s=>Ho(t,JSON.parse(s)));throw new Error("Unsupported schema response format")}function mu(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(s=>typeof s?.image_url?.url=="string").map(s=>({type:"image",url:s.image_url.url}));return[{type:"text",text:t},...r]}return t}var fu={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function Zr(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var St=class extends si{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??ie("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??ie("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.4.3")}_getReasoningParams(t){if(!Se(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),t?.reasoningEffort!==void 0&&e?.effort===void 0&&(e={...e,effort:t.reasoningEffort}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&Gr(t.json_schema.schema)?pu(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}_combineCallOptions(t){return{...this.defaultOptions,...t??{}}}_getClientOptions(t){if(!this.client){let e=Ne({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=Me(r.defaultHeaders),this.client=new P(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return Ct(t)?va(t.metadata.customTool):Rs(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:_a(t,e)}bindTools(t,e){let r;return e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:t.map(s=>{if(Hr(s)||Ct(s))return s;if(Aa(s))return s.extras.providerToolDefinition;let n=this._convertChatOpenAIToolToCompletionsTool(s,{strict:r});return Ss(s)&&s.extras?.defer_loading===!0?{...n,defer_loading:!0}:n}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,s=0;this.model==="gpt-3.5-turbo-0301"?(r=4,s=-1):(r=3,s=1);let n=await Promise.all(t.map(async o=>{let[i,a]=await Promise.all([this.getNumTokens(o.content),this.getNumTokens($e(o))]),l=o.name!==void 0?s+await this.getNumTokens(o.name):0,u=i+r+a+l,f=o;if(f._getType()==="function"&&(u-=2),f.additional_kwargs?.function_call&&(u+=3),f?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(f.additional_kwargs.function_call?.name)),f.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(f.additional_kwargs.function_call?.arguments)))}catch(d){console.error("Error parsing function arguments",d,JSON.stringify(f.additional_kwargs.function_call)),u+=await this.getNumTokens(f.additional_kwargs.function_call?.arguments)}return e+=u,u}));return e+=3,{totalCount:e,countPerMessage:n}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let s=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let n=ga(e);s+=await this.getNumTokens(n),s+=9}return e&&t.find(n=>n._getType()==="system")&&(s-=4),r==="none"?s+=1:typeof r=="object"&&(s+=await this.getNumTokens(r.name)+4),s}async moderateContent(t,e){let r=this._getClientOptions(e?.options),s={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(s,r)}catch(n){throw pe(n)}})}get profile(){return fu[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,s,{schema:n,name:o,includeRaw:i}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let a=cu(this.model,e?.method);if(a==="jsonMode"){s=Tn(n);let l=Nt(n);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:o??"extract",...l}}})}else if(a==="jsonSchema"){let l=Nt(n),u={name:o??"extract",description:Go(l),schema:Gr(n)?n:l,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:u},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:u.name,description:u.description,...l}}}),Gr(n)||kn(n)){let f=Tn(n);s=Xo.from(async d=>"parsed"in d.additional_kwargs?d.additional_kwargs.parsed:f.invoke(d.content))}else s=new Qo}else{let l=o??"extract",u=Nt(n),f;Gr(n)||kn(n)?f={name:l,description:u.description,parameters:u}:typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(f=n,l=n.name):(l=n.title??l,f={name:l,description:n.description??"",parameters:n}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:l}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:l,...u}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=ti(n,l)}return ri(r,s,i)}};var dn={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){let e=Pn({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let r=e.mime_type||t.mime_type||"",s;try{s=On(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(s.type!=="audio"||s.subtype!=="wav"&&s.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:s.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=On(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){let e=Pn({dataUrl:t.url}),r=Wr(t);if(!e)throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,filename:r}}}if(t.source_type==="base64"){let e=Wr(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},Po=({message:t,rawResponse:e,includeRawResponse:r})=>{let s=t.tool_calls,n=t.reasoning_content;switch(t.role){case"assistant":{let o=[],i=[];for(let u of s??[])try{o.push(Es(u,{returnId:!0}))}catch(f){i.push(Mt(u,f.message))}let a={function_call:t.function_call,tool_calls:s};r!==void 0&&(a.__raw_response=e),n!==void 0&&(a.reasoning_content=n);let l={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(a.audio=t.audio),new ae({content:mu(t.content||"",e.choices?.[0]?.message),tool_calls:o,invalid_tool_calls:i,additional_kwargs:a,response_metadata:l,id:e.id})}default:return new Cs(t.content||"",t.role??"unknown")}},vo=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:s})=>{let n=t.role??s,o=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},r&&(i.__raw_response=e),t.reasoning_content!==void 0&&(i.reasoning_content=t.reasoning_content),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});let a={model_provider:"openai",usage:{...e.usage}};if(n==="user")return new qo({content:o,response_metadata:a});if(n==="assistant"){let l=[];if(Array.isArray(t.tool_calls))for(let u of t.tool_calls)l.push({name:u.function?.name,args:u.function?.arguments,id:u.id,index:u.index,type:"tool_call_chunk"});return new $t({content:o,tool_call_chunks:l,additional_kwargs:i,id:e.id,response_metadata:a})}else return n==="system"?new vn({content:o,response_metadata:a}):n==="developer"?new vn({content:o,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):n==="function"?new Bo({content:o,additional_kwargs:i,name:t.name,response_metadata:a}):n==="tool"?new Do({content:o,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new Ko({content:o,role:n,response_metadata:a})},du=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){let e=Wo(()=>{let[,r]=t.mimeType.split("/");return r==="wav"||r==="mp3"?r:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){let e=Wr(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},hu=({message:t,model:e})=>{let r=$e(t);if(r==="system"&&Se(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="assistant")return{role:"assistant",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="tool"&&ks.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(n=>n.type==="text").join("")};function*s(n){for(let o of n){o.type==="text"&&(yield{type:"text",text:o.text});let i=du(o);i&&(yield i)}}return{role:"user",content:Array.from(s(t.contentBlocks))}},xs=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return hu({message:r});let s=$e(r);s==="system"&&Se(e)&&(s="developer");let n=typeof r.content=="string"?r.content:r.content.flatMap(i=>Ps(i)?vs(i,dn):typeof i=="object"&&i!==null&&"type"in i&&i.type==="tool_use"?[]:i),o={role:s,content:n};return r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call),ae.isInstance(r)&&r.tool_calls?.length?o.tool_calls=r.tool_calls.map(ei):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),ks.isInstance(r)&&r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[o,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:o});var hn=class extends St{constructor(t,e){super(Zr(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let s={};t?.stream_options!==void 0?s={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(s={stream_options:{include_usage:!0}});let n={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:r})):void 0,tool_choice:cn(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...s,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(n.prediction=t.prediction),this.service_tier!==void 0&&(n.service_tier=this.service_tier),t?.service_tier!==void 0&&(n.service_tier=t.service_tier);let o=this._getReasoningParams(t);return o!==void 0&&o.effort!==void 0&&(n.reasoning_effort=o.effort),Se(n.model)?n.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:n.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,n}async _generate(t,e,r){e.signal?.throwIfAborted();let s={},n=this.invocationParams(e),o=xs({messages:t,model:this.model});if(n.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let _ of i){_.message.response_metadata={..._.generationInfo,..._.message.response_metadata};let g=_.generationInfo?.completion??0;a[g]===void 0?a[g]=_:a[g]=a[g].concat(_)}let l=Object.entries(a).sort(([_],[g])=>parseInt(_,10)-parseInt(g,10)).map(([_,g])=>g),{functions:u,function_call:f}=this.invocationParams(e),d=await this._getEstimatedTokenCountFromPrompt(t,u,f),y=await this._getNumTokensFromGenerations(l);return s.input_tokens=d,s.output_tokens=y,s.total_tokens=d+y,{generations:l,llmOutput:{estimatedTokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}else{let i=await this.completionWithRetry({...n,stream:!1,messages:o},{signal:e?.signal,...e?.options}),{completion_tokens:a,prompt_tokens:l,total_tokens:u,prompt_tokens_details:f,completion_tokens_details:d}=i?.usage??{};a&&(s.output_tokens=(s.output_tokens??0)+a),l&&(s.input_tokens=(s.input_tokens??0)+l),u&&(s.total_tokens=(s.total_tokens??0)+u),(f?.audio_tokens!==null||f?.cached_tokens!==null)&&(s.input_token_details={...f?.audio_tokens!==null&&{audio:f?.audio_tokens},...f?.cached_tokens!==null&&{cache_read:f?.cached_tokens}}),(d?.audio_tokens!==null||d?.reasoning_tokens!==null)&&(s.output_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.reasoning_tokens!==null&&{reasoning:d?.reasoning_tokens}});let y=[];for(let _ of i?.choices??[]){let g={text:_.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(_.message??{role:"assistant"},i)};g.generationInfo={..._.finish_reason?{finish_reason:_.finish_reason}:{},..._.logprobs?{logprobs:_.logprobs}:{}},Ts(g.message)&&(g.message.usage_metadata=s),g.message=new ae(Object.fromEntries(Object.entries(g.message).filter(([x])=>!x.startsWith("lc_")))),y.push(g)}return{generations:y,llmOutput:{tokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}}async*_streamResponseChunks(t,e,r){let s=xs({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:s,stream:!0},o,i=await this.completionWithRetry(n,e),a;for await(let l of i){if(e.signal?.aborted)return;let u=l?.choices?.[0];if(l.usage&&(a=l.usage),!u)continue;let{delta:f}=u;if(!f)continue;let d=this._convertCompletionsDeltaToBaseMessageChunk(f,l,o);o=f.role??o;let y={prompt:e.promptIndex??0,completion:u.index??0};if(typeof d.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let _={...y};u.finish_reason!=null&&(_.finish_reason=u.finish_reason,_.system_fingerprint=l.system_fingerprint,_.model_name=l.model,_.service_tier=l.service_tier),this.logprobs&&(_.logprobs=u.logprobs);let g=new Jr({message:d,text:d.content,generationInfo:_});yield g,await r?.handleLLMNewToken(g.text??"",y,void 0,void 0,void 0,{chunk:g})}if(a){let l={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},u={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}},f=new Jr({message:new $t({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(l).length>0&&{input_token_details:l},...Object.keys(u).length>0&&{output_token_details:u}}}),text:""});yield f,await r?.handleLLMNewToken(f.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:f})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=this._getClientOptions(e),s=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return s&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(n){throw pe(n)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return vo({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Po({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var _n="__openai_function_call_ids__";function xu(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function Gc(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){let e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}var ko=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},r={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:r}},gn=t=>{if(t.error){let l=new Error(t.error.message);throw l.name=t.error.code,l}let e,r=[],s=[],n=[],o=t.output.map(l=>{if(l.type==="function_call"&&"parsed_arguments"in l){let u={...l};return delete u.parsed_arguments,u}return l}),i={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:o,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},a={};for(let l of t.output)if(l.type==="message")e=l.id,r.push(...l.content.flatMap(u=>u.type==="output_text"?("parsed"in u&&u.parsed!=null&&(a.parsed=u.parsed),{type:"text",text:u.text,annotations:u.annotations.map(xu),...l.phase!==null?{phase:l.phase}:{}}):u.type==="refusal"?(a.refusal=u.refusal,[]):u));else if(l.type==="function_call"){let u={function:{name:l.name,arguments:l.arguments},id:l.call_id};try{s.push(Es(u,{returnId:!0}))}catch(f){let d;typeof f=="object"&&f!=null&&"message"in f&&typeof f.message=="string"&&(d=f.message),n.push(Mt(u,d))}a[_n]??={},l.id&&(a[_n][l.call_id]=l.id)}else if(l.type==="reasoning"){a.reasoning=l;let u=l.summary?.map(f=>f.text).filter(Boolean).join("");u&&r.push({type:"reasoning",reasoning:u})}else if(l.type==="custom_tool_call"){let u=ba(l);u?s.push(u):n.push(Mt(l,"Malformed custom tool call"))}else if(l.type==="computer_call"){let u=xa(l);u?s.push(u):n.push(Mt(l,"Malformed computer call"))}else l.type==="image_generation_call"?(l.result&&r.push({type:"image",mimeType:"image/png",data:l.result,id:l.id,metadata:{status:l.status}}),a.tool_outputs??=[],a.tool_outputs.push(l)):(a.tool_outputs??=[],a.tool_outputs.push(l));return new ae({id:e,content:r,tool_calls:s,invalid_tool_calls:n,usage_metadata:ko(t.usage),additional_kwargs:a,response_metadata:i})},wu=t=>{let e=(t.summary.length>1?t.summary.reduce((r,s)=>{let n=r[r.length-1];return n.index===s.index?n.text+=s.text:r.push(s),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([s])=>s!=="index")));return{...t,summary:e}},To=t=>{let e=[],r={},s,n=[],o={model_provider:"openai"},i={},a;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[xu(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){a=t.item.id;let l="phase"in t.item?t.item.phase:void 0;l&&e.push({type:"text",text:"",phase:l,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")n.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[_n]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")n.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")o.id=t.response.id,o.model_name=t.response.model,o.model=t.response.model;else if(t.type==="response.completed"){let l=gn(t.response);s=ko(t.response.usage),t.response.text?.format?.type==="json_schema"&&l.text&&(i.parsed??=JSON.parse(l.text));for(let[u,f]of Object.entries(t.response))u!=="id"&&(u==="output"?o[u]=l.response_metadata.output:o[u]=f)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")n.push({type:"tool_call_chunk",args:t.delta,index:t.output_index});else if(t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.completed")r={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let l=t.item.summary?t.item.summary.map((f,d)=>({...f,index:d})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...l?{summary:l}:{}};let u=t.item.summary?.map(f=>f.text).filter(Boolean).join("");u&&e.push({type:"reasoning",reasoning:u})}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text});else if(t.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta});else return t.type==="response.image_generation_call.partial_image",null;return new Jr({text:e.map(l=>l.text).join(""),message:new $t({id:a,content:e,tool_call_chunks:n,usage_metadata:s,additional_kwargs:i,response_metadata:o}),generationInfo:r})},Ou=t=>{let e=ae.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let s=me(()=>{try{let h=$e(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"assistant"}catch{return"assistant"}}),n,o=new Set,i=new Set,a=new Map,l=new Map;function*u(){if(!n)return;let h=n.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield n),n=void 0}let f=(h,A)=>{n||(n={type:"message",role:s,content:[],...A?{phase:A}:{}}),typeof n.content=="string"?n.content=n.content.length>0?[{type:"input_text",text:n.content},...h]:[...h]:n.content.push(...h)},d=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},y=h=>{let A=me(()=>{let T=h.metadata?.detail;return T==="low"||T==="high"||T==="auto"?T:"auto"});if(h.fileId)return{type:"input_image",detail:A,file_id:h.fileId};if(h.url)return{type:"input_image",detail:A,image_url:h.url};if(h.data){let T=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_image",detail:A,image_url:`data:${h.mimeType??"image/png"};base64,${T}`}}},_=h=>{if(h.fileId){let A=yo(h);return{type:"input_file",file_id:h.fileId,...A?{filename:A}:{}}}if(h.url){let A=yo(h);return{...A?{filename:A}:{},type:"input_file",file_url:h.url}}if(h.data){let A=Wr(h),T=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_file",file_data:`data:${h.mimeType??"application/octet-stream"};base64,${T}`,filename:A}}},g=h=>{let A=me(()=>{if(Array.isArray(h.summary)){let q=h.summary?.map(j=>j?.text).filter(j=>typeof j=="string")??[];if(q.length>0)return q}return h.reasoning?[h.reasoning]:[]}),T=A.length>0?A.map(q=>({type:"summary_text",text:q})):[{type:"summary_text",text:""}],S={type:"reasoning",id:h.id??"",summary:T};return h.reasoning&&(S.content=[{type:"reasoning_text",text:h.reasoning}]),S},x=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:d(h.args)}),$=h=>{let A=d(h.output),T=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:A,...T?{status:T}:{}}};for(let h of t.contentBlocks)if(h.type==="text"){let A=me(()=>{if("extras"in h&&typeof h.extras=="object"&&h.extras!==null&&"phase"in h.extras)return h.extras.phase});f([{type:"input_text",text:h.text}],A)}else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*u(),yield g(h);else if(h.type==="tool_call"){yield*u();let A=h.id??"";A&&(o.add(A),a.delete(A)),yield x(h)}else if(h.type==="tool_call_chunk"){if(h.id){let A=a.get(h.id)??{name:h.name,args:[]};h.name&&(A.name=h.name),h.args&&A.args.push(h.args),a.set(h.id,A)}}else if(h.type==="server_tool_call"){yield*u();let A=h.id??"";A&&(i.add(A),l.delete(A)),yield x(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){let A=l.get(h.id)??{name:h.name,args:[]};h.name&&(A.name=h.name),h.args&&A.args.push(h.args),l.set(h.id,A)}}else if(h.type==="server_tool_call_result")yield*u(),yield $(h);else if(h.type!=="audio")if(h.type==="file"){let A=_(h);A&&f([A])}else if(h.type==="image"){let A=y(h);A&&f([A])}else if(h.type==="video"){let A=_(h);A&&f([A])}else h.type==="text-plain"?h.text&&f([{type:"input_text",text:h.text}]):h.type==="non_standard"&&e&&(yield*u(),yield h.value)}yield*u();for(let[h,A]of a){if(!h||o.has(h))continue;let T=A.args.join("");!A.name&&!T||(yield{type:"function_call",call_id:h,name:A.name??"",arguments:T})}for(let[h,A]of l){if(!h||i.has(h))continue;let T=A.args.join("");!A.name&&!T||(yield{type:"function_call",call_id:h,name:A.name??"",arguments:T})}}return Array.from(r())},yn=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(s=>{let n=s.response_metadata;if(n?.output_version==="v1")return Ou(s);let o=s.additional_kwargs,i=$e(s);if(i==="system"&&Se(r)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){let a=s;if(o?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let u=a.content.find(y=>y.type==="input_image");if(u)return u;let f=a.content.find(y=>y.type==="computer_screenshot");if(f)return f;let d=a.content.find(y=>y.type==="image_url");if(d)return{type:"input_image",image_url:typeof d.image_url=="string"?d.image_url:d.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let l=Array.isArray(a.content)&&a.content.every(u=>typeof u=="object"&&u!==null&&"type"in u&&(u.type==="input_file"||u.type==="input_image"||u.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:l?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(i==="assistant"){if(!e&&n?.output!=null&&Array.isArray(n?.output)&&n?.output.length>0&&n?.output.every(g=>"type"in g))return n?.output;let a=[],l=o?.reasoning,u=!!l?.encrypted_content;if(l&&(!e||u)){let g=wu(l);a.push(g)}let{content:f}=s;if(o?.refusal&&(typeof f=="string"&&(f=[{type:"output_text",text:f,annotations:[]}]),f=[...f,{type:"refusal",refusal:o.refusal}]),typeof f=="string"||f.length>0){let g={type:"message",role:"assistant",...s.id&&!e&&s.id.startsWith("msg_")?{id:s.id}:{},content:me(()=>typeof f=="string"?f:f.flatMap(x=>{if(x.type==="text"){let $=x;return{type:"output_text",text:$.text,annotations:($.annotations??[]).map(Gc)}}return x.type==="output_text"||x.type==="refusal"?x:[]})),phase:me(()=>{if(Array.isArray(f))return f.find(x=>"phase"in x&&typeof x.phase=="string")?.phase})};a.push(g)}let d=o?.[_n];ae.isInstance(s)&&s.tool_calls?.length?a.push(...s.tool_calls.map(g=>Oa(g)?{type:"custom_tool_call",id:g.call_id,call_id:g.id??"",input:g.args.input,name:g.name}:wa(g)?{type:"computer_call",id:g.call_id,call_id:g.id??"",action:g.args.action}:{type:"function_call",name:g.name,arguments:JSON.stringify(g.args),call_id:g.id,...e?{}:{id:d?.[g.id]}})):o?.tool_calls&&a.push(...o.tool_calls.map(g=>({type:"function_call",name:g.function.name,call_id:g.id,arguments:g.function.arguments,...e?{}:{id:d?.[g.id]}})));let y=n?.output?.length?n?.output:o.tool_outputs,_=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(y!=null){let g=y?.filter(x=>_.includes(x.type));g.length>0&&a.push(...g)}return a}if(i==="user"||i==="system"||i==="developer"){if(typeof s.content=="string")return{type:"message",role:i,content:s.content};let a=[],l=s.content.flatMap(u=>(u.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:u.approval_request_id,approve:u.approve}),Ps(u)?vs(u,dn):u.type==="text"?{type:"input_text",text:u.text}:u.type==="image_url"?{type:"input_image",image_url:me(()=>{if(typeof u.image_url=="string")return u.image_url;if(typeof u.image_url=="object"&&u.image_url!==null&&"url"in u.image_url)return u.image_url.url}),detail:me(()=>{if(typeof u.image_url=="string")return"auto";if(typeof u.image_url=="object"&&u.image_url!==null&&"detail"in u.image_url)return u.image_url.detail})}:u.type==="input_text"||u.type==="input_image"||u.type==="input_file"?u:[]));return l.length>0&&a.push({type:"message",role:i,content:l}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});var An=class extends St{constructor(t,e){super(Zr(t,e))}invocationParams(t){let e;t?.strict!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);let r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:t?.previous_response_id,truncation:t?.truncation,include:t?.include,tools:t?.tools?.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:Ia(t?.tool_choice)?t?.tool_choice:(()=>{let n=cn(t?.tool_choice);if(typeof n=="object"&&"type"in n){if(n.type==="function")return{type:"function",name:n.function.name};if(n.type==="allowed_tools")return{type:"allowed_tools",mode:n.allowed_tools.mode,tools:n.allowed_tools.tools};if(n.type==="custom")return{type:"custom",name:n.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let n=this._getResponseFormat(t?.response_format);return n?.type==="json_schema"?n.json_schema.schema!=null?{format:{type:"json_schema",schema:n.json_schema.schema,description:n.json_schema.description,name:n.json_schema.name,strict:n.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:n,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this._getReasoningParams(t);return s!==void 0&&(r.reasoning=s),r}async _generate(t,e,r){e.signal?.throwIfAborted();let s=this.invocationParams(e);if(s.stream){let n=this._streamResponseChunks(t,e,r),o;for await(let i of n)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},o=o?.concat(i)??i;return{generations:o?[o]:[],llmOutput:{estimatedTokenUsage:o?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:yn({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...s,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:n.output_text,message:gn(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(t,e,r){let s=await this.completionWithRetry({...this.invocationParams(e),input:yn({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(let n of s){if(e.signal?.aborted)return;let o=To(n);o!=null&&(yield o,await r?.handleLLMNewToken(o.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:o}))}}async completionWithRetry(t,e){return this.caller.call(async()=>{let r=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,r):await this.client.responses.create(t,r)}catch(s){throw pe(s)}})}_reduceChatOpenAITools(t,e){let r=[];for(let s of t)if(Hr(s))s.type==="image_generation"&&e?.stream&&(s.partial_images=1),r.push(s);else if(Ct(s)){let n=s.metadata.customTool;r.push({type:"custom",name:n.name,description:n.description,format:n.format})}else if(Rs(s)){let n={};for(let[o,i]of Object.entries(s))o!=="type"&&o!=="function"&&(n[o]=i);r.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:e?.strict??null,...n})}else pn(s)&&r.push(Pa(s));return r}};var In=class Pu extends St{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let s=Zr(e,r);super(s),this.fields=s,this.useResponsesApi=s?.useResponsesApi??!1,this.responses=s?.responses??new An(s),this.completions=s?.completions??new hn(s)}_useResponsesApi(e){let r=e?.tools?.some(Hr),s=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,n=e?.tools?.some(pn)||e?.tools?.some(Ct);return this.useResponsesApi||r||s||n||fa(this.model)}getLsParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(e,r,s){return this._useResponsesApi(r)?this.responses._generate(e,r,s):this.completions._generate(e,r,s)}async*_streamResponseChunks(e,r,s){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),s);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),s)}withConfig(e){let r=new Pu(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var bn=class extends Yo{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(t){let e={maxConcurrency:2,...t};super(e);let r=e?.apiKey??e?.openAIApiKey??ie("OPENAI_API_KEY");this.organization=e?.configuration?.organization??ie("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.batchSize=e?.batchSize??this.batchSize,this.stripNewLines=e?.stripNewLines??this.stripNewLines,this.timeout=e?.timeout,this.dimensions=e?.dimensions,this.encodingFormat=e?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration}}async embedDocuments(t){let e=Rn(this.stripNewLines?t.map(o=>o.replace(/\n/g," ")):t,this.batchSize),r=e.map(o=>{let i={model:this.model,input:o};return this.dimensions&&(i.dimensions=this.dimensions),this.encodingFormat&&(i.encoding_format=this.encodingFormat),this.embeddingWithRetry(i)}),s=await Promise.all(r),n=[];for(let o=0;o<s.length;o+=1){let i=e[o],{data:a}=s[o];for(let l=0;l<i.length;l+=1)n.push(a[l].embedding)}return n}async embedQuery(t){let e={model:this.model,input:this.stripNewLines?t.replace(/\n/g," "):t};this.dimensions&&(e.dimensions=this.dimensions),this.encodingFormat&&(e.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(e);return r[0].embedding}async embeddingWithRetry(t){if(!this.client){let r=Ne({baseURL:this.clientConfig.baseURL}),s={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};s.baseURL||delete s.baseURL,s.defaultHeaders=Me(s.defaultHeaders),this.client=new P(s)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw pe(r)}})}};var ep=I.object({type:I.literal("screenshot")}),tp=I.object({type:I.literal("click"),x:I.number(),y:I.number(),button:I.enum(["left","right","wheel","back","forward"]).default("left")}),rp=I.object({type:I.literal("double_click"),x:I.number(),y:I.number(),button:I.enum(["left","right","wheel","back","forward"]).default("left")}),sp=I.object({type:I.literal("drag"),path:I.array(I.object({x:I.number(),y:I.number()}))}),np=I.object({type:I.literal("keypress"),keys:I.array(I.string())}),op=I.object({type:I.literal("move"),x:I.number(),y:I.number()}),ip=I.object({type:I.literal("scroll"),x:I.number(),y:I.number(),scroll_x:I.number(),scroll_y:I.number()}),ap=I.object({type:I.literal("type"),text:I.string()}),up=I.object({type:I.literal("wait"),duration:I.number().optional()}),lp=I.union([ep,tp,rp,sp,np,op,ip,ap,up]),jv=I.object({action:lp});var cp=I.object({type:I.literal("exec"),command:I.array(I.string()),env:I.record(I.string(),I.string()).optional(),working_directory:I.string().optional(),timeout_ms:I.number().optional(),user:I.string().optional()}),Fv=I.union([cp]);var Wv=I.object({commands:I.array(I.string()).describe("Array of shell commands to execute"),timeout_ms:I.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:I.number().optional().describe("Optional maximum number of characters to return from each command")});var pp=I.object({type:I.literal("create_file"),path:I.string(),diff:I.string()}),mp=I.object({type:I.literal("update_file"),path:I.string(),diff:I.string()}),fp=I.object({type:I.literal("delete_file"),path:I.string()}),Jv=I.union([pp,mp,fp]);var Ro=new Map,xn=null,cdnPortalUrl=()=>{let e=[Tu.getDefault()?.url,hp.portalUrl].find(t=>typeof t==="string"&&t.trim());if(!e)throw new Error("未配置 Portal URL,请设置 Portal.getDefault().url 或 geosceneConfig.portalUrl。");return e.trim().replace(/\/+$/,"")},_p=()=>cdnPortalUrl()+"/ai-assistant/portal",Ru=async t=>{let e=_p();Ro.size===0&&(xn||(xn=(async()=>{try{let s=await fetch(e+"/models?f=json");if(!s.ok)throw new Error("获取 AI 模型发现服务数据失败。");let n=(await s.json()).models;if(!Array.isArray(n))throw new Error("AI 模型发现服务响应缺少 models 数组。");n.forEach(o=>Ro.set(o.name,o))}catch(s){throw xn=null,s}})()),await xn);let r=[...Ro.values()].filter(s=>s.model_type===t&&s.is_active===true);if(r.length!==1)throw new Error("应有且仅有一个已激活的 "+t+" 模型,实际数量为 "+r.length+".");let n=r[0];if(!n.name||!n.endpoint)throw new Error("已激活的 "+t+" 模型缺少 name 或 endpoint。");return{...n,endpoint:new URL(n.endpoint,new URL(e).origin).href}},yp=async()=>(await Ru("embedding")).endpoint,Vr=(t,e)=>e,Eu=(t,e)=>({...t,...e}),Su=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let s=t.trim();if(!s)return r;if(s===r)return t;let n=s.split(`
35
+ ]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{let u=new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return o};function fn(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===C.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((s,n)=>({...s,[n]:v(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:v(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===C.ZodString&&t.keyType._def.checks?.length){let s=Object.entries(mn(t.keyType._def,e)).reduce((n,[o,i])=>o==="type"?n:{...n,[o]:i},{});return{...r,propertyNames:s}}else if(t.keyType?._def.typeName===C.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function qa(t,e){if(e.mapStrategy==="record")return fn(t,e);let r=v(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=v(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,s],minItems:2,maxItems:2}}}function Wa(t){let e=t.values,s=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),n=Array.from(new Set(s.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:s}}function Ha(){return{not:{}}}function Za(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var bs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ja(t,e){if(e.target==="openApi3")return Va(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(s=>s._def.typeName in bs&&(!s._def.checks||!s._def.checks.length))){let s=r.reduce((n,o)=>{let i=bs[o._def.typeName];return i&&!n.includes(i)?[...n,i]:n},[]);return{type:s.length>1?s:s[0]}}else if(r.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){let s=r.reduce((n,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...n,i];case"bigint":return[...n,"integer"];case"object":if(o._def.value===null)return[...n,"null"];default:return n}},[]);if(s.length===r.length){let n=s.filter((o,i,a)=>a.indexOf(o)===i);return{type:n.length>1?n:n[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(s=>s._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((s,n)=>[...s,...n._def.values.filter(o=>!s.includes(o))],[])};return Va(t,e)}var Va=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,n)=>v(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return r.length?{anyOf:r}:void 0};function Ga(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:bs[t.innerType._def.typeName],nullable:!0}:{type:[bs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let s=v(t.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}let r=v(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Xa(t,e){let r={type:"number"};if(!t.checks)return r;for(let s of t.checks)switch(s.kind){case"int":r.type="integer",Io(r,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?R(r,"minimum",s.value,s.message,e):R(r,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(r.exclusiveMinimum=!0),R(r,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?R(r,"maximum",s.value,s.message,e):R(r,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(r.exclusiveMaximum=!0),R(r,"maximum",s.value,s.message,e));break;case"multipleOf":R(r,"multipleOf",s.value,s.message,e);break}return r}function Lc(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":v(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":v(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Ya(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((s,[n,o])=>{if(o===void 0||o._def===void 0)return s;let i=[...e.currentPath,"properties",n],a=v(o._def,{...e,currentPath:i,propertyPath:i});if(a===void 0)return s;if(e.openaiStrictMode&&o.isOptional()&&!o.isNullable()&&typeof o._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...s.properties,[n]:a},required:o.isOptional()&&!e.openaiStrictMode?s.required:[...s.required,n]}},{properties:{},required:[]}),additionalProperties:Lc(t,e)};return r.required.length||delete r.required,r}var Qa=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return v(t.innerType._def,{...e,currentPath:e.currentPath});let r=v(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}};var eu=(t,e)=>{if(e.pipeStrategy==="input")return v(t.in._def,e);if(e.pipeStrategy==="output")return v(t.out._def,e);let r=v(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=v(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,s].filter(n=>n!==void 0)}};function tu(t,e){return v(t.type._def,e)}function ru(t,e){let s={type:"array",uniqueItems:!0,items:v(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&R(s,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&R(s,"maxItems",t.maxSize.value,t.maxSize.message,e),s}function su(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,s)=>v(r._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[]),additionalItems:v(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,s)=>v(r._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[])}}function nu(){return{not:{}}}function ou(){return{}}var iu=(t,e)=>v(t.innerType._def,e);function v(t,e,r=!1){let s=e.seen.get(t);if(e.override){let i=e.override?.(t,e,s,r);if(i!==Ta)return i}if(s&&!r){let i=Uc(s,e);if(i!==void 0)return"$ref"in i&&e.seenRefs.add(i.$ref),i}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);let o=Fc(t,t.typeName,e,r);return o&&Kc(t,e,o),n.jsonSchema=o,o}var Uc=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:Dc(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((s,n)=>e.currentPath[n]===s)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Dc=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},Fc=(t,e,r,s)=>{switch(e){case C.ZodString:return mn(t,r);case C.ZodNumber:return Xa(t,r);case C.ZodObject:return Ya(t,r);case C.ZodBigInt:return Na(t,r);case C.ZodBoolean:return Ma();case C.ZodDate:return bo(t,r);case C.ZodUndefined:return nu();case C.ZodNull:return Za(r);case C.ZodArray:return $a(t,r);case C.ZodUnion:case C.ZodDiscriminatedUnion:return Ja(t,r);case C.ZodIntersection:return Fa(t,r);case C.ZodTuple:return su(t,r);case C.ZodRecord:return fn(t,r);case C.ZodLiteral:return Ka(t,r);case C.ZodEnum:return Da(t);case C.ZodNativeEnum:return Wa(t);case C.ZodNullable:return Ga(t,r);case C.ZodOptional:return Qa(t,r);case C.ZodMap:return qa(t,r);case C.ZodSet:return ru(t,r);case C.ZodLazy:return v(t.getter()._def,r);case C.ZodPromise:return tu(t,r);case C.ZodNaN:case C.ZodNever:return Ha();case C.ZodEffects:return Ua(t,r,s);case C.ZodAny:return Sa();case C.ZodUnknown:return ou();case C.ZodDefault:return La(t,r);case C.ZodBranded:return za(t,r);case C.ZodReadonly:return iu(t,r);case C.ZodCatch:return ja(t,r);case C.ZodPipeline:return eu(t,r);case C.ZodFunction:case C.ZodVoid:case C.ZodSymbol:return;default:return(n=>{})(e)}},Kc=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var wo=(t,e)=>{let r=Ea(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,n=v(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??{},o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(n.title=o);let i=(()=>{if(Ra(r.definitions))return;let l={},u=new Set;for(let f=0;f<500;f++){let d=Object.entries(r.definitions).filter(([y])=>!u.has(y));if(d.length===0)break;for(let[y,_]of d)l[y]=v(Is(_),{...r,currentPath:[...r.basePath,r.definitionPath,y]},!0)??{},u.add(y)}return l})(),a=s===void 0?i?{...n,[r.definitionPath]:i}:n:r.nameStrategy==="duplicate-ref"?{...n,...i||r.seenRefs.size?{[r.definitionPath]:{...i,...r.seenRefs.size?{[s]:n}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...i,[s]:n}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function au(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);let e=structuredClone(t);return ze(e,[],e)}function Oo(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Oo(e))return!0;for(let e of t.anyOf??[])if(Oo(e))return!0;return!1}function ze(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!Et(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let s=t.$defs;if(Et(s))for(let[y,_]of Object.entries(s))ze(_,[...e,"$defs",y],r);let n=t.definitions;if(Et(n))for(let[y,_]of Object.entries(n))ze(_,[...e,"definitions",y],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let i=t.required??[],a=t.properties;if(Et(a)){for(let[y,_]of Object.entries(a))if(!Oo(_)&&!i.includes(y))throw new Error(`Zod field at \`${[...e,"properties",y].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(a),t.properties=Object.fromEntries(Object.entries(a).map(([y,_])=>[y,ze(_,[...e,"properties",y],r)]))}let l=t.items;Et(l)&&(t.items=ze(l,[...e,"items"],r));let u=t.anyOf;Array.isArray(u)&&(t.anyOf=u.map((y,_)=>ze(y,[...e,"anyOf",String(_)],r)));let f=t.allOf;if(Array.isArray(f))if(f.length===1){let y=ze(f[0],[...e,"allOf","0"],r);Object.assign(t,y),delete t.allOf}else t.allOf=f.map((y,_)=>ze(y,[...e,"allOf",String(_)],r));t.default===null&&delete t.default;let d=t.$ref;if(d&&qc(t,1)){if(typeof d!="string")throw new TypeError(`Received non-string $ref - ${d}; path=${e.join("/")}`);let y=Bc(r,d);if(typeof y=="boolean")throw new Error(`Expected \`$ref: ${d}\` to resolve to an object schema but got boolean`);if(!Et(y))throw new Error(`Expected \`$ref: ${d}\` to resolve to an object but got ${JSON.stringify(y)}`);return Object.assign(t,{...y,...t}),delete t.$ref,ze(t,e,r)}return t}function Bc(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),s=t;for(let n of r){if(!Et(s))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(s)}`);let o=s[n];if(o===void 0)throw new Error(`Key ${n} not found while resolving ${e}`);s=o}return s}function Et(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qc(t,e){let r=0;for(let s in t)if(r++,r>e)return!0;return!1}function Wc(t,e){return wo(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Hc(t){return au(Zo(t,{target:"draft-7"}))}function Zc(t){return"_zod"in t}function uu(t,e,r){return Di({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Zc(t)?Hc(t):Wc(t,{name:e})}},s=>t.parse(JSON.parse(s)))}var lu=["jsonSchema","functionCalling","jsonMode"];function cu(t,e){if(typeof e<"u"&&!lu.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${lu.join(", ")}`);let r=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(r&&!e)return"jsonSchema";if(!r&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function Vc(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function pu(t,e,r){if(Jo(t))return uu(t,e,r);if(Vo(t))return Vc({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Nt(t,{cycles:"ref",reused:"ref",override(s){s.jsonSchema.title=e}})}},s=>Ho(t,JSON.parse(s)));throw new Error("Unsupported schema response format")}function mu(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(s=>typeof s?.image_url?.url=="string").map(s=>({type:"image",url:s.image_url.url}));return[{type:"text",text:t},...r]}return t}var fu={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function Zr(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var St=class extends si{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??ie("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??ie("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.4.3")}_getReasoningParams(t){if(!Se(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),t?.reasoningEffort!==void 0&&e?.effort===void 0&&(e={...e,effort:t.reasoningEffort}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&Gr(t.json_schema.schema)?pu(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}_combineCallOptions(t){return{...this.defaultOptions,...t??{}}}_getClientOptions(t){if(!this.client){let e=Ne({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=Me(r.defaultHeaders),this.client=new P(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return Ct(t)?va(t.metadata.customTool):Rs(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:_a(t,e)}bindTools(t,e){let r;return e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:t.map(s=>{if(Hr(s)||Ct(s))return s;if(Aa(s))return s.extras.providerToolDefinition;let n=this._convertChatOpenAIToolToCompletionsTool(s,{strict:r});return Ss(s)&&s.extras?.defer_loading===!0?{...n,defer_loading:!0}:n}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,s=0;this.model==="gpt-3.5-turbo-0301"?(r=4,s=-1):(r=3,s=1);let n=await Promise.all(t.map(async o=>{let[i,a]=await Promise.all([this.getNumTokens(o.content),this.getNumTokens($e(o))]),l=o.name!==void 0?s+await this.getNumTokens(o.name):0,u=i+r+a+l,f=o;if(f._getType()==="function"&&(u-=2),f.additional_kwargs?.function_call&&(u+=3),f?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(f.additional_kwargs.function_call?.name)),f.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(f.additional_kwargs.function_call?.arguments)))}catch(d){console.error("Error parsing function arguments",d,JSON.stringify(f.additional_kwargs.function_call)),u+=await this.getNumTokens(f.additional_kwargs.function_call?.arguments)}return e+=u,u}));return e+=3,{totalCount:e,countPerMessage:n}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let s=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let n=ga(e);s+=await this.getNumTokens(n),s+=9}return e&&t.find(n=>n._getType()==="system")&&(s-=4),r==="none"?s+=1:typeof r=="object"&&(s+=await this.getNumTokens(r.name)+4),s}async moderateContent(t,e){let r=this._getClientOptions(e?.options),s={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(s,r)}catch(n){throw pe(n)}})}get profile(){return fu[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,s,{schema:n,name:o,includeRaw:i}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let a=cu(this.model,e?.method);if(a==="jsonMode"){s=Tn(n);let l=Nt(n);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:o??"extract",...l}}})}else if(a==="jsonSchema"){let l=Nt(n),u={name:o??"extract",description:Go(l),schema:Gr(n)?n:l,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:u},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:u.name,description:u.description,...l}}}),Gr(n)||kn(n)){let f=Tn(n);s=Xo.from(async d=>"parsed"in d.additional_kwargs?d.additional_kwargs.parsed:f.invoke(d.content))}else s=new Qo}else{let l=o??"extract",u=Nt(n),f;Gr(n)||kn(n)?f={name:l,description:u.description,parameters:u}:typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(f=n,l=n.name):(l=n.title??l,f={name:l,description:n.description??"",parameters:n}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:l}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:l,...u}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=ti(n,l)}return ri(r,s,i)}};var dn={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){let e=Pn({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let r=e.mime_type||t.mime_type||"",s;try{s=On(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(s.type!=="audio"||s.subtype!=="wav"&&s.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:s.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=On(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){let e=Pn({dataUrl:t.url}),r=Wr(t);if(!e)throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,filename:r}}}if(t.source_type==="base64"){let e=Wr(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},Po=({message:t,rawResponse:e,includeRawResponse:r})=>{let s=t.tool_calls,n=t.reasoning_content;switch(t.role){case"assistant":{let o=[],i=[];for(let u of s??[])try{o.push(Es(u,{returnId:!0}))}catch(f){i.push(Mt(u,f.message))}let a={function_call:t.function_call,tool_calls:s};r!==void 0&&(a.__raw_response=e),n!==void 0&&(a.reasoning_content=n);let l={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(a.audio=t.audio),new ae({content:mu(t.content||"",e.choices?.[0]?.message),tool_calls:o,invalid_tool_calls:i,additional_kwargs:a,response_metadata:l,id:e.id})}default:return new Cs(t.content||"",t.role??"unknown")}},vo=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:s})=>{let n=t.role??s,o=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},r&&(i.__raw_response=e),t.reasoning_content!==void 0&&(i.reasoning_content=t.reasoning_content),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});let a={model_provider:"openai",usage:{...e.usage}};if(n==="user")return new qo({content:o,response_metadata:a});if(n==="assistant"){let l=[];if(Array.isArray(t.tool_calls))for(let u of t.tool_calls)l.push({name:u.function?.name,args:u.function?.arguments,id:u.id,index:u.index,type:"tool_call_chunk"});return new $t({content:o,tool_call_chunks:l,additional_kwargs:i,id:e.id,response_metadata:a})}else return n==="system"?new vn({content:o,response_metadata:a}):n==="developer"?new vn({content:o,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):n==="function"?new Bo({content:o,additional_kwargs:i,name:t.name,response_metadata:a}):n==="tool"?new Do({content:o,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new Ko({content:o,role:n,response_metadata:a})},du=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){let e=Wo(()=>{let[,r]=t.mimeType.split("/");return r==="wav"||r==="mp3"?r:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){let e=Wr(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},hu=({message:t,model:e})=>{let r=$e(t);if(r==="system"&&Se(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="assistant")return{role:"assistant",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="tool"&&ks.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(n=>n.type==="text").join("")};function*s(n){for(let o of n){o.type==="text"&&(yield{type:"text",text:o.text});let i=du(o);i&&(yield i)}}return{role:"user",content:Array.from(s(t.contentBlocks))}},xs=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return hu({message:r});let s=$e(r);s==="system"&&Se(e)&&(s="developer");let n=typeof r.content=="string"?r.content:r.content.flatMap(i=>Ps(i)?vs(i,dn):typeof i=="object"&&i!==null&&"type"in i&&i.type==="tool_use"?[]:i),o={role:s,content:n};return r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call),ae.isInstance(r)&&r.tool_calls?.length?o.tool_calls=r.tool_calls.map(ei):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),ks.isInstance(r)&&r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[o,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:o});var hn=class extends St{constructor(t,e){super(Zr(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let s={};t?.stream_options!==void 0?s={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(s={stream_options:{include_usage:!0}});let n={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:r})):void 0,tool_choice:cn(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...s,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(n.prediction=t.prediction),this.service_tier!==void 0&&(n.service_tier=this.service_tier),t?.service_tier!==void 0&&(n.service_tier=t.service_tier);let o=this._getReasoningParams(t);return o!==void 0&&o.effort!==void 0&&(n.reasoning_effort=o.effort),Se(n.model)?n.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:n.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,n}async _generate(t,e,r){e.signal?.throwIfAborted();let s={},n=this.invocationParams(e),o=xs({messages:t,model:this.model});if(n.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let _ of i){_.message.response_metadata={..._.generationInfo,..._.message.response_metadata};let g=_.generationInfo?.completion??0;a[g]===void 0?a[g]=_:a[g]=a[g].concat(_)}let l=Object.entries(a).sort(([_],[g])=>parseInt(_,10)-parseInt(g,10)).map(([_,g])=>g),{functions:u,function_call:f}=this.invocationParams(e),d=await this._getEstimatedTokenCountFromPrompt(t,u,f),y=await this._getNumTokensFromGenerations(l);return s.input_tokens=d,s.output_tokens=y,s.total_tokens=d+y,{generations:l,llmOutput:{estimatedTokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}else{let i=await this.completionWithRetry({...n,stream:!1,messages:o},{signal:e?.signal,...e?.options}),{completion_tokens:a,prompt_tokens:l,total_tokens:u,prompt_tokens_details:f,completion_tokens_details:d}=i?.usage??{};a&&(s.output_tokens=(s.output_tokens??0)+a),l&&(s.input_tokens=(s.input_tokens??0)+l),u&&(s.total_tokens=(s.total_tokens??0)+u),(f?.audio_tokens!==null||f?.cached_tokens!==null)&&(s.input_token_details={...f?.audio_tokens!==null&&{audio:f?.audio_tokens},...f?.cached_tokens!==null&&{cache_read:f?.cached_tokens}}),(d?.audio_tokens!==null||d?.reasoning_tokens!==null)&&(s.output_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.reasoning_tokens!==null&&{reasoning:d?.reasoning_tokens}});let y=[];for(let _ of i?.choices??[]){let g={text:_.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(_.message??{role:"assistant"},i)};g.generationInfo={..._.finish_reason?{finish_reason:_.finish_reason}:{},..._.logprobs?{logprobs:_.logprobs}:{}},Ts(g.message)&&(g.message.usage_metadata=s),g.message=new ae(Object.fromEntries(Object.entries(g.message).filter(([x])=>!x.startsWith("lc_")))),y.push(g)}return{generations:y,llmOutput:{tokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}}async*_streamResponseChunks(t,e,r){let s=xs({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:s,stream:!0},o,i=await this.completionWithRetry(n,e),a;for await(let l of i){if(e.signal?.aborted)return;let u=l?.choices?.[0];if(l.usage&&(a=l.usage),!u)continue;let{delta:f}=u;if(!f)continue;let d=this._convertCompletionsDeltaToBaseMessageChunk(f,l,o);o=f.role??o;let y={prompt:e.promptIndex??0,completion:u.index??0};if(typeof d.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let _={...y};u.finish_reason!=null&&(_.finish_reason=u.finish_reason,_.system_fingerprint=l.system_fingerprint,_.model_name=l.model,_.service_tier=l.service_tier),this.logprobs&&(_.logprobs=u.logprobs);let g=new Jr({message:d,text:d.content,generationInfo:_});yield g,await r?.handleLLMNewToken(g.text??"",y,void 0,void 0,void 0,{chunk:g})}if(a){let l={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},u={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}},f=new Jr({message:new $t({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(l).length>0&&{input_token_details:l},...Object.keys(u).length>0&&{output_token_details:u}}}),text:""});yield f,await r?.handleLLMNewToken(f.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:f})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=this._getClientOptions(e),s=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return s&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(n){throw pe(n)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return vo({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Po({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var _n="__openai_function_call_ids__";function xu(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function Gc(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){let e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}var ko=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},r={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:r}},gn=t=>{if(t.error){let l=new Error(t.error.message);throw l.name=t.error.code,l}let e,r=[],s=[],n=[],o=t.output.map(l=>{if(l.type==="function_call"&&"parsed_arguments"in l){let u={...l};return delete u.parsed_arguments,u}return l}),i={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:o,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},a={};for(let l of t.output)if(l.type==="message")e=l.id,r.push(...l.content.flatMap(u=>u.type==="output_text"?("parsed"in u&&u.parsed!=null&&(a.parsed=u.parsed),{type:"text",text:u.text,annotations:u.annotations.map(xu),...l.phase!==null?{phase:l.phase}:{}}):u.type==="refusal"?(a.refusal=u.refusal,[]):u));else if(l.type==="function_call"){let u={function:{name:l.name,arguments:l.arguments},id:l.call_id};try{s.push(Es(u,{returnId:!0}))}catch(f){let d;typeof f=="object"&&f!=null&&"message"in f&&typeof f.message=="string"&&(d=f.message),n.push(Mt(u,d))}a[_n]??={},l.id&&(a[_n][l.call_id]=l.id)}else if(l.type==="reasoning"){a.reasoning=l;let u=l.summary?.map(f=>f.text).filter(Boolean).join("");u&&r.push({type:"reasoning",reasoning:u})}else if(l.type==="custom_tool_call"){let u=ba(l);u?s.push(u):n.push(Mt(l,"Malformed custom tool call"))}else if(l.type==="computer_call"){let u=xa(l);u?s.push(u):n.push(Mt(l,"Malformed computer call"))}else l.type==="image_generation_call"?(l.result&&r.push({type:"image",mimeType:"image/png",data:l.result,id:l.id,metadata:{status:l.status}}),a.tool_outputs??=[],a.tool_outputs.push(l)):(a.tool_outputs??=[],a.tool_outputs.push(l));return new ae({id:e,content:r,tool_calls:s,invalid_tool_calls:n,usage_metadata:ko(t.usage),additional_kwargs:a,response_metadata:i})},wu=t=>{let e=(t.summary.length>1?t.summary.reduce((r,s)=>{let n=r[r.length-1];return n.index===s.index?n.text+=s.text:r.push(s),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([s])=>s!=="index")));return{...t,summary:e}},To=t=>{let e=[],r={},s,n=[],o={model_provider:"openai"},i={},a;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[xu(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){a=t.item.id;let l="phase"in t.item?t.item.phase:void 0;l&&e.push({type:"text",text:"",phase:l,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")n.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[_n]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")n.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")o.id=t.response.id,o.model_name=t.response.model,o.model=t.response.model;else if(t.type==="response.completed"){let l=gn(t.response);s=ko(t.response.usage),t.response.text?.format?.type==="json_schema"&&l.text&&(i.parsed??=JSON.parse(l.text));for(let[u,f]of Object.entries(t.response))u!=="id"&&(u==="output"?o[u]=l.response_metadata.output:o[u]=f)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")n.push({type:"tool_call_chunk",args:t.delta,index:t.output_index});else if(t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.completed")r={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let l=t.item.summary?t.item.summary.map((f,d)=>({...f,index:d})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...l?{summary:l}:{}};let u=t.item.summary?.map(f=>f.text).filter(Boolean).join("");u&&e.push({type:"reasoning",reasoning:u})}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text});else if(t.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta});else return t.type==="response.image_generation_call.partial_image",null;return new Jr({text:e.map(l=>l.text).join(""),message:new $t({id:a,content:e,tool_call_chunks:n,usage_metadata:s,additional_kwargs:i,response_metadata:o}),generationInfo:r})},Ou=t=>{let e=ae.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let s=me(()=>{try{let h=$e(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"assistant"}catch{return"assistant"}}),n,o=new Set,i=new Set,a=new Map,l=new Map;function*u(){if(!n)return;let h=n.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield n),n=void 0}let f=(h,A)=>{n||(n={type:"message",role:s,content:[],...A?{phase:A}:{}}),typeof n.content=="string"?n.content=n.content.length>0?[{type:"input_text",text:n.content},...h]:[...h]:n.content.push(...h)},d=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},y=h=>{let A=me(()=>{let T=h.metadata?.detail;return T==="low"||T==="high"||T==="auto"?T:"auto"});if(h.fileId)return{type:"input_image",detail:A,file_id:h.fileId};if(h.url)return{type:"input_image",detail:A,image_url:h.url};if(h.data){let T=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_image",detail:A,image_url:`data:${h.mimeType??"image/png"};base64,${T}`}}},_=h=>{if(h.fileId){let A=yo(h);return{type:"input_file",file_id:h.fileId,...A?{filename:A}:{}}}if(h.url){let A=yo(h);return{...A?{filename:A}:{},type:"input_file",file_url:h.url}}if(h.data){let A=Wr(h),T=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_file",file_data:`data:${h.mimeType??"application/octet-stream"};base64,${T}`,filename:A}}},g=h=>{let A=me(()=>{if(Array.isArray(h.summary)){let q=h.summary?.map(j=>j?.text).filter(j=>typeof j=="string")??[];if(q.length>0)return q}return h.reasoning?[h.reasoning]:[]}),T=A.length>0?A.map(q=>({type:"summary_text",text:q})):[{type:"summary_text",text:""}],S={type:"reasoning",id:h.id??"",summary:T};return h.reasoning&&(S.content=[{type:"reasoning_text",text:h.reasoning}]),S},x=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:d(h.args)}),$=h=>{let A=d(h.output),T=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:A,...T?{status:T}:{}}};for(let h of t.contentBlocks)if(h.type==="text"){let A=me(()=>{if("extras"in h&&typeof h.extras=="object"&&h.extras!==null&&"phase"in h.extras)return h.extras.phase});f([{type:"input_text",text:h.text}],A)}else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*u(),yield g(h);else if(h.type==="tool_call"){yield*u();let A=h.id??"";A&&(o.add(A),a.delete(A)),yield x(h)}else if(h.type==="tool_call_chunk"){if(h.id){let A=a.get(h.id)??{name:h.name,args:[]};h.name&&(A.name=h.name),h.args&&A.args.push(h.args),a.set(h.id,A)}}else if(h.type==="server_tool_call"){yield*u();let A=h.id??"";A&&(i.add(A),l.delete(A)),yield x(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){let A=l.get(h.id)??{name:h.name,args:[]};h.name&&(A.name=h.name),h.args&&A.args.push(h.args),l.set(h.id,A)}}else if(h.type==="server_tool_call_result")yield*u(),yield $(h);else if(h.type!=="audio")if(h.type==="file"){let A=_(h);A&&f([A])}else if(h.type==="image"){let A=y(h);A&&f([A])}else if(h.type==="video"){let A=_(h);A&&f([A])}else h.type==="text-plain"?h.text&&f([{type:"input_text",text:h.text}]):h.type==="non_standard"&&e&&(yield*u(),yield h.value)}yield*u();for(let[h,A]of a){if(!h||o.has(h))continue;let T=A.args.join("");!A.name&&!T||(yield{type:"function_call",call_id:h,name:A.name??"",arguments:T})}for(let[h,A]of l){if(!h||i.has(h))continue;let T=A.args.join("");!A.name&&!T||(yield{type:"function_call",call_id:h,name:A.name??"",arguments:T})}}return Array.from(r())},yn=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(s=>{let n=s.response_metadata;if(n?.output_version==="v1")return Ou(s);let o=s.additional_kwargs,i=$e(s);if(i==="system"&&Se(r)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){let a=s;if(o?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let u=a.content.find(y=>y.type==="input_image");if(u)return u;let f=a.content.find(y=>y.type==="computer_screenshot");if(f)return f;let d=a.content.find(y=>y.type==="image_url");if(d)return{type:"input_image",image_url:typeof d.image_url=="string"?d.image_url:d.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let l=Array.isArray(a.content)&&a.content.every(u=>typeof u=="object"&&u!==null&&"type"in u&&(u.type==="input_file"||u.type==="input_image"||u.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:l?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(i==="assistant"){if(!e&&n?.output!=null&&Array.isArray(n?.output)&&n?.output.length>0&&n?.output.every(g=>"type"in g))return n?.output;let a=[],l=o?.reasoning,u=!!l?.encrypted_content;if(l&&(!e||u)){let g=wu(l);a.push(g)}let{content:f}=s;if(o?.refusal&&(typeof f=="string"&&(f=[{type:"output_text",text:f,annotations:[]}]),f=[...f,{type:"refusal",refusal:o.refusal}]),typeof f=="string"||f.length>0){let g={type:"message",role:"assistant",...s.id&&!e&&s.id.startsWith("msg_")?{id:s.id}:{},content:me(()=>typeof f=="string"?f:f.flatMap(x=>{if(x.type==="text"){let $=x;return{type:"output_text",text:$.text,annotations:($.annotations??[]).map(Gc)}}return x.type==="output_text"||x.type==="refusal"?x:[]})),phase:me(()=>{if(Array.isArray(f))return f.find(x=>"phase"in x&&typeof x.phase=="string")?.phase})};a.push(g)}let d=o?.[_n];ae.isInstance(s)&&s.tool_calls?.length?a.push(...s.tool_calls.map(g=>Oa(g)?{type:"custom_tool_call",id:g.call_id,call_id:g.id??"",input:g.args.input,name:g.name}:wa(g)?{type:"computer_call",id:g.call_id,call_id:g.id??"",action:g.args.action}:{type:"function_call",name:g.name,arguments:JSON.stringify(g.args),call_id:g.id,...e?{}:{id:d?.[g.id]}})):o?.tool_calls&&a.push(...o.tool_calls.map(g=>({type:"function_call",name:g.function.name,call_id:g.id,arguments:g.function.arguments,...e?{}:{id:d?.[g.id]}})));let y=n?.output?.length?n?.output:o.tool_outputs,_=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(y!=null){let g=y?.filter(x=>_.includes(x.type));g.length>0&&a.push(...g)}return a}if(i==="user"||i==="system"||i==="developer"){if(typeof s.content=="string")return{type:"message",role:i,content:s.content};let a=[],l=s.content.flatMap(u=>(u.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:u.approval_request_id,approve:u.approve}),Ps(u)?vs(u,dn):u.type==="text"?{type:"input_text",text:u.text}:u.type==="image_url"?{type:"input_image",image_url:me(()=>{if(typeof u.image_url=="string")return u.image_url;if(typeof u.image_url=="object"&&u.image_url!==null&&"url"in u.image_url)return u.image_url.url}),detail:me(()=>{if(typeof u.image_url=="string")return"auto";if(typeof u.image_url=="object"&&u.image_url!==null&&"detail"in u.image_url)return u.image_url.detail})}:u.type==="input_text"||u.type==="input_image"||u.type==="input_file"?u:[]));return l.length>0&&a.push({type:"message",role:i,content:l}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});var An=class extends St{constructor(t,e){super(Zr(t,e))}invocationParams(t){let e;t?.strict!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);let r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:t?.previous_response_id,truncation:t?.truncation,include:t?.include,tools:t?.tools?.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:Ia(t?.tool_choice)?t?.tool_choice:(()=>{let n=cn(t?.tool_choice);if(typeof n=="object"&&"type"in n){if(n.type==="function")return{type:"function",name:n.function.name};if(n.type==="allowed_tools")return{type:"allowed_tools",mode:n.allowed_tools.mode,tools:n.allowed_tools.tools};if(n.type==="custom")return{type:"custom",name:n.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let n=this._getResponseFormat(t?.response_format);return n?.type==="json_schema"?n.json_schema.schema!=null?{format:{type:"json_schema",schema:n.json_schema.schema,description:n.json_schema.description,name:n.json_schema.name,strict:n.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:n,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this._getReasoningParams(t);return s!==void 0&&(r.reasoning=s),r}async _generate(t,e,r){e.signal?.throwIfAborted();let s=this.invocationParams(e);if(s.stream){let n=this._streamResponseChunks(t,e,r),o;for await(let i of n)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},o=o?.concat(i)??i;return{generations:o?[o]:[],llmOutput:{estimatedTokenUsage:o?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:yn({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...s,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:n.output_text,message:gn(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(t,e,r){let s=await this.completionWithRetry({...this.invocationParams(e),input:yn({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(let n of s){if(e.signal?.aborted)return;let o=To(n);o!=null&&(yield o,await r?.handleLLMNewToken(o.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:o}))}}async completionWithRetry(t,e){return this.caller.call(async()=>{let r=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,r):await this.client.responses.create(t,r)}catch(s){throw pe(s)}})}_reduceChatOpenAITools(t,e){let r=[];for(let s of t)if(Hr(s))s.type==="image_generation"&&e?.stream&&(s.partial_images=1),r.push(s);else if(Ct(s)){let n=s.metadata.customTool;r.push({type:"custom",name:n.name,description:n.description,format:n.format})}else if(Rs(s)){let n={};for(let[o,i]of Object.entries(s))o!=="type"&&o!=="function"&&(n[o]=i);r.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:e?.strict??null,...n})}else pn(s)&&r.push(Pa(s));return r}};var In=class Pu extends St{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let s=Zr(e,r);super(s),this.fields=s,this.useResponsesApi=s?.useResponsesApi??!1,this.responses=s?.responses??new An(s),this.completions=s?.completions??new hn(s)}_useResponsesApi(e){let r=e?.tools?.some(Hr),s=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,n=e?.tools?.some(pn)||e?.tools?.some(Ct);return this.useResponsesApi||r||s||n||fa(this.model)}getLsParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(e,r,s){return this._useResponsesApi(r)?this.responses._generate(e,r,s):this.completions._generate(e,r,s)}async*_streamResponseChunks(e,r,s){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),s);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),s)}withConfig(e){let r=new Pu(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var bn=class extends Yo{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(t){let e={maxConcurrency:2,...t};super(e);let r=e?.apiKey??e?.openAIApiKey??ie("OPENAI_API_KEY");this.organization=e?.configuration?.organization??ie("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.batchSize=e?.batchSize??this.batchSize,this.stripNewLines=e?.stripNewLines??this.stripNewLines,this.timeout=e?.timeout,this.dimensions=e?.dimensions,this.encodingFormat=e?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration}}async embedDocuments(t){let e=Rn(this.stripNewLines?t.map(o=>o.replace(/\n/g," ")):t,this.batchSize),r=e.map(o=>{let i={model:this.model,input:o};return this.dimensions&&(i.dimensions=this.dimensions),this.encodingFormat&&(i.encoding_format=this.encodingFormat),this.embeddingWithRetry(i)}),s=await Promise.all(r),n=[];for(let o=0;o<s.length;o+=1){let i=e[o],{data:a}=s[o];for(let l=0;l<i.length;l+=1)n.push(a[l].embedding)}return n}async embedQuery(t){let e={model:this.model,input:this.stripNewLines?t.replace(/\n/g," "):t};this.dimensions&&(e.dimensions=this.dimensions),this.encodingFormat&&(e.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(e);return r[0].embedding}async embeddingWithRetry(t){if(!this.client){let r=Ne({baseURL:this.clientConfig.baseURL}),s={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};s.baseURL||delete s.baseURL,s.defaultHeaders=Me(s.defaultHeaders),this.client=new P(s)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw pe(r)}})}};var ep=I.object({type:I.literal("screenshot")}),tp=I.object({type:I.literal("click"),x:I.number(),y:I.number(),button:I.enum(["left","right","wheel","back","forward"]).default("left")}),rp=I.object({type:I.literal("double_click"),x:I.number(),y:I.number(),button:I.enum(["left","right","wheel","back","forward"]).default("left")}),sp=I.object({type:I.literal("drag"),path:I.array(I.object({x:I.number(),y:I.number()}))}),np=I.object({type:I.literal("keypress"),keys:I.array(I.string())}),op=I.object({type:I.literal("move"),x:I.number(),y:I.number()}),ip=I.object({type:I.literal("scroll"),x:I.number(),y:I.number(),scroll_x:I.number(),scroll_y:I.number()}),ap=I.object({type:I.literal("type"),text:I.string()}),up=I.object({type:I.literal("wait"),duration:I.number().optional()}),lp=I.union([ep,tp,rp,sp,np,op,ip,ap,up]),jv=I.object({action:lp});var cp=I.object({type:I.literal("exec"),command:I.array(I.string()),env:I.record(I.string(),I.string()).optional(),working_directory:I.string().optional(),timeout_ms:I.number().optional(),user:I.string().optional()}),Fv=I.union([cp]);var Wv=I.object({commands:I.array(I.string()).describe("Array of shell commands to execute"),timeout_ms:I.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:I.number().optional().describe("Optional maximum number of characters to return from each command")});var pp=I.object({type:I.literal("create_file"),path:I.string(),diff:I.string()}),mp=I.object({type:I.literal("update_file"),path:I.string(),diff:I.string()}),fp=I.object({type:I.literal("delete_file"),path:I.string()}),Jv=I.union([pp,mp,fp]);var Ro=new Map,xn=null,cdnPortalUrl=()=>{let e=[Tu.getDefault()?.url,hp.portalUrl].find(t=>typeof t==="string"&&t.trim());if(!e)throw new Error("未配置 Portal URL,请设置 Portal.getDefault().url 或 geosceneConfig.portalUrl。");return e.trim().replace(/\/+$/,"")},_p=()=>cdnPortalUrl()+"/ai-assistant/portal",Ru=async t=>{let e=_p();Ro.size===0&&(xn||(xn=(async()=>{try{let s=await fetch(e+"/models?f=json");if(!s.ok)throw new Error("获取 AI 模型发现服务数据失败。");let n=(await s.json()).models;if(!Array.isArray(n))throw new Error("AI 模型发现服务响应缺少 models 数组。");n.forEach(o=>Ro.set(o.name,o))}catch(s){throw xn=null,s}})()),await xn);let r=[...Ro.values()].filter(s=>s.model_type===t&&s.is_active===true);if(r.length!==1)throw new Error("应有且仅有一个已激活的 "+t+" 模型,实际数量为 "+r.length+".");let n=r[0];if(!n.name||!n.endpoint)throw new Error("已激活的 "+t+" 模型缺少 name 或 endpoint。");return{...n,endpoint:new URL(n.endpoint.replace(/^\/+/, ""),getPortalUrl()+"/").href}},yp=async()=>(await Ru("embedding")).endpoint,Vr=(t,e)=>e,Eu=(t,e)=>({...t,...e}),Su=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let s=t.trim();if(!s)return r;if(s===r)return t;let n=s.split(`
36
36
 
37
37
  `);return n[n.length-1]?.trim()===r?t:`${t}
38
38
 
@@ -1,3 +1,3 @@
1
1
  /* COPYRIGHT GeoScene - https://js.geoscene.cn/5.1/LICENSE.txt */
2
2
  import a from"./PFW7KXCP.js";import{b as f}from"./4EALV6QJ.js";import{a as l}from"./KGYSBUFO.js";import{U as R,a as v,b as x,ta as S,u as E}from"./H3EEFM4A.js";import{Z as I,ja as b}from"./4ASZF5I2.js";export default $geoscene.t(([O,P,q,N,T,{a:C,d:k,e:p,g:A,h:$,o:M}])=>{var U=async t=>{let e=await _(),r=await C("default"),s=P.getDefault(),n=(await O.getCredential(`${s.url}/sharing`)).token,a={type:"generateEmbeddings",webmapEmbeddings:t,auth:{apiUrl:r,token:n}};return e.postMessage(a),await new Promise((i,o)=>{let d=u=>{u.data==="completed"&&(e.removeEventListener("message",d),i())},c=u=>{e.removeEventListener("message",d),o(u instanceof Error?u:new Error("嵌入向量 Worker 出错"))};e.addEventListener("message",d),e.addEventListener("error",c,{once:!0})}),e},_=async()=>{{let t=(await import("./URYKQKFE.js")).default;return new t}},G=t=>{t.currentIntent="none"},z=async(t,e)=>{let r=p(e);if(t.agentExecutionContext.userRequest){let n=new b(t.agentExecutionContext.userRequest.trim());t.agentExecutionContext.messages=[...t.agentExecutionContext.messages,n],G(t)}let s=r?.services.agentRegistry.list().map(n=>n.agent.id)??[];return await l({text:`可用 Agent:${[...s].join(", ")}`},e),await l({text:"正在分析用户输入"},e),t},Q=async(t,e)=>(await l({text:"正在退出……"},e),t),D=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),B=(t,e)=>{if(!D(t)){t!==void 0&&console.warn(`Agent "${e}”返回的 sharedStatePatch 无效,已忽略。`);return}let r={};for(let[s,n]of Object.entries(t)){if(!D(n)||!("value"in n)){console.warn(`Agent "${e}”返回了无效的 sharedStatePatch 条目,字段为“${s}”,已忽略该条目。`);continue}r[s]={value:n.value}}return r},J=t=>{let{previousSharedState:e,patch:r,agentId:s}=t;if(!r)return e;let n=Date.now(),a={...e};for(let[i,o]of Object.entries(r))o?.value!==void 0&&(a[i]={value:o.value,meta:{updatedByAgentId:s,updatedAt:n}});return a},W=t=>typeof t!="string"?void 0:t.trim()||void 0,K=t=>{switch(t){case"failed":return"Agent 执行失败,未提供摘要。";case"unknown":return"Agent 返回未知状态。";case"success":return"Agent 已完成,未提供摘要。";default:return"Agent 已完成,未提供摘要。"}},V=(t,e)=>{let r=W(e?.outputMessage),s=W(e?.summary),n=e?.status,a=n==="success"||n==="failed"?n:"unknown";a==="unknown"&&console.warn(`Agent "${t}”缺少有效 status,默认设为 unknown。`);let i=B(e?.sharedStatePatch,t);return{outputMessage:r,summary:s??r??K(a),status:a,sharedStatePatch:i}},F=4e3,X=async(t,e)=>{let r=p(e);if(e?.signal?.aborted)return await l({text:"运行已取消,跳过 Agent 执行"},e),{...t,currentIntent:"none",requiresFollowUp:!1};let{agentRegistry:s}=r?.services??{},n=s?.get(t.currentIntent);if(!n)return console.warn(`未找到处理该意图的 Agent:${t.currentIntent}`),t;await l({text:`正在执行已注册 Agent:${n.agent.name}`},e);let a={...e??{},configurable:{...r??{},agentId:n.agent.id,context:n.getContext?await n.getContext():void 0}},i;try{let c=await n.agent.createGraph().compile().invoke({agentExecutionContext:{...t.agentExecutionContext,messages:[...t.agentExecutionContext.messages],priorSteps:structuredClone(t.agentExecutionContext.priorSteps??[]),sharedState:structuredClone(t.agentExecutionContext.sharedState??{})}},a);i=V(n.agent.name,c),await l({text:`已注册 Agent 执行完成:${n.agent.name}`},e)}catch(c){if(E(c)||e?.signal?.aborted||c instanceof Error&&c.name==="AbortError")throw c;let u=c instanceof Error?c.message:String(c);console.error(`Agent "${n.agent.name}”失败:`,c),await l({text:`已注册 Agent 执行失败:${n.agent.name}. ${u}`},e),i={status:"failed",outputMessage:`Agent 执行失败:${u}`,summary:`Agent 执行失败:${u}`}}let o=i.outputMessage,d=[...t.agentExecutionContext.messages];if(o){let c=o.length>F?`${o.slice(0,F-14)}
3
- [已截断]`:o;d.push(new I(c))}return{...t,stepCount:t.stepCount+1,lastExecutedAgent:n.agent.id,requiresFollowUp:i.status==="failed"?!0:t.requiresFollowUp,finalOutputMessage:o??"",agentExecutionContext:{...t.agentExecutionContext,messages:d,priorSteps:[...t.agentExecutionContext.priorSteps??[],{agentId:n.agent.id,assignedTask:t.agentExecutionContext.assignedTask,summary:i?.summary||"未提供摘要。",status:i?.status||"unknown"}],sharedState:J({previousSharedState:t.agentExecutionContext.sharedState,patch:i.sharedStatePatch,agentId:n.agent.id})}}},Y=3,Z=()=>new S(k).addNode("ingestInput",z).addNode("intentLLM",$).addNode("executeRegisteredAgent",X).addNode("exit",Q).addEdge(v,"ingestInput").addEdge("ingestInput","intentLLM").addConditionalEdges("intentLLM",t=>t.currentIntent==="none"||t.currentIntent===t.lastExecutedAgent?"exit":"executeRegisteredAgent").addConditionalEdges("executeRegisteredAgent",t=>t.stepCount>=Y||!t.requiresFollowUp?"exit":"intentLLM").addEdge("exit",x),w=class{constructor(){this.agentRegistry=new Map}register(e){let{agent:r}=e;if(this.agentRegistry.has(r.id))throw new Error(`重复的 Agent ID:${r.id}`);this.agentRegistry.set(r.id,e)}get(e){return this.agentRegistry.get(e)}list(){return[...this.agentRegistry.values()]}},y=class{constructor(e,r){this.graph=e,this.config={...r}}async waitForUser(){return await new Promise((e,r)=>{this.resolveWait=e,this.rejectWait=r})}handle(e,r){try{let s={agentId:e.agentId,id:e.id,payload:r},n=this.graph.streamEvents(null,{...this.config,configurable:{...this.config.configurable,hitlResponse:s},subgraphs:!0,version:"v2"});this.resolveWait?.(n)}catch(s){this.rejectWait?.(s)}finally{this.resolveWait=void 0,this.rejectWait=void 0}}cancel(){this.rejectWait&&(this.rejectWait(new Error("用户已取消请求。")),this.resolveWait=void 0,this.rejectWait=void 0)}},ee=async t=>{try{return await(await A()).embedDocuments(t)}catch(e){throw console.error("生成嵌入向量失败:",e),e}},j=async(t,e)=>{let r=e.get(t);if(r)return r;let s=await ee([t]);return e.set(t,s[0]),s[0]};async function te(t,e,r,s){let n=`req-${Date.now()}`,a={type:"layerSearch",precomputedEmbedding:s?await j(t,s):void 0,requestId:n,minScore:r};return await new Promise(i=>{let o=d=>{d.data.requestId===n&&i(d.data.results.filter(item=>item.score>=r))};e.addEventListener("message",o,{once:!0}),e.postMessage(a)})}function re(t){let{worker:e}=t;return{async searchLayers({text:r,minScore:s,embeddingCache:n}){return await te(r,e,s,n)}}}var ne=async({combinedQuery:t,layerIds:e,embeddingsWorker:r,minScore:s,topResults:n,embeddingCache:a})=>{let i=`req-${Date.now()}`,o=a?await j(t,a):void 0,d={type:"fieldSearch",layerIdForFieldsSearch:e,precomputedEmbedding:o,requestId:i,minScore:s,topResults:n};return await new Promise(c=>{let u=h=>{if(h.data.requestId!==i)return;let g=h.data.results.map(({layerId:m,results:H})=>({layerId:m,results:H}));c(g)};r.addEventListener("message",u,{once:!0}),r.postMessage(d)})};function se(t){let{worker:e}=t;return{async searchFields({text:r,layerIds:s,minScore:n,topResults:a,embeddingCache:i}){return await ne({combinedQuery:r,layerIds:s,embeddingsWorker:e,minScore:n,topResults:a,embeddingCache:i})}}}var ae=async t=>{let e=await M.safeParseAsync(t);if(!e.success)throw new Error("嵌入向量响应校验失败,请重新生成向量。");return e.data},ie=(t,e)=>{let r=new Map,s=new Map;if(e.allLayers.forEach(n=>{n instanceof N&&s.set(n.id,n)}),t.length!==s.size)throw new Error("恢复注册表时图层数量不一致,请重新生成向量。");for(let n of t){let a=s.get(n.id);if(!a)throw new Error(`ID 为 ${n.id} 的图层未在原地图中找到,请重新生成向量。`);if(n.fields.length!==a.fields.length)throw new Error(`恢复注册表时字段数量不一致,图层 ID:${n.id},请重新生成向量。`);let i={name:n.name,title:n.title,description:n.description},o=new Map;for(let d of n.fields){let c=a.fieldsIndex.get(d.name);if(!c)throw new Error(`字段 ${d.name} 未在原图层中找到,图层 ID:${n.id},请重新生成向量。`);o.set(d.name,{name:d.name,alias:a.getFieldAlias(d.name)??d.alias,description:d.description,type:c.type||"unknown",valueType:c.valueType||"unknown",domain:a.getFieldDomain(d.name)??void 0})}r.set(n.id,{layerItem:i,fieldRegistry:o})}return r},oe=async t=>{try{return(await T(t,{responseType:"json"})).data}catch(e){throw new Error(`获取数据失败,地址:${t}: ${String(e)}`)}},de=async t=>{let e=t.map;if(!e?.portalItem)throw new Error("缺少 WebMap 的 Portal 资源。");let{resources:r}=await e.portalItem.fetchResources(),s=r.find(a=>a.resource.path==="embeddings-v01.json");if(!s?.resource.url)throw new Error("WebMap 的 Portal 资源中未找到 embeddings-v01.json。");let n=await oe(s.resource.url);return ae(n)},L=class t{constructor(){this.orchestratorReady=!1,this.chatHistory=[],this.priorSteps=[],this.sharedState={},this.agentRegistry=new w,this.activeRunId="",this.cancelledRunIds=new Set,this.streamEpoch=0}static async init(e){let r=new t;try{if(e.view?.map){await q.whenOnce(()=>e.view.ready);let s=await de(e.view),n=ie(s.layers,e.view.map);r.layersAndFieldsRegistry=n,r.embeddingsWorker=await U(s)}return e.agents?.forEach(s=>{r.agentRegistry.register(s)}),r.orchestratorReady=!0,r}catch(s){throw console.error("编排器初始化失败:",s),s}}async*ask(e){if(!this.orchestratorReady)throw new Error("编排器尚未就绪。");if(!this.agentRegistry.list().length)throw new Error("编排器未注册任何 Agent。");if(++this.streamEpoch,!e.trim())return;let r=f();this.activeRunId=r,this.activeAbortController=new AbortController,this.graph||(this.graph=Z().compile({checkpointer:new R}));let s=this.embeddingsWorker?re({worker:this.embeddingsWorker}):void 0,n=this.embeddingsWorker?se({worker:this.embeddingsWorker}):void 0,a=new Map,i={thread_id:r,hitlResponse:null,services:{layerSearch:s,fieldSearch:n,layersAndFieldsRegistry:this.layersAndFieldsRegistry,agentRegistry:this.agentRegistry,embeddingCache:a}},o={version:"v2",streamMode:"custom",signal:this.activeAbortController.signal,configurable:i,subgraphs:!0},d=this.graph?.streamEvents({agentExecutionContext:{userRequest:e,messages:this.chatHistory,priorSteps:this.priorSteps,sharedState:this.sharedState}},o),c=++this.streamEpoch;if(yield*this.pipeStream(d,c,r),this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}for(;;){if(this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}let h=(await this.graph.getState(o,{subgraphs:!0})).tasks.find(g=>g.interrupts.length>0)?.interrupts[0]?.value;if(!h)break;this.currentInterrupt=h,this.interruptHandler=new y(this.graph,o),yield{runId:r,timestamp:Date.now(),type:"interrupt",interrupt:h};try{let g=await this.interruptHandler.waitForUser(),m=++this.streamEpoch;yield*this.pipeStream(g,m,r)}catch(g){if(this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}if(g){yield{runId:r,timestamp:Date.now(),type:"error",error:{message:g?.message}};return}}}if(this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}let u=(await this.graph.getState(o,{subgraphs:!0})).values;if(this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}this.chatHistory=u.agentExecutionContext.messages.length?u.agentExecutionContext.messages:this.chatHistory,this.priorSteps=u.agentExecutionContext.priorSteps?.slice(-5)??[],this.sharedState=u.agentExecutionContext.sharedState??{},yield{runId:r,timestamp:Date.now(),type:"completed",result:{content:u.finalOutputMessage}}}newConversation(){this.chatHistory=[],this.priorSteps=[],this.sharedState={}}resumeInterrupt(e){if(!this.currentInterrupt||!this.interruptHandler)throw new Error("没有可恢复的待处理中断。");this.interruptHandler.handle(this.currentInterrupt,e)}cancelInterrupt(){this.interruptHandler&&this.interruptHandler.cancel()}cancel(){this.activeRunId&&(this.cancelledRunIds.add(this.activeRunId),this.activeAbortController?.abort(),++this.streamEpoch,this.interruptHandler?.cancel())}async*pipeStream(e,r,s){for await(let n of e){if(this.isRunCancelled(s)||r!==this.streamEpoch)break;n.event==="on_custom_event"&&n.name==="trace_message"?yield{runId:s,timestamp:Date.now(),type:"trace",data:n.data}:n.name==="graph_ux_suggestion"&&(yield{runId:s,timestamp:Date.now(),type:"ux-suggestion",suggestion:n.data})}}isRunCancelled(e){return this.cancelledRunIds.has(e)}dispose(){this.embeddingsWorker&&(this.embeddingsWorker.terminate(),this.embeddingsWorker=void 0),this.orchestratorReady=!1}};return{a:ee,b:L}},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request",a)
3
+ [已截断]`:o;d.push(new I(c))}return{...t,stepCount:t.stepCount+1,lastExecutedAgent:n.agent.id,requiresFollowUp:i.status==="failed"?!0:t.requiresFollowUp,finalOutputMessage:o??"",agentExecutionContext:{...t.agentExecutionContext,messages:d,priorSteps:[...t.agentExecutionContext.priorSteps??[],{agentId:n.agent.id,assignedTask:t.agentExecutionContext.assignedTask,summary:i?.summary||"未提供摘要。",status:i?.status||"unknown"}],sharedState:J({previousSharedState:t.agentExecutionContext.sharedState,patch:i.sharedStatePatch,agentId:n.agent.id})}}},Y=3,Z=()=>new S(k).addNode("ingestInput",z).addNode("intentLLM",$).addNode("executeRegisteredAgent",X).addNode("exit",Q).addEdge(v,"ingestInput").addEdge("ingestInput","intentLLM").addConditionalEdges("intentLLM",t=>t.currentIntent==="none"||t.currentIntent===t.lastExecutedAgent?"exit":"executeRegisteredAgent").addConditionalEdges("executeRegisteredAgent",t=>t.stepCount>=Y||!t.requiresFollowUp?"exit":"intentLLM").addEdge("exit",x),w=class{constructor(){this.agentRegistry=new Map}register(e){let{agent:r}=e;if(this.agentRegistry.has(r.id))throw new Error(`重复的 Agent ID:${r.id}`);this.agentRegistry.set(r.id,e)}get(e){return this.agentRegistry.get(e)}list(){return[...this.agentRegistry.values()]}},y=class{constructor(e,r){this.graph=e,this.config={...r}}async waitForUser(){return await new Promise((e,r)=>{this.resolveWait=e,this.rejectWait=r})}handle(e,r){try{let s={agentId:e.agentId,id:e.id,payload:r},n=this.graph.streamEvents(null,{...this.config,configurable:{...this.config.configurable,hitlResponse:s},subgraphs:!0,version:"v2"});this.resolveWait?.(n)}catch(s){this.rejectWait?.(s)}finally{this.resolveWait=void 0,this.rejectWait=void 0}}cancel(){this.rejectWait&&(this.rejectWait(new Error("用户已取消请求。")),this.resolveWait=void 0,this.rejectWait=void 0)}},ee=async t=>{try{return await(await A()).embedDocuments(t)}catch(e){throw console.error("生成嵌入向量失败:",e),e}},j=async(t,e)=>{let r=e.get(t);if(r)return r;let s=await ee([t]);return e.set(t,s[0]),s[0]};async function te(t,e,r,s){let n=`req-${Date.now()}`,a={type:"layerSearch",precomputedEmbedding:s?await j(t,s):void 0,requestId:n,minScore:r};return await new Promise(i=>{let o=d=>{d.data.requestId===n&&i(d.data.results)};e.addEventListener("message",o,{once:!0}),e.postMessage(a)})}function re(t){let{worker:e}=t;return{async searchLayers({text:r,minScore:s,embeddingCache:n}){return await te(r,e,s,n)}}}var ne=async({combinedQuery:t,layerIds:e,embeddingsWorker:r,minScore:s,topResults:n,embeddingCache:a})=>{let i=`req-${Date.now()}`,o=a?await j(t,a):void 0,d={type:"fieldSearch",layerIdForFieldsSearch:e,precomputedEmbedding:o,requestId:i,minScore:s,topResults:n};return await new Promise(c=>{let u=h=>{if(h.data.requestId!==i)return;let g=h.data.results.map(({layerId:m,results:H})=>({layerId:m,results:H}));c(g)};r.addEventListener("message",u,{once:!0}),r.postMessage(d)})};function se(t){let{worker:e}=t;return{async searchFields({text:r,layerIds:s,minScore:n,topResults:a,embeddingCache:i}){return await ne({combinedQuery:r,layerIds:s,embeddingsWorker:e,minScore:n,topResults:a,embeddingCache:i})}}}var ae=async t=>{let e=await M.safeParseAsync(t);if(!e.success)throw new Error("嵌入向量响应校验失败,请重新生成向量。");return e.data},ie=(t,e)=>{let r=new Map,s=new Map;if(e.allLayers.forEach(n=>{n instanceof N&&s.set(n.id,n)}),t.length!==s.size)throw new Error("恢复注册表时图层数量不一致,请重新生成向量。");for(let n of t){let a=s.get(n.id);if(!a)throw new Error(`ID 为 ${n.id} 的图层未在原地图中找到,请重新生成向量。`);if(n.fields.length!==a.fields.length)throw new Error(`恢复注册表时字段数量不一致,图层 ID:${n.id},请重新生成向量。`);let i={name:n.name,title:n.title,description:n.description},o=new Map;for(let d of n.fields){let c=a.fieldsIndex.get(d.name);if(!c)throw new Error(`字段 ${d.name} 未在原图层中找到,图层 ID:${n.id},请重新生成向量。`);o.set(d.name,{name:d.name,alias:a.getFieldAlias(d.name)??d.alias,description:d.description,type:c.type||"unknown",valueType:c.valueType||"unknown",domain:a.getFieldDomain(d.name)??void 0})}r.set(n.id,{layerItem:i,fieldRegistry:o})}return r},oe=async t=>{try{return(await T(t,{responseType:"json"})).data}catch(e){throw new Error(`获取数据失败,地址:${t}: ${String(e)}`)}},de=async t=>{let e=t.map;if(!e?.portalItem)throw new Error("缺少 WebMap 的 Portal 资源。");let{resources:r}=await e.portalItem.fetchResources(),s=r.find(a=>a.resource.path==="embeddings-v01.json");if(!s?.resource.url)throw new Error("WebMap 的 Portal 资源中未找到 embeddings-v01.json。");let n=await oe(s.resource.url);return ae(n)},L=class t{constructor(){this.orchestratorReady=!1,this.chatHistory=[],this.priorSteps=[],this.sharedState={},this.agentRegistry=new w,this.activeRunId="",this.cancelledRunIds=new Set,this.streamEpoch=0}static async init(e){let r=new t;try{if(e.view?.map){await q.whenOnce(()=>e.view.ready);let s=await de(e.view),n=ie(s.layers,e.view.map);r.layersAndFieldsRegistry=n,r.embeddingsWorker=await U(s)}return e.agents?.forEach(s=>{r.agentRegistry.register(s)}),r.orchestratorReady=!0,r}catch(s){throw console.error("编排器初始化失败:",s),s}}async*ask(e){if(!this.orchestratorReady)throw new Error("编排器尚未就绪。");if(!this.agentRegistry.list().length)throw new Error("编排器未注册任何 Agent。");if(++this.streamEpoch,!e.trim())return;let r=f();this.activeRunId=r,this.activeAbortController=new AbortController,this.graph||(this.graph=Z().compile({checkpointer:new R}));let s=this.embeddingsWorker?re({worker:this.embeddingsWorker}):void 0,n=this.embeddingsWorker?se({worker:this.embeddingsWorker}):void 0,a=new Map,i={thread_id:r,hitlResponse:null,services:{layerSearch:s,fieldSearch:n,layersAndFieldsRegistry:this.layersAndFieldsRegistry,agentRegistry:this.agentRegistry,embeddingCache:a}},o={version:"v2",streamMode:"custom",signal:this.activeAbortController.signal,configurable:i,subgraphs:!0},d=this.graph?.streamEvents({agentExecutionContext:{userRequest:e,messages:this.chatHistory,priorSteps:this.priorSteps,sharedState:this.sharedState}},o),c=++this.streamEpoch;if(yield*this.pipeStream(d,c,r),this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}for(;;){if(this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}let h=(await this.graph.getState(o,{subgraphs:!0})).tasks.find(g=>g.interrupts.length>0)?.interrupts[0]?.value;if(!h)break;this.currentInterrupt=h,this.interruptHandler=new y(this.graph,o),yield{runId:r,timestamp:Date.now(),type:"interrupt",interrupt:h};try{let g=await this.interruptHandler.waitForUser(),m=++this.streamEpoch;yield*this.pipeStream(g,m,r)}catch(g){if(this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}if(g){yield{runId:r,timestamp:Date.now(),type:"error",error:{message:g?.message}};return}}}if(this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}let u=(await this.graph.getState(o,{subgraphs:!0})).values;if(this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}this.chatHistory=u.agentExecutionContext.messages.length?u.agentExecutionContext.messages:this.chatHistory,this.priorSteps=u.agentExecutionContext.priorSteps?.slice(-5)??[],this.sharedState=u.agentExecutionContext.sharedState??{},yield{runId:r,timestamp:Date.now(),type:"completed",result:{content:u.finalOutputMessage}}}newConversation(){this.chatHistory=[],this.priorSteps=[],this.sharedState={}}resumeInterrupt(e){if(!this.currentInterrupt||!this.interruptHandler)throw new Error("没有可恢复的待处理中断。");this.interruptHandler.handle(this.currentInterrupt,e)}cancelInterrupt(){this.interruptHandler&&this.interruptHandler.cancel()}cancel(){this.activeRunId&&(this.cancelledRunIds.add(this.activeRunId),this.activeAbortController?.abort(),++this.streamEpoch,this.interruptHandler?.cancel())}async*pipeStream(e,r,s){for await(let n of e){if(this.isRunCancelled(s)||r!==this.streamEpoch)break;n.event==="on_custom_event"&&n.name==="trace_message"?yield{runId:s,timestamp:Date.now(),type:"trace",data:n.data}:n.name==="graph_ux_suggestion"&&(yield{runId:s,timestamp:Date.now(),type:"ux-suggestion",suggestion:n.data})}}isRunCancelled(e){return this.cancelledRunIds.has(e)}dispose(){this.embeddingsWorker&&(this.embeddingsWorker.terminate(),this.embeddingsWorker=void 0),this.orchestratorReady=!1}};return{a:ee,b:L}},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request",a)
@@ -1,6 +1,6 @@
1
1
  /* COPYRIGHT GeoScene - https://js.geoscene.cn/5.1/LICENSE.txt */
2
2
  import a from"./PFW7KXCP.js";import{a as S,b as x}from"./KGYSBUFO.js";import{_ as b,ea as xe,g as Te,j as B,k as U,pa as D,u as Se}from"./H3EEFM4A.js";import{L as z,P as oe,_ as j,wc as y}from"./4ASZF5I2.js";import{a as s}from"./QH6TSBNI.js";import{Dd as N}from"./LXJWWOGK.js";export default $geoscene.t(([Me,F,ie,je,,Ae,nt,{addressToLocations:it},st,lt,De,{createRenderer:ct},{getSchemesByTag:ut,getSchemes:dt},{getBackgroundColorTheme:Re},{createAgeRenderer:pt,createContinuousRenderer:mt},{getSchemesByTag:ge},{createContinuousRenderer:ht},{createRenderer:ft},{getSchemesByTag:yt},{createRenderer:gt},{getSchemesByTag:wt},{createRenderer:bt},{getSchemesByTag:vt},{createRenderer:Tt},{getSchemesByTag:St},{createAgeRenderer:xt,createContinuousRenderer:Et},{createRenderer:It},{getSchemesByTag:Nt},kt,Le,Oe,{formatDateOnly:$t,convertDateFormatToIntlOptions:W,formatTimeOnly:Ft,formatDate:qe},Mt,At,Rt,qt,Ct,Pe,,{fetchKnowledgeGraph:Ce,executeQueryStreaming:_t,executeSearchStreaming:zt},jt,{getBindParametersFromCypherQuery:Dt},{b:L,c:Ee,q:Ie}])=>{var Fe=e=>Array.isArray(e)&&e.every(z),tt=e=>typeof e=="object"&&e!=null&&"messages"in e&&Fe(e.messages),rt=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,K=class extends xe{tools;handleToolErrors=!0;trace=!1;constructor(e,t){let{name:r,tags:o,handleToolErrors:a}=t??{};super({name:r,tags:o,func:(n,l)=>this.run(n,l)}),this.tools=e,this.handleToolErrors=a??this.handleToolErrors}async runTool(e,t){let r=this.tools.find(o=>o.name===e.name);try{if(r===void 0)throw new Error(`Tool "${e.name}”不存在。`);let o=await r.invoke({...e,type:"tool_call"},t);return z(o)&&o.getType()==="tool"||U(o)?o:new oe({status:"success",name:r.name,content:typeof o=="string"?o:JSON.stringify(o),tool_call_id:e.id})}catch(o){if(!this.handleToolErrors||Se(o))throw o;return new oe({status:"error",content:`错误:${o.message}
3
- Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,t){let r;if(rt(e))r=[await this.runTool(e.lg_tool_call,t)];else{let n;if(Fe(e))n=e;else if(tt(e))n=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let l=new Set(n.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=n.length-1;u>=0;u-=1){let c=n[u];if(j(c)){i=c;break}}if(i==null||!j(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!l.has(u.id)).map(u=>this.runTool(u,t))??[])}if(!r.some(U))return Array.isArray(e)?r:{messages:r};let o=[],a=null;for(let n of r)U(n)?n.graph===B.PARENT&&Array.isArray(n.goto)&&n.goto.every(l=>Te(l))?a?a.goto.push(...n.goto):a=new B({graph:B.PARENT,goto:n.goto}):o.push(n):o.push(Array.isArray(e)?[n]:{messages:[n]});return a&&o.push(a),o}};var Dn=b.Root({llmInputMessages:b({reducer:(e,t)=>D([],t),default:()=>[]})});var O=(e,t)=>t??e,Wi=b.Root({...Ee(),intent:b({reducer:O}),vectorSearchLayerResults:b({reducer:O,default:()=>[]}),vectorSearchFieldResults:b({reducer:O}),navigationInternalState:b({reducer:O,default:()=>({toolCallMessage:void 0})})});async function Lt(e,t){let r=F.getDefault().helperServices,o=r.geocode.find(d=>d.name==="GeoScene World Geocoding Service")??r.geocode[0];if(!o)throw new Error("helperServices 中没有地理编码服务。");let a=o.url,n=`${ie.assetsPath?.endsWith("/")?ie.assetsPath:`${ie.assetsPath}/`}esri/images/search/search-symbol-32.png`,l=(await it(a,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!l?.extent||!l.location)throw new Error(`未找到以下位置:${e}`);let i=new st({url:n,width:24,height:24}),u=new nt({geometry:l.location,symbol:i});t.graphics.removeAll(),t.graphics.add(u),await t.goTo(l.extent);let c={address:l.address??"",location:l.location?l.location.toJSON():null,extent:l.extent?l.extent.toJSON():null};return{text:`已缩放到 ${e}.`,sharedStatePatch:{lastResolvedLocation:{value:c}}}}var Ot=["mapView"];function k(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("NavigationAgent 缺少上下文");let r=Ot.filter(o=>!(o in t));if(r.length)throw new Error(`NavigationAgent 缺少上下文:${r.join(", ")}`);return t}async function Pt({address:e},t){let{mapView:r}=k(t);return await Lt(e,r)}var Gt=s.object({address:s.string().describe("要定位的完整地址或地名。")}),Hi=y(Pt,{name:"goToAddress",description:"使用 GeoScene 全球地理编码服务解析地址,并将地图缩放到该位置。",schema:Gt});async function Vt(e,t){let r=t.map.bookmarks;if(!r||r.length===0)throw new Error("地图中没有书签。");let o=r.find(n=>n.name===e);if(!o)throw new Error(`书签“${e}”不存在。`);let a=o.viewpoint;if(!a)throw new Error(`书签“${e}”没有有效视点。`);return await t.goTo(a),{text:`已定位到书签:${e}`}}async function Qt({bookmarkName:e},t){let{mapView:r}=k(t);return await Promise.resolve(Vt(e,r))}var Bt=N.object({bookmarkName:N.string().describe("要定位到的书签名称。")}),Ji=y(Qt,{name:"goToBookmark",description:"定位到指定名称书签的范围。",schema:Bt});async function Ut(e,t,r){let o=r.map?.allLayers.find(l=>l.id===e);if(!o)return{text:`错误:未找到图层,ID 为 ${e},不存在`};let a=t?.trim()?t:"1=1",n=o.createQuery();n.where=a;try{let{extent:l,count:i}=await o.queryExtent(n);if(i===0)return{text:`未找到要素,图层为 ${o.title},匹配条件:${a}`,where:a};if(l)await r.goTo(l);else return{text:`错误:无法确定以下要素的范围:${o.title}`,where:a};let u={layerId:e,layerTitle:o.title??e,where:a,count:i};return{text:`已缩放到 ${i} 个要素,所在图层:${o.title},匹配条件:${a}`,where:a,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(l){return console.error("goToFeatures 执行错误:",l),{text:`错误:${l instanceof Error?l.message:"未知错误"}`,where:a}}}async function Kt({layerId:e,where:t},r){let{mapView:o}=k(r);return await Ut(e,t,o)}var Wt=N.object({layerId:N.string().describe("要缩放到的图层 layerId。"),where:N.string().describe("所选图层 query.where 使用的 GeoScene SQL-92 WHERE 表达式。只能使用该图层字段,返回布尔过滤表达式,例如比较、LIKE、IN、BETWEEN、IS NULL、AND/OR/NOT。不得包含子查询、嵌套 SELECT、JOIN、GROUP BY、HAVING、ORDER BY 或分号。")}),Zi=y(Kt,{name:"goToFeatures",description:"定位到指定 layerId 中符合过滤条件的要素。",schema:Wt});async function Ht(e){let t=new lt({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await e.goTo(t),{text:"已缩放到全球范围"}}async function Jt(e,t){let{mapView:r}=k(t);return await Ht(r)}var Zt=N.object({}),Yi=y(Jt,{name:"goToFullExtent",description:"使用 GeoScene 地理编码服务将地图缩放到全球范围。",schema:Zt});async function Yt(e){let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;if(t)await e.goTo(t);else throw new Error("未定义初始范围");return{text:"已返回初始范围"}}async function Xt(e,t){let{mapView:r}=k(t);return await Yt(r)}var er=s.object({}),Xi=y(Xt,{name:"goToHomeExtent",description:"返回 WebMap 初始视图范围",schema:er});async function tr(e,t){await t.when();let r=t.map?.allLayers.find(a=>a.id===e);if(!r)return console.warn(`[goToLayer] 未找到匹配的 FeatureLayer:${e}`),{text:`未找到图层:${e}`};let o;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&t.map?.activeLinkChartLayer?o=t.map.diagramNodesExtent:o=r.fullExtent,o?(await t.goTo(o),r.visible=!0,{text:`已缩放到:${r.title??""}`}):{text:"图层未定义范围,无法缩放到该图层。"}}async function rr({layerId:e},t){let{mapView:r}=k(t);return await tr(e,r)}var or=N.object({layerId:N.string().describe("要定位的图层 ID")}),es=y(rr,{name:"goToLayer",description:"将地图缩放到最佳匹配图层的完整范围。",schema:or});async function ar(e,t){return await t.goTo({scale:e}),{text:`已缩放到:${e}`}}async function nr({scale:e},t){let{mapView:r}=k(t);return await ar(e,r)}var ir=s.object({scale:s.number().describe("目标视图的地图比例尺。")}),ts=y(nr,{name:"goToScale",description:"定位到指定比例尺。",schema:ir});async function sr(e,t,r){let o={target:new De({longitude:e.longitude,latitude:e.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(o.zoom=r.zoom),r?.scale!==void 0&&(o.scale=r.scale),await t.goTo(o),{text:`已定位到:${[`(${e.latitude}\xB0, ${e.longitude}\xB0)`,r?.zoom!==void 0?`缩放级别 ${r.zoom}`:"",r?.scale!==void 0?`比例尺 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function lr({center:e,zoom:t,scale:r},o){let{mapView:a}=k(o);return await sr(e,a,{zoom:t,scale:r})}var cr=s.object({center:s.object({longitude:s.number().describe("目标点的经度,即 x 坐标。"),latitude:s.number().describe("目标点的纬度,即 y 坐标。")}),zoom:s.number().optional().describe("缩放级别,数值越大,地图放得越大。"),scale:s.number().optional().describe("地图比例尺,可替代 zoom;比例尺分母越小,地图放得越大。")}),rs=y(lr,{name:"goToViewpoint",description:"定位到指定视点,可以组合 scale、center、zoom 等参数。",schema:cr});async function ur(e,t){return await t.goTo({zoom:e}),{text:`已缩放到:${e}`}}async function dr({zoom:e},t){let{mapView:r}=k(t);return await ur(e,r)}var pr=s.object({zoom:s.number().min(1).max(20).describe("目标视图的缩放级别。")}),os=y(dr,{name:"goToZoom",description:"定位到指定缩放级别。如果要求较笼统,例如“放大”,只调整到下一个适当级别;放大时增加级别,缩小时降低级别。",schema:pr}),_e=Object.assign({"../agents/geosceneKnowledge/prompts/geoscene_knowledge_current_lc_context.md":()=>import("./VDAF255D.js").then(e=>e.default),"../agents/geosceneKnowledge/prompts/geoscene_knowledge_current_map_context.md":()=>import("./BUTKUPXN.js").then(e=>e.default),"../agents/geosceneKnowledge/prompts/geoscene_knowledge_cypher_query_prompt.md":()=>import("./CU2TRUZQ.js").then(e=>e.default),"../agents/geosceneKnowledge/prompts/geoscene_knowledge_lucene_generation_prompt.md":()=>import("./53Z3R4OY.js").then(e=>e.default),"../agents/geosceneKnowledge/prompts/geoscene_knowledge_summarize_result_prompt.md":()=>import("./4BA4OUWC.js").then(e=>e.default),"../agents/geosceneKnowledge/prompts/geoscene_knowledge_tool_prompt_knowledge_tool_prompt.md":()=>import("./PTKZXFXB.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./NMWLJECU.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./5RQUSM3T.js").then(e=>e.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./VWMJ7HIK.js").then(e=>e.default),"../agents/help/prompts/help_prompt.md":()=>import("./N2SKXRLK.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./77GAVZIK.js").then(e=>e.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./AJKWCXDA.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./HJGF7W5O.js").then(e=>e.default)});async function Z(e){let t=Object.entries(_e).find(([r])=>r.endsWith(`/${e}.md`));if(!t)throw new Error(`未找到提示词:${e}
3
+ Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,t){let r;if(rt(e))r=[await this.runTool(e.lg_tool_call,t)];else{let n;if(Fe(e))n=e;else if(tt(e))n=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let l=new Set(n.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=n.length-1;u>=0;u-=1){let c=n[u];if(j(c)){i=c;break}}if(i==null||!j(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!l.has(u.id)).map(u=>this.runTool(u,t))??[])}if(!r.some(U))return Array.isArray(e)?r:{messages:r};let o=[],a=null;for(let n of r)U(n)?n.graph===B.PARENT&&Array.isArray(n.goto)&&n.goto.every(l=>Te(l))?a?a.goto.push(...n.goto):a=new B({graph:B.PARENT,goto:n.goto}):o.push(n):o.push(Array.isArray(e)?[n]:{messages:[n]});return a&&o.push(a),o}};var Dn=b.Root({llmInputMessages:b({reducer:(e,t)=>D([],t),default:()=>[]})});var O=(e,t)=>t??e,Wi=b.Root({...Ee(),intent:b({reducer:O}),vectorSearchLayerResults:b({reducer:O,default:()=>[]}),vectorSearchFieldResults:b({reducer:O}),navigationInternalState:b({reducer:O,default:()=>({toolCallMessage:void 0})})});async function Lt(e,t){let r=F.getDefault().helperServices,o=r.geocode.find(d=>d.name==="GeoScene World Geocoding Service")??r.geocode[0];if(!o)throw new Error("helperServices 中没有地理编码服务。");let a=o.url,n=`${ie.assetsPath?.endsWith("/")?ie.assetsPath:`${ie.assetsPath}/`}geoscene/images/search/search-symbol-32.png`,l=(await it(a,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!l?.extent||!l.location)throw new Error(`未找到以下位置:${e}`);let i=new st({url:n,width:24,height:24}),u=new nt({geometry:l.location,symbol:i});t.graphics.removeAll(),t.graphics.add(u),await t.goTo(l.extent);let c={address:l.address??"",location:l.location?l.location.toJSON():null,extent:l.extent?l.extent.toJSON():null};return{text:`已缩放到 ${e}.`,sharedStatePatch:{lastResolvedLocation:{value:c}}}}var Ot=["mapView"];function k(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("NavigationAgent 缺少上下文");let r=Ot.filter(o=>!(o in t));if(r.length)throw new Error(`NavigationAgent 缺少上下文:${r.join(", ")}`);return t}async function Pt({address:e},t){let{mapView:r}=k(t);return await Lt(e,r)}var Gt=s.object({address:s.string().describe("要定位的完整地址或地名。")}),Hi=y(Pt,{name:"goToAddress",description:"使用 GeoScene 全球地理编码服务解析地址,并将地图缩放到该位置。",schema:Gt});async function Vt(e,t){let r=t.map.bookmarks;if(!r||r.length===0)throw new Error("地图中没有书签。");let o=r.find(n=>n.name===e);if(!o)throw new Error(`书签“${e}”不存在。`);let a=o.viewpoint;if(!a)throw new Error(`书签“${e}”没有有效视点。`);return await t.goTo(a),{text:`已定位到书签:${e}`}}async function Qt({bookmarkName:e},t){let{mapView:r}=k(t);return await Promise.resolve(Vt(e,r))}var Bt=N.object({bookmarkName:N.string().describe("要定位到的书签名称。")}),Ji=y(Qt,{name:"goToBookmark",description:"定位到指定名称书签的范围。",schema:Bt});async function Ut(e,t,r){let o=r.map?.allLayers.find(l=>l.id===e);if(!o)return{text:`错误:未找到图层,ID 为 ${e},不存在`};let a=t?.trim()?t:"1=1",n=o.createQuery();n.where=a;try{let{extent:l,count:i}=await o.queryExtent(n);if(i===0)return{text:`未找到要素,图层为 ${o.title},匹配条件:${a}`,where:a};if(l)await r.goTo(l);else return{text:`错误:无法确定以下要素的范围:${o.title}`,where:a};let u={layerId:e,layerTitle:o.title??e,where:a,count:i};return{text:`已缩放到 ${i} 个要素,所在图层:${o.title},匹配条件:${a}`,where:a,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(l){return console.error("goToFeatures 执行错误:",l),{text:`错误:${l instanceof Error?l.message:"未知错误"}`,where:a}}}async function Kt({layerId:e,where:t},r){let{mapView:o}=k(r);return await Ut(e,t,o)}var Wt=N.object({layerId:N.string().describe("要缩放到的图层 layerId。"),where:N.string().describe("所选图层 query.where 使用的 GeoScene SQL-92 WHERE 表达式。只能使用该图层字段,返回布尔过滤表达式,例如比较、LIKE、IN、BETWEEN、IS NULL、AND/OR/NOT。不得包含子查询、嵌套 SELECT、JOIN、GROUP BY、HAVING、ORDER BY 或分号。")}),Zi=y(Kt,{name:"goToFeatures",description:"定位到指定 layerId 中符合过滤条件的要素。",schema:Wt});async function Ht(e){let t=new lt({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await e.goTo(t),{text:"已缩放到全球范围"}}async function Jt(e,t){let{mapView:r}=k(t);return await Ht(r)}var Zt=N.object({}),Yi=y(Jt,{name:"goToFullExtent",description:"使用 GeoScene 地理编码服务将地图缩放到全球范围。",schema:Zt});async function Yt(e){let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;if(t)await e.goTo(t);else throw new Error("未定义初始范围");return{text:"已返回初始范围"}}async function Xt(e,t){let{mapView:r}=k(t);return await Yt(r)}var er=s.object({}),Xi=y(Xt,{name:"goToHomeExtent",description:"返回 WebMap 初始视图范围",schema:er});async function tr(e,t){await t.when();let r=t.map?.allLayers.find(a=>a.id===e);if(!r)return console.warn(`[goToLayer] 未找到匹配的 FeatureLayer:${e}`),{text:`未找到图层:${e}`};let o;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&t.map?.activeLinkChartLayer?o=t.map.diagramNodesExtent:o=r.fullExtent,o?(await t.goTo(o),r.visible=!0,{text:`已缩放到:${r.title??""}`}):{text:"图层未定义范围,无法缩放到该图层。"}}async function rr({layerId:e},t){let{mapView:r}=k(t);return await tr(e,r)}var or=N.object({layerId:N.string().describe("要定位的图层 ID")}),es=y(rr,{name:"goToLayer",description:"将地图缩放到最佳匹配图层的完整范围。",schema:or});async function ar(e,t){return await t.goTo({scale:e}),{text:`已缩放到:${e}`}}async function nr({scale:e},t){let{mapView:r}=k(t);return await ar(e,r)}var ir=s.object({scale:s.number().describe("目标视图的地图比例尺。")}),ts=y(nr,{name:"goToScale",description:"定位到指定比例尺。",schema:ir});async function sr(e,t,r){let o={target:new De({longitude:e.longitude,latitude:e.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(o.zoom=r.zoom),r?.scale!==void 0&&(o.scale=r.scale),await t.goTo(o),{text:`已定位到:${[`(${e.latitude}\xB0, ${e.longitude}\xB0)`,r?.zoom!==void 0?`缩放级别 ${r.zoom}`:"",r?.scale!==void 0?`比例尺 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function lr({center:e,zoom:t,scale:r},o){let{mapView:a}=k(o);return await sr(e,a,{zoom:t,scale:r})}var cr=s.object({center:s.object({longitude:s.number().describe("目标点的经度,即 x 坐标。"),latitude:s.number().describe("目标点的纬度,即 y 坐标。")}),zoom:s.number().optional().describe("缩放级别,数值越大,地图放得越大。"),scale:s.number().optional().describe("地图比例尺,可替代 zoom;比例尺分母越小,地图放得越大。")}),rs=y(lr,{name:"goToViewpoint",description:"定位到指定视点,可以组合 scale、center、zoom 等参数。",schema:cr});async function ur(e,t){return await t.goTo({zoom:e}),{text:`已缩放到:${e}`}}async function dr({zoom:e},t){let{mapView:r}=k(t);return await ur(e,r)}var pr=s.object({zoom:s.number().min(1).max(20).describe("目标视图的缩放级别。")}),os=y(dr,{name:"goToZoom",description:"定位到指定缩放级别。如果要求较笼统,例如“放大”,只调整到下一个适当级别;放大时增加级别,缩小时降低级别。",schema:pr}),_e=Object.assign({"../agents/geosceneKnowledge/prompts/geoscene_knowledge_current_lc_context.md":()=>import("./VDAF255D.js").then(e=>e.default),"../agents/geosceneKnowledge/prompts/geoscene_knowledge_current_map_context.md":()=>import("./BUTKUPXN.js").then(e=>e.default),"../agents/geosceneKnowledge/prompts/geoscene_knowledge_cypher_query_prompt.md":()=>import("./CU2TRUZQ.js").then(e=>e.default),"../agents/geosceneKnowledge/prompts/geoscene_knowledge_lucene_generation_prompt.md":()=>import("./53Z3R4OY.js").then(e=>e.default),"../agents/geosceneKnowledge/prompts/geoscene_knowledge_summarize_result_prompt.md":()=>import("./4BA4OUWC.js").then(e=>e.default),"../agents/geosceneKnowledge/prompts/geoscene_knowledge_tool_prompt_knowledge_tool_prompt.md":()=>import("./PTKZXFXB.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./NMWLJECU.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./5RQUSM3T.js").then(e=>e.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./VWMJ7HIK.js").then(e=>e.default),"../agents/help/prompts/help_prompt.md":()=>import("./N2SKXRLK.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./77GAVZIK.js").then(e=>e.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./AJKWCXDA.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./HJGF7W5O.js").then(e=>e.default)});async function Z(e){let t=Object.entries(_e).find(([r])=>r.endsWith(`/${e}.md`));if(!t)throw new Error(`未找到提示词:${e}
4
4
  可用提示词:
5
5
  ${Object.keys(_e).join(`
6
6
  `)}`);return await t[1]()}var mr=(e,t=300)=>{let r=e.replace(/\s+/gu," ").replace(/[*_`#>\-]/gu,"").trim();return r.length>t?`${r.slice(0,t)}...`:r},Ge=(e,t)=>{let r=e?.configurable?.services?.[t];if(r==null)throw new Error(`${t} 在 config.configurable.services 中不存在`);return r},as=(e,t)=>(r,o)=>{let a=o?.configurable?.services;for(let n of e)if(!a?.[n])throw new Error(`${t} 需要服务。${n} 可用。`);return r};async function hr(e){let{fields:t,layer:r,view:o,styleName:a,colorSchemeTags:n}=e,l;return n?l=ut({basemapTheme:await Re(o),geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,8)})[0]:l=dt({basemapTheme:await Re(o),geometryType:r.geometryType,numColors:Math.min(t.length,8)}).primaryScheme,{layer:r,view:o,attributes:t.map(i=>({field:i,label:r.fields.find(u=>u.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:a.includes("Size"),pieChartScheme:l}}async function fr(e){return await ct(e)}async function yr({geosceneMap:e,geosceneMapView:t,layerId:r,fields:o,colorSchemes:a,includeSize:n}){let l=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`未找到图层,ID:${r}`;let u={styleName:n?"chart-size":"chart",fields:o,layer:i,view:l,colorSchemeTags:a};try{let c=await hr(u),d=await fr(c);return i.renderer=d.renderer,i.visible=!0,`已为图层应用图表渲染器:${i.title??i.id},使用字段 ${o.join(", ")}`}catch(c){return`应用图表渲染器失败:${c instanceof Error?c.message:String(c)}`}}var gr=["mapView"];function I(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("LayerStylingAgent 缺少上下文");let r=gr.filter(o=>!(o in t));if(r.length)throw new Error(`LayerStylingAgent 缺少上下文:${r.join(", ")}`);return t}async function wr({layerId:e,fields:t,colorSchemes:r,includeSize:o},a){let{mapView:n}=I(a);return await x({type:"show-legend",data:{layerIds:[e]}},a),await yr({geosceneMap:n.map,geosceneMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:o})}var br=s.object({layerId:s.string().describe("要应用图表渲染器的图层 ID"),fields:s.array(s.string()).describe("图表使用的多个数值字段"),colorSchemes:s.array(s.string()).optional().describe("可选的配色方案标签"),includeSize:s.boolean().optional().describe("是否按总量改变图表大小(chart-size)")}),ns=y(wr,{name:"chart",description:`标签:图表
@@ -238,7 +238,7 @@ const se = async (t, e) => {
238
238
  } catch (a) {
239
239
  throw await n({ text: "获取统计信息失败" }, e), new Error(`获取统计信息失败:${a instanceof Error ? a.message : String(a)}`);
240
240
  }
241
- }, M = 0.5, re = 10, oe = async (t, e) => {
241
+ }, M = 0.4, re = 50, oe = async (t, e) => {
242
242
  try {
243
243
  await n({ text: "正在通过相似度搜索字段" }, e);
244
244
  const a = f(e, "fieldSearch"), d = f(e, "layersAndFieldsRegistry"), l = f(e, "embeddingCache"), s = await a.searchFields({
@@ -39,7 +39,8 @@ const getPortalUrl = () => {
39
39
  const n = s[0];
40
40
  if (!n.name || !n.endpoint)
41
41
  throw new Error(`已激活的 ${e} 模型缺少 name 或 endpoint。`);
42
- return { ...n, endpoint: new URL(n.endpoint, new URL(t).origin).href };
42
+ const endpoint =new URL(n.endpoint.replace(/^\/+/, ""), `${getPortalUrl()}/`).href;
43
+ return { ...n, endpoint };
43
44
  }, ie = async () => (await U("embedding")).endpoint, h = (e, t) => t, P = (e, t) => ({
44
45
  ...e,
45
46
  ...t
@@ -263,7 +263,7 @@ async function ne(t, e, r, s) {
263
263
  };
264
264
  return await new Promise((c) => {
265
265
  const d = (a) => {
266
- a.data.requestId === n && c(a.data.results.filter((item) => item.score >= r));
266
+ a.data.requestId === n && c(a.data.results);
267
267
  };
268
268
  e.addEventListener("message", d, { once: !0 }), e.postMessage(i);
269
269
  });
@@ -6,8 +6,8 @@
6
6
  if (opener) {
7
7
  if (location.hash) {
8
8
  // opener.console.log("oauth callback href:", location.href);
9
- if (typeof opener.require === "function" && opener.require("esri/kernel")) {
10
- opener.require("esri/kernel").id.setOAuthResponseHash(location.hash);
9
+ if (typeof opener.require === "function" && opener.require("geoscene/kernel")) {
10
+ opener.require("geoscene/kernel").id.setOAuthResponseHash(location.hash);
11
11
  } else {
12
12
  opener.dispatchEvent(new CustomEvent("arcgis:auth:hash", { detail: location.hash }));
13
13
  }
package/package.json CHANGED
@@ -1,67 +1,67 @@
1
- {
2
- "name": "@geoscene/ai-components",
3
- "version": "5.1.15",
4
- "description": "GeoScene AI Components",
5
- "type": "module",
6
- "main": "./dist/index.js",
7
- "module": "./dist/index.js",
8
- "types": "./dist/index.d.ts",
9
- "exports": {
10
- ".": "./dist/index.js",
11
- "./loader": "./dist/loader.js",
12
- "./agent-utils/index.js": "./dist/agent-utils/index.js",
13
- "./agent-utils/BaseAgent.js": "./dist/agent-utils/BaseAgent.js",
14
- "./agent-utils/FunctionAgent.js": "./dist/agent-utils/FunctionAgent.js",
15
- "./agent-utils/LLMAgent.js": "./dist/agent-utils/LLMAgent.js",
16
- "./agent-utils/WorkflowAgent.js": "./dist/agent-utils/WorkflowAgent.js",
17
- "./agent-utils/tools/FunctionTool.js": "./dist/agent-utils/tools/FunctionTool.js",
18
- "./agent-utils/workflows/ConditionalWorkflow.js": "./dist/agent-utils/workflows/ConditionalWorkflow.js",
19
- "./agent-utils/workflows/LoopWorkflow.js": "./dist/agent-utils/workflows/LoopWorkflow.js",
20
- "./agent-utils/workflows/ParallelWorkflow.js": "./dist/agent-utils/workflows/ParallelWorkflow.js",
21
- "./agent-utils/workflows/RouterWorkflow.js": "./dist/agent-utils/workflows/RouterWorkflow.js",
22
- "./agent-utils/workflows/SequentialWorkflow.js": "./dist/agent-utils/workflows/SequentialWorkflow.js",
23
- "./agent-utils/workflows/SwitchWorkflow.js": "./dist/agent-utils/workflows/SwitchWorkflow.js",
24
- "./agent-utils/middlewares/middleware.js": "./dist/agent-utils/middlewares/middleware.js",
25
- "./agent-utils/middlewares/humanInTheLoop.js": "./dist/agent-utils/middlewares/humanInTheLoop.js",
26
- "./agent-utils/middlewares/trace.js": "./dist/agent-utils/middlewares/trace.js",
27
- "./agent-utils/middlewares/types.js": "./dist/agent-utils/middlewares/types.js",
28
- "./utils/index.js": "./dist/utils/index.js",
29
- "./package.json": "./package.json",
30
- "./components/*/customElement": "./dist/components/*/customElement.js",
31
- "./components/*": "./dist/components/*/index.js",
32
- "./types/*": "./dist/types/*.d.ts",
33
- "./docs/*": "./dist/docs/*",
34
- "./cdn/index.css": "./dist/cdn/main.css",
35
- "./main.css": "./dist/cdn/main.css"
36
- },
37
- "files": [
38
- "dist/"
39
- ],
40
- "license": "SEE LICENSE IN LICENSE.md",
41
- "dependencies": {
42
- "@geoscene/geoscene-html-sanitizer": "~4.1.0",
43
- "@langchain/core": "^1.1.39",
44
- "@langchain/langgraph": "^1.2.6",
45
- "@langchain/openai": "^1.4.3",
46
- "langchain": "^1.3.1",
47
- "lit": "^3.3.0",
48
- "marked": "~18.0.5",
49
- "tslib": "^2.8.1",
50
- "zod": "^4.3.6",
51
- "@geoscene/toolkit": "5.1.13",
52
- "@geoscene/lumina": "5.1.13"
53
- },
54
- "peerDependencies": {
55
- "@geoscene/core": "^5.1.0",
56
- "@geoscene/calcite-components": "^5.1.1",
57
- "@geoscene/map-components": "~5.1.13"
58
- },
59
- "css.customData": [
60
- "dist/docs/vscode.css-custom-data.json"
61
- ],
62
- "customElements": "dist/docs/api.json",
63
- "html.customData": [
64
- "dist/docs/vscode.html-custom-data.json"
65
- ],
66
- "web-types": "dist/docs/web-types.json"
1
+ {
2
+ "name": "@geoscene/ai-components",
3
+ "version": "5.1.17",
4
+ "description": "GeoScene AI Components",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": "./dist/index.js",
11
+ "./loader": "./dist/loader.js",
12
+ "./agent-utils/index.js": "./dist/agent-utils/index.js",
13
+ "./agent-utils/BaseAgent.js": "./dist/agent-utils/BaseAgent.js",
14
+ "./agent-utils/FunctionAgent.js": "./dist/agent-utils/FunctionAgent.js",
15
+ "./agent-utils/LLMAgent.js": "./dist/agent-utils/LLMAgent.js",
16
+ "./agent-utils/WorkflowAgent.js": "./dist/agent-utils/WorkflowAgent.js",
17
+ "./agent-utils/tools/FunctionTool.js": "./dist/agent-utils/tools/FunctionTool.js",
18
+ "./agent-utils/workflows/ConditionalWorkflow.js": "./dist/agent-utils/workflows/ConditionalWorkflow.js",
19
+ "./agent-utils/workflows/LoopWorkflow.js": "./dist/agent-utils/workflows/LoopWorkflow.js",
20
+ "./agent-utils/workflows/ParallelWorkflow.js": "./dist/agent-utils/workflows/ParallelWorkflow.js",
21
+ "./agent-utils/workflows/RouterWorkflow.js": "./dist/agent-utils/workflows/RouterWorkflow.js",
22
+ "./agent-utils/workflows/SequentialWorkflow.js": "./dist/agent-utils/workflows/SequentialWorkflow.js",
23
+ "./agent-utils/workflows/SwitchWorkflow.js": "./dist/agent-utils/workflows/SwitchWorkflow.js",
24
+ "./agent-utils/middlewares/middleware.js": "./dist/agent-utils/middlewares/middleware.js",
25
+ "./agent-utils/middlewares/humanInTheLoop.js": "./dist/agent-utils/middlewares/humanInTheLoop.js",
26
+ "./agent-utils/middlewares/trace.js": "./dist/agent-utils/middlewares/trace.js",
27
+ "./agent-utils/middlewares/types.js": "./dist/agent-utils/middlewares/types.js",
28
+ "./utils/index.js": "./dist/utils/index.js",
29
+ "./package.json": "./package.json",
30
+ "./components/*/customElement": "./dist/components/*/customElement.js",
31
+ "./components/*": "./dist/components/*/index.js",
32
+ "./types/*": "./dist/types/*.d.ts",
33
+ "./docs/*": "./dist/docs/*",
34
+ "./cdn/index.css": "./dist/cdn/main.css",
35
+ "./main.css": "./dist/cdn/main.css"
36
+ },
37
+ "files": [
38
+ "dist/"
39
+ ],
40
+ "license": "SEE LICENSE IN LICENSE.md",
41
+ "dependencies": {
42
+ "@geoscene/geoscene-html-sanitizer": "~4.1.0",
43
+ "@langchain/core": "^1.1.39",
44
+ "@langchain/langgraph": "^1.2.6",
45
+ "@langchain/openai": "^1.4.3",
46
+ "langchain": "^1.3.1",
47
+ "lit": "^3.3.0",
48
+ "marked": "~18.0.5",
49
+ "tslib": "^2.8.1",
50
+ "zod": "^4.3.6",
51
+ "@geoscene/toolkit": "^5.1.13",
52
+ "@geoscene/lumina": "^5.1.13"
53
+ },
54
+ "peerDependencies": {
55
+ "@geoscene/core": "^5.1.0",
56
+ "@geoscene/calcite-components": "^5.1.1",
57
+ "@geoscene/map-components": "~5.1.13"
58
+ },
59
+ "css.customData": [
60
+ "dist/docs/vscode.css-custom-data.json"
61
+ ],
62
+ "customElements": "dist/docs/api.json",
63
+ "html.customData": [
64
+ "dist/docs/vscode.html-custom-data.json"
65
+ ],
66
+ "web-types": "dist/docs/web-types.json"
67
67
  }