@arcgis/portal-components 5.1.13 → 5.1.15

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,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import a from"./XR4PMNYP.js";import"./BCUEYBNI.js";import{a as ao,b as pl}from"./4ISLOZQ3.js";import{a as dl}from"./JVS4CSZH.js";import"./32NYU4WG.js";import{I as oo,J as so,K as ul,Q as cl,h as sl,j as Or,m as al,v as il,y as ll}from"./TVFC2BH2.js";import{$ as De,$a as N,Aa as bt,Ba as qe,Ca as us,D as hl,Da as Ml,E as Xe,Ea as Pl,F as gl,Fa as cs,G as ts,Ga as Rl,H as xa,Ha as Rr,I as Aa,Ia as Ca,J as rs,Ja as Nl,K as Ia,Ka as $l,L as lo,La as po,M as U,Ma as Ll,N as va,Na as mo,O as yl,Oa as fo,P as R,Pa as I,Q as yt,Qa as D,R as et,Ra as Ea,S as ns,T as _l,U as wl,V as Ta,W as Ae,X as os,Y as bl,Z as ss,_ as xl,a as he,aa as uo,b as B,ba as Al,ca as Sa,da as Il,ea as co,f as ge,fa as _t,fb as jl,g as ml,ga as vl,ha as Tl,ia as Sl,j as re,ja as Mr,k as ue,ka as kl,la as tt,ma as Cl,mb as xt,na as wt,nb as Oa,oa as as,ob as Ie,pa as rt,q as es,qa as is,qb as ho,ra as El,rb as ds,sa as ls,sb as go,t as fl,ta as Ol,tb as ps,u as io,ua as q,ub as ye,va as x,wa as ka,xa as Fe,ya as Pr,za as Ce}from"./YJK6JAPE.js";import"./CFDTXKJ6.js";export default $arcgis.t(([PU,NU,Dd,Xh,eg,fg,FU,UU,Y2,zb,Yd,Cr,Di,sp,,Xd,_g,{addressToLocations:wg},bg,xg,ap,{createRenderer:Ag},{getSchemesByTag:Ig,getSchemes:vg},{getBackgroundColorTheme:ep},{createAgeRenderer:Tg,createContinuousRenderer:Sg},{getSchemesByTag:Ji},{createContinuousRenderer:kg},{createRenderer:Cg},{getSchemesByTag:Eg},{createRenderer:Og},{getSchemesByTag:Mg},{createRenderer:Pg},{getSchemesByTag:Rg},{createRenderer:Ng},{getSchemesByTag:$g},{createAgeRenderer:Lg,createContinuousRenderer:jg},{createRenderer:zg},{getSchemesByTag:Dg},Fg,ip,lp,{formatDateOnly:qg,convertDateFormatToIntlOptions:ca,formatTimeOnly:Ug,formatDate:tp},Bg,Kg,Wg,Vg,Gg,up,,{fetchKnowledgeGraph:rp,executeQueryStreaming:Hg,executeSearchStreaming:Jg},Zg,{getBindParametersFromCypherQuery:Qg},,,,,,,,,,,,,,,,,,,,,,,,,YW,e2,,,,,,,,,,,,,Db,Ap,{a:zl,b:Dl,c:Fl,d:ql,e:Ul}])=>{var d=I;async function Ma(t,e,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
2
+ import a from"./XR4PMNYP.js";import"./BCUEYBNI.js";import{a as ao,b as pl}from"./4ISLOZQ3.js";import{a as dl}from"./F4HCVBRU.js";import"./OWQLFGIX.js";import{I as oo,J as so,K as ul,Q as cl,h as sl,j as Or,m as al,v as il,y as ll}from"./BLB6A5XP.js";import{$ as De,$a as N,Aa as bt,Ba as qe,Ca as us,D as hl,Da as Ml,E as Xe,Ea as Pl,F as gl,Fa as cs,G as ts,Ga as Rl,H as xa,Ha as Rr,I as Aa,Ia as Ca,J as rs,Ja as Nl,K as Ia,Ka as $l,L as lo,La as po,M as U,Ma as Ll,N as va,Na as mo,O as yl,Oa as fo,P as R,Pa as I,Q as yt,Qa as D,R as et,Ra as Ea,S as ns,T as _l,U as wl,V as Ta,W as Ae,X as os,Y as bl,Z as ss,_ as xl,a as he,aa as uo,b as B,ba as Al,ca as Sa,da as Il,ea as co,f as ge,fa as _t,fb as jl,g as ml,ga as vl,ha as Tl,ia as Sl,j as re,ja as Mr,k as ue,ka as kl,la as tt,ma as Cl,mb as xt,na as wt,nb as Oa,oa as as,ob as Ie,pa as rt,q as es,qa as is,qb as ho,ra as El,rb as ds,sa as ls,sb as go,t as fl,ta as Ol,tb as ps,u as io,ua as q,ub as ye,va as x,wa as ka,xa as Fe,ya as Pr,za as Ce}from"./YJK6JAPE.js";import"./CFDTXKJ6.js";export default $arcgis.t(([NU,LU,Dd,Xh,eg,tg,hg,UU,KU,eV,Db,Yd,Cr,Xd,Di,sp,,wg,{addressToLocations:bg},xg,Ag,ap,{createRenderer:Ig},{getSchemesByTag:vg,getSchemes:Tg},{getBackgroundColorTheme:ep},{createAgeRenderer:Sg,createContinuousRenderer:kg},{getSchemesByTag:Ji},{createContinuousRenderer:Cg},{createRenderer:Eg},{getSchemesByTag:Og},{createRenderer:Mg},{getSchemesByTag:Pg},{createRenderer:Rg},{getSchemesByTag:Ng},{createRenderer:$g},{getSchemesByTag:Lg},{createAgeRenderer:jg,createContinuousRenderer:zg},{createRenderer:Dg},{getSchemesByTag:Fg},qg,ip,lp,{formatDateOnly:Ug,convertDateFormatToIntlOptions:ca,formatTimeOnly:Bg,formatDate:tp},Kg,Wg,Vg,Gg,Hg,up,,{fetchKnowledgeGraph:rp,executeQueryStreaming:Jg,executeSearchStreaming:Zg},Qg,{getBindParametersFromCypherQuery:Yg},,,,,,,,,,,,,,,,,,,,,,,,,e2,r2,,,,,,,,,,,,,Fb,Ap,{a:zl,b:Dl,c:Fl,d:ql,e:Ul}])=>{var d=I;async function Ma(t,e,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
3
3
 
4
4
  If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
5
5
 
@@ -32,7 +32,7 @@ To fix this, either:
32
32
  ${s.error.issues[0]?.path.join(".")}: "value"
33
33
  })`)}return r}function su(t){let e={messages:I.custom(()=>[]),structuredResponse:I.any().optional()};if(!t)return I.object(e);let r;if(Ie.isInstance(t)){r={};for(let[o,s]of Object.entries(t.fields))xt.isInstance(s)?r[o]=s.inputSchema||s.valueSchema:r[o]=s}else r=is(t);let n={...e};for(let[o,s]of Object.entries(r))o.startsWith("_")?n[o]=s.optional():n[o]=s;return I.object(n)}function au(t){if(rt(t))return El(t);if(Ie.isInstance(t)){let e={};for(let[r,n]of Object.entries(t.fields)){let o;xt.isInstance(n)?o=n.inputSchema||n.valueSchema:o=n,e[r]=Mr(o)?o.optional():I.any().optional()}return I.object(e)}return I.object({})}function Oe(t){if(t){if(["model_request","tools",B].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return B;throw new Error(`Invalid jump target: ${t}, must be "model", "tools" or "end".`)}}function ws(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var $r=class extends Pr{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(t){super(),this.name=t.name??t.func.name,this.func=t.func,this.config=t.tags?{tags:t.tags}:void 0,this.recurse=t.recurse??this.recurse}getState(){return this.#e}setState(t){this.#e={...this.#e,...t}}async invoke(t,e){let r=De(this.config,e),n=await ss.runWithConfig(r,async()=>this.func(t,r));return Pr.isRunnable(n)&&this.recurse?await ss.runWithConfig(r,async()=>n.invoke(t,r)):(this.#e=n,n)}};function iu(t,e){let r,n;if(e==="inline")r=Xl,n=eu;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function o(s){return s.map(r)}return bt.from([qe.from(o),t,qe.from(n)])}function Vp(t){return R.isInstance(t)||ue(t)||typeof t=="object"&&t!==null&&"structuredResponse"in t&&"messages"in t}var ae="model_request",lu=class extends $r{#e;#r;constructor(t){super({name:t.name??"model",func:(e,r)=>this.#t(e,r)}),this.#e=t,this.#r=t.systemMessage}async#s(t,e=this.#e.responseFormat){if(!e)return;let r;Nr(t)?r=await t._getModelInstance():typeof t!="string"&&(r=t);let n=Hl(e,void 0,r);if(n.length!==0)return n.every(o=>o instanceof It)?{type:"native",strategy:n[0]}:{type:"tool",tools:n.filter(o=>o instanceof Ee).reduce((o,s)=>(o[s.name]=s,o),{})}}async#t(t,e){let r=t.messages.at(-1);if(r&&U.isInstance(r)&&r.name&&this.#e.shouldReturnDirect.has(r.name))return[new re({update:{messages:[]}})];let{response:n,lastAiMessage:o,collectedCommands:s}=await this.#a(t,e);if(typeof n=="object"&&n!==null&&"structuredResponse"in n&&"messages"in n){let{structuredResponse:u,messages:l}=n;return{messages:[...t.messages,...l],structuredResponse:u}}let a=[],i=R.isInstance(n)?n:o;return i&&(i.name=this.name,i.lc_kwargs.name=this.name,this.#o(t,i)?a.push(new re({update:{messages:[new R({content:"Sorry, need more steps to process this request.",name:this.name,id:i.id})]}})):a.push(new re({update:{messages:[i]}}))),ue(n)&&!s.includes(n)&&a.push(n),a.push(...s),a}#n(){if(typeof this.#e.model=="string")return At(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#a(t,e,r={}){let n=await this.#n(),o=e,s=this.#r,a=null,i=[],u=async m=>{_s(m.model);let g=await this.#s(m.model,m.responseFormat),y=await this.#c(m.model,m,g),A=[...s.text===""?[]:[s],...m.messages],C=ws(this.#e.signal,e.signal),h=await Al(y.invoke(A,{...e,signal:C}),C);if(a=h,g?.type==="native"){let j=g.strategy.parse(h);return j?{structuredResponse:j,messages:[h]}:h}if(!g||!h.tool_calls)return h;let b=h.tool_calls.filter(j=>j.name in g.tools);if(b.length===0)return h;if(b.length>1)return this.#l(h,b,g);let S=g.tools[b[0].name]?.options?.toolMessageContent;return this.#u(h,b[0],g,S??r.lastMessage)},l=this.#e.wrapModelCallHookMiddleware??[],c=u;for(let m=l.length-1;m>=0;m--){let[g,y]=l[m];if(g.wrapModelCall){let A=c,C=g,h=y;c=async b=>{let S=s,j=C.contextSchema?wt(C.contextSchema,o?.context||{}):o?.context,Q=Object.freeze({context:j,store:o.store,configurable:o.configurable,writer:o.writer,interrupt:o.interrupt,signal:o.signal}),G={...b,state:{...g.stateSchema?wt(au(g.stateSchema),t):{},...h(),messages:t.messages},runtime:Q},K=async z=>{s=S;let T=z.tools??[],E=new Map(this.#e.toolClasses.filter(Ht).map(fe=>[fe.name,fe])),F=T.filter(fe=>Ht(fe)&&!E.has(fe.name)),J=T.filter(fe=>{if(!Ht(fe))return!1;let ol=E.get(fe.name);return ol!=null&&ol!==fe});if(F.length>0&&!this.#e.middleware?.some(fe=>fe.wrapToolCall!=null))throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${C.name}": ${F.map(fe=>fe.name).join(", ")}. This is not supported unless a middleware provides a "wrapToolCall" handler to execute it.`);if(J.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${C.name}": ${J.map(fe=>fe.name).join(", ")}. This is not supported.`);let Z=z,$=z.systemPrompt!==s.text,W=z.systemMessage!==s;if($&&W)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");$&&(s=new Ae({content:[{type:"text",text:z.systemPrompt}]}),Z={...z,systemPrompt:s.text,systemMessage:s}),W&&(s=new Ae({...z.systemMessage}),Z={...z,systemPrompt:s.text,systemMessage:s});let Xo=await A(Z);return ue(Xo)&&a?(i.includes(Xo)||i.push(Xo),a):Xo};if(!C.wrapModelCall)return K(G);try{let z=await C.wrapModelCall(G,K);if(!Vp(z))throw new Error(`Invalid response from "wrapModelCall" in middleware "${C.name}": expected AIMessage or Command, got ${typeof z}`);return R.isInstance(z)?a=z:ue(z)&&i.push(z),z}catch(z){throw yo.wrap(z,C.name)}}}}s=this.#r;let p={model:n,responseFormat:this.#e.responseFormat,systemPrompt:s?.text,systemMessage:s,messages:t.messages,tools:this.#e.toolClasses,state:t,runtime:Object.freeze({context:o?.context,store:o.store,configurable:o.configurable,writer:o.writer,interrupt:o.interrupt,signal:o.signal})};return{response:await c(p),lastAiMessage:a,collectedCommands:i}}#l(t,e,r){let n=new gs(e.map(o=>o.name));return this.#i(n,t,e[0],r)}#u(t,e,r,n){let o=r.tools[e.name];try{let s=o.parse(e.args);return{structuredResponse:s,messages:[t,new U({tool_call_id:e.id??"",content:JSON.stringify(s),name:e.name}),new R(n??`Returning structured response: ${JSON.stringify(s)}`)]}}catch(s){return this.#i(s,t,e,r)}}async#i(t,e,r,n){let o=Object.values(n.tools).at(0)?.options?.handleError,s=r.id;if(!s)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(o===!1)throw t;if(o===void 0||typeof o=="boolean"&&o||Array.isArray(o)&&o.some(a=>a instanceof gs))return new re({update:{messages:[e,new U({content:t.message,tool_call_id:s})]},goto:ae});if(typeof o=="string")return new re({update:{messages:[e,new U({content:o,tool_call_id:s})]},goto:ae});if(typeof o=="function"){let a=await o(t);if(typeof a!="string")throw new Error("Error handler must return a string.");return new re({update:{messages:[e,new U({content:a,tool_call_id:s})]},goto:ae})}return new re({update:{messages:[e,new U({content:t.message,tool_call_id:s})]},goto:ae})}#o(t,e){let r=R.isInstance(e)&&e.tool_calls?.every(o=>this.#e.shouldReturnDirect.has(o.name)),n="remainingSteps"in t?t.remainingSteps:void 0;return!!(n&&(n<1&&r||n<2&&za(t.messages.at(-1))))}async#c(t,e,r){let n={},o=Object.values(r&&"tools"in r?r.tools:{}),s=[...e?.tools??this.#e.toolClasses,...o.map(u=>u.tool)],a=e?.toolChoice||(o.length>0?"any":void 0);if(r?.type==="native"){let u=e?.modelSettings?.strict??r?.strategy?.strict??!0,l={name:r.strategy.schema?.name??"extract",description:as(r.strategy.schema),schema:r.strategy.schema,strict:u};Object.assign(n,{response_format:{type:"json_schema",json_schema:l},outputConfig:{format:{type:"json_schema",schema:r.strategy.schema}},responseSchema:r.strategy.schema,ls_structured_output_format:{kwargs:{method:"json_schema"},schema:r.strategy.schema},strict:u})}let i=await ru(t,s,{...n,...e?.modelSettings,tool_choice:a});return this.#e.includeAgentName==="inline"?iu(i,this.#e.includeAgentName):i}getState(){let t=super.getState();return{messages:[],...t&&!ue(t)?t:{}}}};var uu=(t,e)=>`Error: ${t} is not a valid tool, try one of [${e.join(", ")}].`,we="tools",cu=t=>Array.isArray(t)&&t.every(Ia.isInstance),Gp=t=>typeof t=="object"&&t!=null&&"messages"in t&&cu(t.messages),Hp=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function Jp(t,e){return t instanceof ys?new U({content:t.message,tool_call_id:e.id,name:e.name}):new U({content:`${t}
34
34
  Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var du=class extends $r{tools;trace=!1;signal;handleToolErrors=Jp;wrapToolCall;constructor(t,e){let{name:r,tags:n,handleToolErrors:o,signal:s,wrapToolCall:a}=e??{};super({name:r,tags:n,func:(i,u)=>this.run(i,u)}),this.options=e,this.tools=t,this.handleToolErrors=o??this.handleToolErrors,this.signal=s,this.wrapToolCall=a}#e(t,e,r){if(io(t)||this.signal?.aborted||r&&this.handleToolErrors!==!0||!this.handleToolErrors)throw t;if(typeof this.handleToolErrors=="function"){let n=this.handleToolErrors(t,e);if(n&&U.isInstance(n))return n;throw t}else if(this.handleToolErrors)return new U({name:e.name,content:`${t}
35
- Please fix your mistakes.`,tool_call_id:e.id});throw t}async runTool(t,e,r){let n=e,o={context:n?.context,store:n?.store,configurable:n?.configurable,writer:n?.writer,interrupt:n?.interrupt,signal:n?.signal},s=this.tools.find(u=>u.name===t.name),a=async u=>{let{toolCall:l,tool:c}=u,p=c??this.tools.find(g=>g.name===l.name);if(p===void 0){let g=this.tools.map(y=>y.name);return new U({content:uu(l.name,g),tool_call_id:l.id,name:l.name,status:"error"})}let m=p;try{let g=await m.invoke({...l,type:"tool_call"},{...e,config:e,toolCallId:l.id,state:e.configurable?.__pregel_scratchpad?.currentTaskInput,signal:ws(this.signal,e.signal)});return U.isInstance(g)||ue(g)?g:new U({name:m.name,content:typeof g=="string"?g:JSON.stringify(g),tool_call_id:l.id})}catch(g){throw g instanceof yl?new ys(g,l):g}},i={toolCall:t,tool:s,state:r,runtime:o};if(this.wrapToolCall)try{return await this.wrapToolCall(i,a)}catch(u){return this.#e(u,t,!0)}if(!s){let u=this.tools.map(l=>l.name);return new U({content:uu(t.name,u),tool_call_id:t.id,name:t.name,status:"error"})}try{return await a(i)}catch(u){return this.#e(u,t,!1)}}async run(t,e){let r;if(Hp(t)){let{lg_tool_call:s,jumpTo:a,...i}=t;r=[await this.runTool(t.lg_tool_call,e,i)]}else{let s;if(cu(t))s=t;else if(Gp(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(R.isInstance(l)){i=l;break}}if(!R.isInstance(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e,t))??[])}if(!r.some(ue))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)ue(s)?s.graph===re.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>Zp(a))?o?o.goto.push(...s.goto):o=new re({graph:re.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};function Zp(t){return t instanceof ge}var Qp=class{},Yp=class{},St=class extends $r{#e;constructor(t,e){super(t),this.#e=e}async invokeMiddleware(t,e){let r={};if(this.middleware.contextSchema){let u=this.middleware.contextSchema?.shape;if(u){let l={},c=e?.context||{};for(let p of Object.keys(u))p in c&&(l[p]=c[p]);r=wt(this.middleware.contextSchema,l)}}let n={...this.#e.getState(),...t,messages:t.messages},o={context:r,store:e?.store,configurable:e?.configurable,writer:e?.writer,interrupt:e?.interrupt,signal:e?.signal},s=await this.runHook(n,Object.freeze(Object.assign(new Yp,{...o,context:Object.freeze(Object.assign(new Qp,r))})));if(!s)return{jumpTo:void 0};let a,i;if(this.name?.startsWith("BeforeAgentNode_")?(a=Ue(this.middleware.beforeAgent),i="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(a=Ue(this.middleware.beforeModel),i="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(a=Ue(this.middleware.afterAgent),i="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(a=Ue(this.middleware.afterModel),i="afterModel.canJumpTo"),typeof s.jumpTo=="string"&&!a?.includes(s.jumpTo)){let u=a&&a.length>0?`must be one of: ${a?.join(", ")}.`:i?`no ${i} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${s.jumpTo}, ${u}.`)}if(typeof s=="object"&&"type"in s){if(s.type==="terminate"){if(s.error)throw s.error;return{...n,...s.result||{},jumpTo:s.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(s)}`)}return{...n,...s,jumpTo:s.jumpTo}}get nodeOptions(){return{input:su(this.middleware.stateSchema)}}};var pu=class extends St{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(t,e){super({name:`BeforeAgentNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return vt(this.middleware.beforeAgent)(t,e)}};var mu=class extends St{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(t,e){super({name:`BeforeModelNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return vt(this.middleware.beforeModel)(t,e)}};var fu=class extends St{lc_namespace=["langchain","agents","afterModelNodes"];constructor(t,e){super({name:`AfterModelNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return vt(this.middleware.afterModel)(t,e)}};var hu=class extends St{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(t,e){super({name:`AfterAgentNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return vt(this.middleware.afterAgent)(t,e)}};var gu=class{#e=new Map;addNode(t,e){this.#e.set(t.name,[...this.#e.get(t.name)??[],e])}getState(t){let e=(this.#e.get(t)??[]).reduce((r,n)=>({...r,...n.getState()??{}}),{});return delete e.jumpTo,e}};var yu=class _u{#e;#r="v2";#s;#t=new gu;#n;constructor(e,r){if(this.options=e,this.#n=De(r??{},{metadata:{ls_integration:"langchain_create_agent"}}),e.name&&(this.#n=De(this.#n,{metadata:{lc_agent_name:e.name}})),this.#r=e.version??this.#r,!e.model)throw new Error("`model` option is required to create an agent.");typeof e.model!="string"&&_s(e.model);let n=this.options.middleware?.filter(T=>T.tools).flatMap(T=>T.tools)??[],o=[...e.tools??[],...n],s=new Set(o.filter(Ht).filter(T=>"returnDirect"in T&&T.returnDirect).map(T=>T.name)),a=!!this.options.middleware?.some(T=>T.wrapModelCall),{state:i,input:u,output:l}=Ql(this.options.responseFormat!==void 0||a,this.options.stateSchema,this.options.middleware),c=new ye(i,{input:u,output:l,context:this.options.contextSchema}),p=[],m=[],g=[],y=[],A=[];this.#s=new lu({model:this.options.model,systemMessage:tu(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:o,shouldReturnDirect:s,signal:this.options.signal,wrapModelCallHookMiddleware:A});let C=new Set,h=this.options.middleware??[];for(let T=0;T<h.length;T++){let E,F,J,Z,$=h[T];if(C.has($.name))throw new Error(`Middleware ${$.name} is defined multiple times`);if(C.add($.name),$.beforeAgent){E=new pu($,{getState:()=>this.#t.getState($.name)}),this.#t.addNode($,E);let W=`${$.name}.before_agent`;p.push({index:T,name:W,allowed:Ue($.beforeAgent)}),c.addNode(W,E,E.nodeOptions)}if($.beforeModel){F=new mu($,{getState:()=>this.#t.getState($.name)}),this.#t.addNode($,F);let W=`${$.name}.before_model`;m.push({index:T,name:W,allowed:Ue($.beforeModel)}),c.addNode(W,F,F.nodeOptions)}if($.afterModel){J=new fu($,{getState:()=>this.#t.getState($.name)}),this.#t.addNode($,J);let W=`${$.name}.after_model`;g.push({index:T,name:W,allowed:Ue($.afterModel)}),c.addNode(W,J,J.nodeOptions)}if($.afterAgent){Z=new hu($,{getState:()=>this.#t.getState($.name)}),this.#t.addNode($,Z);let W=`${$.name}.after_agent`;y.push({index:T,name:W,allowed:Ue($.afterAgent)}),c.addNode(W,Z,Z.nodeOptions)}$.wrapModelCall&&A.push([$,()=>this.#t.getState($.name)])}c.addNode(ae,this.#s);let b=h.some(T=>T.wrapToolCall),S=o.filter(Ht);if(S.length>0||b){let T=new du(S,{signal:this.options.signal,wrapToolCall:nu(h)});c.addNode(we,T)}let j;p.length>0?j=p[0].name:m.length>0?j=m[0].name:j=ae;let Q=m.length>0?m[0].name:ae,G=y.length>0?y[y.length-1].name:B;c.addEdge(he,j);let K=S.length>0||b;for(let T=0;T<p.length;T++){let E=p[T],F=E.name,J=T===p.length-1?Q:p[T+1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(W=>Oe(W)).filter(W=>W!=="tools"||K),$=Array.from(new Set([J,...Z.map(W=>W===B?G:W)]));c.addConditionalEdges(F,this.#c(S,J,G,K),$)}else c.addEdge(F,J)}for(let T=0;T<m.length;T++){let E=m[T],F=E.name,J=T===m.length-1?ae:m[T+1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(W=>Oe(W)).filter(W=>W!=="tools"||K),$=Array.from(new Set([J,...Z]));c.addConditionalEdges(F,this.#p(S,J,K),$)}else c.addEdge(F,J)}let z=g.at(-1);if(g.length>0&&z)c.addEdge(ae,z.name);else{let T=this.#a(S,!1,K).map(E=>E===B?G:E);T.length===1?c.addEdge(ae,T[0]):c.addConditionalEdges(ae,this.#u(G),T)}for(let T=g.length-1;T>0;T--){let E=g[T],F=E.name,J=g[T-1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(W=>Oe(W)).filter(W=>W!=="tools"||K),$=Array.from(new Set([J,...Z]));c.addConditionalEdges(F,this.#o(S,E.allowed,J,K),$)}else c.addEdge(F,J)}if(g.length>0){let T=g[0],E=T.name,F=this.#a(S,!0,K).filter($=>$!=="tools"||K),J=!!(T.allowed&&T.allowed.length>0),Z=F.map($=>$===B?G:$);c.addConditionalEdges(E,this.#i(S,J,G,K),Z)}for(let T=y.length-1;T>0;T--){let E=y[T],F=E.name,J=y[T-1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(W=>Oe(W)).filter(W=>W!=="tools"||K),$=Array.from(new Set([J,...Z]));c.addConditionalEdges(F,this.#o(S,E.allowed,J,K),$)}else c.addEdge(F,J)}if(y.length>0){let T=y[0],E=T.name;if(T.allowed&&T.allowed.length>0){let F=T.allowed.map(Z=>Oe(Z)).filter(Z=>Z!=="tools"||K),J=Array.from(new Set([B,...F]));c.addConditionalEdges(E,this.#o(S,T.allowed,B,K),J)}else c.addEdge(E,B)}if(K){let T=Q;s.size>0?c.addConditionalEdges(we,this.#l(s,G,T),[T,G]):c.addEdge(we,T)}this.#e=c.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}get checkpointer(){return this.#e.checkpointer}set checkpointer(e){this.#e.checkpointer=e}get store(){return this.#e.store}set store(e){this.#e.store=e}withConfig(e){return new _u(this.options,De(this.#n,e))}#a(e,r=!1,n=e.length>0){let o=[];return n&&o.push(we),r&&o.push(ae),o.push(B),o}#l(e,r,n){return o=>{let s=o.messages,a=s[s.length-1];return U.isInstance(a)&&a.name&&e.has(a.name)?this.options.responseFormat?n:r:n}}#u(e=B){return r=>{let n=r.messages.at(-1);if(!R.isInstance(n)||!n.tool_calls||n.tool_calls.length===0||n.tool_calls.every(s=>s.name.startsWith("extract-")))return e;if(this.#r==="v1")return we;let o=n.tool_calls.filter(s=>!s.name.startsWith("extract-"));return o.length===0?e:o.map(s=>new ge(we,{...r,lg_tool_call:s}))}}#i(e,r,n,o=e.length>0){let s=!!this.options.responseFormat;return a=>{let i=a,u=i.messages,l=u.at(-1);if(R.isInstance(l)&&(!l.tool_calls||l.tool_calls.length===0))return n;if(r&&i.jumpTo){let h=Oe(i.jumpTo);return h===B?n:h==="tools"?o?new ge(we,{...a,jumpTo:void 0}):n:new ge(ae,{...a,jumpTo:void 0})}let c=u.filter(U.isInstance),p=u.filter(R.isInstance).at(-1),m=p?.tool_calls?.filter(h=>!c.some(b=>b.tool_call_id===h.id));if(m&&m.length>0)return this.#r==="v1"?we:m.map(h=>new ge(we,{...a,lg_tool_call:h}));let g=p?.tool_calls?.some(h=>h.name.startsWith("extract-"));if(m&&m.length===0&&!g&&s)return ae;if(!R.isInstance(l)||!l.tool_calls||l.tool_calls.length===0)return n;let y=l.tool_calls.every(h=>h.name.startsWith("extract-")),A=l.tool_calls.some(h=>!h.name.startsWith("extract-"));if(y||!A)return n;if(this.#r==="v1")return we;let C=l.tool_calls.filter(h=>!h.name.startsWith("extract-"));return C.length===0?n:C.map(h=>new ge(we,{...a,lg_tool_call:h}))}}#o(e,r,n,o=e.length>0){let s=new Set(r.map(a=>Oe(a)));return a=>{let i=a;if(i.jumpTo){let u=Oe(i.jumpTo);if(u===B&&s.has(B))return B;if(u==="tools"&&s.has("tools"))return o?new ge(we,{...a,jumpTo:void 0}):B;if(u==="model_request"&&s.has("model_request"))return new ge(ae,{...a,jumpTo:void 0})}return n}}#c(e,r,n,o=e.length>0){return s=>{let a=s;if(!a.jumpTo)return r;let i=Oe(a.jumpTo);return i===B?n:i==="tools"?o?new ge(we,{...s,jumpTo:void 0}):n:new ge(ae,{...s,jumpTo:void 0})}}#p(e,r,n=e.length>0){return o=>{let s=o;if(!s.jumpTo)return r;let a=Oe(s.jumpTo);return a===B?B:a==="tools"?n?new ge(we,{...o,jumpTo:void 0}):B:new ge(ae,{...o,jumpTo:void 0})}}async#d(e,r){if(!this.options.middleware||this.options.middleware.length===0||e instanceof re||!e)return e;let n=await ou(this.options.middleware,e),o={...(await this.#e.getState(r).catch(()=>({values:{}}))).values,...e};if(!o)return o;for(let[s,a]of Object.entries(n))s in o||(o[s]=a);return o}async invoke(e,r){let n=De(this.#n,r),o=await this.#d(e,n);return this.#e.invoke(o,n)}async stream(e,r){let n=De(this.#n,r),o=await this.#d(e,n);return this.#e.stream(o,n)}async drawMermaidPng(e){let r=await(await(await this.#e.getGraphAsync()).drawMermaidPng(e)).arrayBuffer();return new Uint8Array(r)}async drawMermaid(e){return(await this.#e.getGraphAsync()).drawMermaid(e)}streamEvents(e,r,n){let o=De(this.#n,r);return this.#e.streamEvents(e,{...o,version:r?.version??"v2"},n)}getGraphAsync(e){return this.#e.getGraphAsync(e)}getState(e,r){return this.#e.getState(e,r)}getStateHistory(e,r){return this.#e.getStateHistory(e,r)}getSubgraphs(e,r){return this.#e.getSubgraphs(e,r)}getSubgraphsAsync(e,r){return this.#e.getSubgraphsAsync(e,r)}updateState(e,r,n){return this.#e.updateState(e,r,n)}get builder(){return this.#e.builder}};function wo(t){return new yu(t)}var Xp=x.function().args(x.custom(),x.custom(),x.custom()).returns(x.union([x.string(),x.promise(x.string())])),em=["approve","edit","reject"],tm=x.enum(em),rm=x.object({allowedDecisions:x.array(tm),description:x.union([x.string(),Xp]).optional(),argsSchema:x.record(x.any()).optional()}),vv=x.object({interruptOn:x.record(x.union([x.boolean(),rm])).optional(),descriptionPrefix:x.string().default("Tool execution requires approval")});var am=`<role>
35
+ Please fix your mistakes.`,tool_call_id:e.id});throw t}async runTool(t,e,r){let n=e,o={context:n?.context,store:n?.store,configurable:n?.configurable,writer:n?.writer,interrupt:n?.interrupt,signal:n?.signal},s=this.tools.find(u=>u.name===t.name),a=async u=>{let{toolCall:l,tool:c}=u,p=c??this.tools.find(g=>g.name===l.name);if(p===void 0){let g=this.tools.map(y=>y.name);return new U({content:uu(l.name,g),tool_call_id:l.id,name:l.name,status:"error"})}let m=p;try{let g=await m.invoke({...l,type:"tool_call"},{...e,config:e,toolCallId:l.id,state:e.configurable?.__pregel_scratchpad?.currentTaskInput,signal:ws(this.signal,e.signal)});return U.isInstance(g)||ue(g)?g:new U({name:m.name,content:typeof g=="string"?g:JSON.stringify(g),tool_call_id:l.id})}catch(g){throw g instanceof yl?new ys(g,l):g}},i={toolCall:t,tool:s,state:r,runtime:o};if(this.wrapToolCall)try{return await this.wrapToolCall(i,a)}catch(u){return this.#e(u,t,!0)}if(!s){let u=this.tools.map(l=>l.name);return new U({content:uu(t.name,u),tool_call_id:t.id,name:t.name,status:"error"})}try{return await a(i)}catch(u){return this.#e(u,t,!1)}}async run(t,e){let r;if(Hp(t)){let{lg_tool_call:s,jumpTo:a,...i}=t;r=[await this.runTool(t.lg_tool_call,e,i)]}else{let s;if(cu(t))s=t;else if(Gp(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(R.isInstance(l)){i=l;break}}if(!R.isInstance(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e,t))??[])}if(!r.some(ue))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)ue(s)?s.graph===re.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>Zp(a))?o?o.goto.push(...s.goto):o=new re({graph:re.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};function Zp(t){return t instanceof ge}var Qp=class{},Yp=class{},St=class extends $r{#e;constructor(t,e){super(t),this.#e=e}async invokeMiddleware(t,e){let r={};if(this.middleware.contextSchema){let u=this.middleware.contextSchema?.shape;if(u){let l={},c=e?.context||{};for(let p of Object.keys(u))p in c&&(l[p]=c[p]);r=wt(this.middleware.contextSchema,l)}}let n={...this.#e.getState(),...t,messages:t.messages},o={context:r,store:e?.store,configurable:e?.configurable,writer:e?.writer,interrupt:e?.interrupt,signal:e?.signal},s=await this.runHook(n,Object.freeze(Object.assign(new Yp,{...o,context:Object.freeze(Object.assign(new Qp,r))})));if(!s)return{jumpTo:void 0};let a,i;if(this.name?.startsWith("BeforeAgentNode_")?(a=Ue(this.middleware.beforeAgent),i="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(a=Ue(this.middleware.beforeModel),i="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(a=Ue(this.middleware.afterAgent),i="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(a=Ue(this.middleware.afterModel),i="afterModel.canJumpTo"),typeof s.jumpTo=="string"&&!a?.includes(s.jumpTo)){let u=a&&a.length>0?`must be one of: ${a?.join(", ")}.`:i?`no ${i} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${s.jumpTo}, ${u}.`)}if(typeof s=="object"&&"type"in s){if(s.type==="terminate"){if(s.error)throw s.error;return{...n,...s.result||{},jumpTo:s.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(s)}`)}return{...n,...s,jumpTo:s.jumpTo}}get nodeOptions(){return{input:su(this.middleware.stateSchema)}}};var pu=class extends St{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(t,e){super({name:`BeforeAgentNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return vt(this.middleware.beforeAgent)(t,e)}};var mu=class extends St{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(t,e){super({name:`BeforeModelNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return vt(this.middleware.beforeModel)(t,e)}};var fu=class extends St{lc_namespace=["langchain","agents","afterModelNodes"];constructor(t,e){super({name:`AfterModelNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return vt(this.middleware.afterModel)(t,e)}};var hu=class extends St{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(t,e){super({name:`AfterAgentNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return vt(this.middleware.afterAgent)(t,e)}};var gu=class{#e=new Map;addNode(t,e){this.#e.set(t.name,[...this.#e.get(t.name)??[],e])}getState(t){let e=(this.#e.get(t)??[]).reduce((r,n)=>({...r,...n.getState()??{}}),{});return delete e.jumpTo,e}};var yu=class _u{#e;#r="v2";#s;#t=new gu;#n;constructor(e,r){if(this.options=e,this.#n=De(r??{},{metadata:{ls_integration:"langchain_create_agent"}}),e.name&&(this.#n=De(this.#n,{metadata:{lc_agent_name:e.name}})),this.#r=e.version??this.#r,!e.model)throw new Error("`model` option is required to create an agent.");typeof e.model!="string"&&_s(e.model);let n=this.options.middleware?.filter(T=>T.tools).flatMap(T=>T.tools)??[],o=[...e.tools??[],...n],s=new Set(o.filter(Ht).filter(T=>"returnDirect"in T&&T.returnDirect).map(T=>T.name)),a=!!this.options.middleware?.some(T=>T.wrapModelCall),{state:i,input:u,output:l}=Ql(this.options.responseFormat!==void 0||a,this.options.stateSchema,this.options.middleware),c=new ye(i,{input:u,output:l,context:this.options.contextSchema}),p=[],m=[],g=[],y=[],A=[];this.#s=new lu({model:this.options.model,systemMessage:tu(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:o,shouldReturnDirect:s,signal:this.options.signal,wrapModelCallHookMiddleware:A});let C=new Set,h=this.options.middleware??[];for(let T=0;T<h.length;T++){let E,F,J,Z,$=h[T];if(C.has($.name))throw new Error(`Middleware ${$.name} is defined multiple times`);if(C.add($.name),$.beforeAgent){E=new pu($,{getState:()=>this.#t.getState($.name)}),this.#t.addNode($,E);let W=`${$.name}.before_agent`;p.push({index:T,name:W,allowed:Ue($.beforeAgent)}),c.addNode(W,E,E.nodeOptions)}if($.beforeModel){F=new mu($,{getState:()=>this.#t.getState($.name)}),this.#t.addNode($,F);let W=`${$.name}.before_model`;m.push({index:T,name:W,allowed:Ue($.beforeModel)}),c.addNode(W,F,F.nodeOptions)}if($.afterModel){J=new fu($,{getState:()=>this.#t.getState($.name)}),this.#t.addNode($,J);let W=`${$.name}.after_model`;g.push({index:T,name:W,allowed:Ue($.afterModel)}),c.addNode(W,J,J.nodeOptions)}if($.afterAgent){Z=new hu($,{getState:()=>this.#t.getState($.name)}),this.#t.addNode($,Z);let W=`${$.name}.after_agent`;y.push({index:T,name:W,allowed:Ue($.afterAgent)}),c.addNode(W,Z,Z.nodeOptions)}$.wrapModelCall&&A.push([$,()=>this.#t.getState($.name)])}c.addNode(ae,this.#s);let b=h.some(T=>T.wrapToolCall),S=o.filter(Ht);if(S.length>0||b){let T=new du(S,{signal:this.options.signal,wrapToolCall:nu(h)});c.addNode(we,T)}let j;p.length>0?j=p[0].name:m.length>0?j=m[0].name:j=ae;let Q=m.length>0?m[0].name:ae,G=y.length>0?y[y.length-1].name:B;c.addEdge(he,j);let K=S.length>0||b;for(let T=0;T<p.length;T++){let E=p[T],F=E.name,J=T===p.length-1?Q:p[T+1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(W=>Oe(W)).filter(W=>W!=="tools"||K),$=Array.from(new Set([J,...Z.map(W=>W===B?G:W)]));c.addConditionalEdges(F,this.#c(S,J,G,K),$)}else c.addEdge(F,J)}for(let T=0;T<m.length;T++){let E=m[T],F=E.name,J=T===m.length-1?ae:m[T+1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(W=>Oe(W)).filter(W=>W!=="tools"||K),$=Array.from(new Set([J,...Z]));c.addConditionalEdges(F,this.#p(S,J,K),$)}else c.addEdge(F,J)}let z=g.at(-1);if(g.length>0&&z)c.addEdge(ae,z.name);else{let T=this.#a(S,!1,K).map(E=>E===B?G:E);T.length===1?c.addEdge(ae,T[0]):c.addConditionalEdges(ae,this.#u(G),T)}for(let T=g.length-1;T>0;T--){let E=g[T],F=E.name,J=g[T-1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(W=>Oe(W)).filter(W=>W!=="tools"||K),$=Array.from(new Set([J,...Z]));c.addConditionalEdges(F,this.#o(S,E.allowed,J,K),$)}else c.addEdge(F,J)}if(g.length>0){let T=g[0],E=T.name,F=this.#a(S,!0,K).filter($=>$!=="tools"||K),J=!!(T.allowed&&T.allowed.length>0),Z=F.map($=>$===B?G:$);c.addConditionalEdges(E,this.#i(S,J,G,K),Z)}for(let T=y.length-1;T>0;T--){let E=y[T],F=E.name,J=y[T-1].name;if(E.allowed&&E.allowed.length>0){let Z=E.allowed.map(W=>Oe(W)).filter(W=>W!=="tools"||K),$=Array.from(new Set([J,...Z]));c.addConditionalEdges(F,this.#o(S,E.allowed,J,K),$)}else c.addEdge(F,J)}if(y.length>0){let T=y[0],E=T.name;if(T.allowed&&T.allowed.length>0){let F=T.allowed.map(Z=>Oe(Z)).filter(Z=>Z!=="tools"||K),J=Array.from(new Set([B,...F]));c.addConditionalEdges(E,this.#o(S,T.allowed,B,K),J)}else c.addEdge(E,B)}if(K){let T=Q;s.size>0?c.addConditionalEdges(we,this.#l(s,G,T),[T,G]):c.addEdge(we,T)}this.#e=c.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}get checkpointer(){return this.#e.checkpointer}set checkpointer(e){this.#e.checkpointer=e}get store(){return this.#e.store}set store(e){this.#e.store=e}withConfig(e){return new _u(this.options,De(this.#n,e))}#a(e,r=!1,n=e.length>0){let o=[];return n&&o.push(we),r&&o.push(ae),o.push(B),o}#l(e,r,n){return o=>{let s=o.messages,a=s[s.length-1];return U.isInstance(a)&&a.name&&e.has(a.name)?this.options.responseFormat?n:r:n}}#u(e=B){return r=>{let n=r.messages.at(-1);if(!R.isInstance(n)||!n.tool_calls||n.tool_calls.length===0||n.tool_calls.every(s=>s.name.startsWith("extract-")))return e;if(this.#r==="v1")return we;let o=n.tool_calls.filter(s=>!s.name.startsWith("extract-"));return o.length===0?e:o.map(s=>new ge(we,{...r,lg_tool_call:s}))}}#i(e,r,n,o=e.length>0){let s=!!this.options.responseFormat;return a=>{let i=a,u=i.messages,l=u.at(-1);if(R.isInstance(l)&&(!l.tool_calls||l.tool_calls.length===0))return n;if(r&&i.jumpTo){let h=Oe(i.jumpTo);return h===B?n:h==="tools"?o?new ge(we,{...a,jumpTo:void 0}):n:new ge(ae,{...a,jumpTo:void 0})}let c=u.filter(U.isInstance),p=u.filter(R.isInstance).at(-1),m=p?.tool_calls?.filter(h=>!c.some(b=>b.tool_call_id===h.id));if(m&&m.length>0)return this.#r==="v1"?we:m.map(h=>new ge(we,{...a,lg_tool_call:h}));let g=p?.tool_calls?.some(h=>h.name.startsWith("extract-"));if(m&&m.length===0&&!g&&s)return ae;if(!R.isInstance(l)||!l.tool_calls||l.tool_calls.length===0)return n;let y=l.tool_calls.every(h=>h.name.startsWith("extract-")),A=l.tool_calls.some(h=>!h.name.startsWith("extract-"));if(y||!A)return n;if(this.#r==="v1")return we;let C=l.tool_calls.filter(h=>!h.name.startsWith("extract-"));return C.length===0?n:C.map(h=>new ge(we,{...a,lg_tool_call:h}))}}#o(e,r,n,o=e.length>0){let s=new Set(r.map(a=>Oe(a)));return a=>{let i=a;if(i.jumpTo){let u=Oe(i.jumpTo);if(u===B&&s.has(B))return B;if(u==="tools"&&s.has("tools"))return o?new ge(we,{...a,jumpTo:void 0}):B;if(u==="model_request"&&s.has("model_request"))return new ge(ae,{...a,jumpTo:void 0})}return n}}#c(e,r,n,o=e.length>0){return s=>{let a=s;if(!a.jumpTo)return r;let i=Oe(a.jumpTo);return i===B?n:i==="tools"?o?new ge(we,{...s,jumpTo:void 0}):n:new ge(ae,{...s,jumpTo:void 0})}}#p(e,r,n=e.length>0){return o=>{let s=o;if(!s.jumpTo)return r;let a=Oe(s.jumpTo);return a===B?B:a==="tools"?n?new ge(we,{...o,jumpTo:void 0}):B:new ge(ae,{...o,jumpTo:void 0})}}async#d(e,r){if(!this.options.middleware||this.options.middleware.length===0||e instanceof re||!e)return e;let n=await ou(this.options.middleware,e),o={...(await this.#e.getState(r).catch(()=>({values:{}}))).values,...e};if(!o)return o;for(let[s,a]of Object.entries(n))s in o||(o[s]=a);return o}async invoke(e,r){let n=De(this.#n,r),o=await this.#d(e,n);return this.#e.invoke(o,n)}async stream(e,r){let n=De(this.#n,r),o=await this.#d(e,n);return this.#e.stream(o,n)}async drawMermaidPng(e){let r=await(await(await this.#e.getGraphAsync()).drawMermaidPng(e)).arrayBuffer();return new Uint8Array(r)}async drawMermaid(e){return(await this.#e.getGraphAsync()).drawMermaid(e)}streamEvents(e,r,n){let o=De(this.#n,r);return this.#e.streamEvents(e,{...o,version:r?.version??"v2"},n)}getGraphAsync(e){return this.#e.getGraphAsync(e)}getState(e,r){return this.#e.getState(e,r)}getStateHistory(e,r){return this.#e.getStateHistory(e,r)}getSubgraphs(e,r){return this.#e.getSubgraphs(e,r)}getSubgraphsAsync(e,r){return this.#e.getSubgraphsAsync(e,r)}updateState(e,r,n){return this.#e.updateState(e,r,n)}get builder(){return this.#e.builder}};function wo(t){return new yu(t)}var Xp=x.function().args(x.custom(),x.custom(),x.custom()).returns(x.union([x.string(),x.promise(x.string())])),em=["approve","edit","reject"],tm=x.enum(em),rm=x.object({allowedDecisions:x.array(tm),description:x.union([x.string(),Xp]).optional(),argsSchema:x.record(x.any()).optional()}),Tv=x.object({interruptOn:x.record(x.union([x.boolean(),rm])).optional(),descriptionPrefix:x.string().default("Tool execution requires approval")});var am=`<role>
36
36
  Context Extraction Assistant
37
37
  </role>
38
38
 
@@ -58,7 +58,7 @@ Respond ONLY with the extracted context. Do not include any additional informati
58
58
  <messages>
59
59
  Messages to summarize:
60
60
  {messages}
61
- </messages>`;var im=x.function().args(x.array(x.custom())).returns(x.union([x.number(),x.promise(x.number())])),Da=x.object({fraction:x.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:x.number().positive("Tokens must be greater than 0").optional(),messages:x.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),bu=x.object({fraction:x.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:x.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:x.number().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),Fv=x.object({model:x.custom(),trigger:x.union([Da,x.array(Da)]).optional(),keep:bu.optional(),tokenCounter:im.optional(),summaryPrompt:x.string().default(am),trimTokensToSummarize:x.number().optional(),summaryPrefix:x.string().optional(),maxTokensBeforeSummary:x.number().optional(),messagesToKeep:x.number().optional()});var Zv=x.object({model:x.string().or(x.instanceof(Ml)).optional(),systemPrompt:x.string().optional(),maxTools:x.number().optional(),alwaysInclude:x.array(x.string()).optional()});var nT=x.object({applyToInput:x.boolean().optional(),applyToOutput:x.boolean().optional(),applyToToolResults:x.boolean().optional()});var lT=x.object({rules:x.record(x.string(),x.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var lm=["continue","error","end"],um="continue";var cm=x.enum(lm).default(um);x.object({toolName:x.string().optional(),threadLimit:x.number().optional(),runLimit:x.number().optional(),exitBehavior:cm});var wT=x.object({threadToolCallCount:x.record(x.string(),x.number()).default({}),runToolCallCount:x.record(x.string(),x.number()).default({})});var dm=x.enum(["pending","in_progress","completed"]).describe("Status of the todo"),pm=x.object({content:x.string().describe("Content of the todo item"),status:dm}),kT=x.object({todos:x.array(pm).default([])});var PT=x.object({threadLimit:x.number().optional(),runLimit:x.number().optional(),exitBehavior:x.enum(["error","end"]).optional()}),RT=x.object({threadModelCallCount:x.number().default(0),runModelCallCount:x.number().default(0)});var bs=x.object({maxRetries:x.number().min(0).default(2),retryOn:x.union([x.function().args(x.instanceof(Error)).returns(x.boolean()),x.array(x.custom())]).default(()=>()=>!0),backoffFactor:x.number().min(0).default(2),initialDelayMs:x.number().min(0).default(1e3),maxDelayMs:x.number().min(0).default(6e4),jitter:x.boolean().default(!0)});var GT=x.object({onFailure:x.union([x.literal("error"),x.literal("continue"),x.function().args(x.instanceof(Error)).returns(x.string())]).default("continue")}).merge(bs);var tS=x.object({tools:x.array(x.union([x.custom(),x.custom(),x.string()])).optional(),onFailure:x.union([x.literal("error"),x.literal("continue"),x.literal("raise"),x.literal("return_message"),x.function().args(x.instanceof(Error)).returns(x.string())]).default("continue")}).merge(bs);var mS=x.object({enableCaching:x.boolean().optional(),ttl:x.enum(["5m","1h"]).optional(),minMessagesToCache:x.number().optional(),unsupportedModelBehavior:x.enum(["ignore","warn","raise"]).optional()});function bo(t,e){return t.lc_error_code=e,t.message=`${t.message}
61
+ </messages>`;var im=x.function().args(x.array(x.custom())).returns(x.union([x.number(),x.promise(x.number())])),Da=x.object({fraction:x.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:x.number().positive("Tokens must be greater than 0").optional(),messages:x.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),bu=x.object({fraction:x.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:x.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:x.number().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),qv=x.object({model:x.custom(),trigger:x.union([Da,x.array(Da)]).optional(),keep:bu.optional(),tokenCounter:im.optional(),summaryPrompt:x.string().default(am),trimTokensToSummarize:x.number().optional(),summaryPrefix:x.string().optional(),maxTokensBeforeSummary:x.number().optional(),messagesToKeep:x.number().optional()});var Qv=x.object({model:x.string().or(x.instanceof(Ml)).optional(),systemPrompt:x.string().optional(),maxTools:x.number().optional(),alwaysInclude:x.array(x.string()).optional()});var oT=x.object({applyToInput:x.boolean().optional(),applyToOutput:x.boolean().optional(),applyToToolResults:x.boolean().optional()});var uT=x.object({rules:x.record(x.string(),x.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var lm=["continue","error","end"],um="continue";var cm=x.enum(lm).default(um);x.object({toolName:x.string().optional(),threadLimit:x.number().optional(),runLimit:x.number().optional(),exitBehavior:cm});var bT=x.object({threadToolCallCount:x.record(x.string(),x.number()).default({}),runToolCallCount:x.record(x.string(),x.number()).default({})});var dm=x.enum(["pending","in_progress","completed"]).describe("Status of the todo"),pm=x.object({content:x.string().describe("Content of the todo item"),status:dm}),CT=x.object({todos:x.array(pm).default([])});var RT=x.object({threadLimit:x.number().optional(),runLimit:x.number().optional(),exitBehavior:x.enum(["error","end"]).optional()}),NT=x.object({threadModelCallCount:x.number().default(0),runModelCallCount:x.number().default(0)});var bs=x.object({maxRetries:x.number().min(0).default(2),retryOn:x.union([x.function().args(x.instanceof(Error)).returns(x.boolean()),x.array(x.custom())]).default(()=>()=>!0),backoffFactor:x.number().min(0).default(2),initialDelayMs:x.number().min(0).default(1e3),maxDelayMs:x.number().min(0).default(6e4),jitter:x.boolean().default(!0)});var HT=x.object({onFailure:x.union([x.literal("error"),x.literal("continue"),x.function().args(x.instanceof(Error)).returns(x.string())]).default("continue")}).merge(bs);var rS=x.object({tools:x.array(x.union([x.custom(),x.custom(),x.string()])).optional(),onFailure:x.union([x.literal("error"),x.literal("continue"),x.literal("raise"),x.literal("return_message"),x.function().args(x.instanceof(Error)).returns(x.string())]).default("continue")}).merge(bs);var fS=x.object({enableCaching:x.boolean().optional(),ttl:x.enum(["5m","1h"]).optional(),minMessagesToCache:x.number().optional(),unsupportedModelBehavior:x.enum(["ignore","warn","raise"]).optional()});function bo(t,e){return t.lc_error_code=e,t.message=`${t.message}
62
62
 
63
63
  Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
64
64
  `,t}function O(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}function w(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var Fa=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Fa=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function xo(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Ao=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var k=class extends Error{},Y=class t extends k{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=r;let s=r;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new kt({message:n,cause:Ao(r)});let s=r?.error;return e===400?new Lr(e,s,n,o):e===401?new jr(e,s,n,o):e===403?new zr(e,s,n,o):e===404?new Dr(e,s,n,o):e===409?new Fr(e,s,n,o):e===422?new qr(e,s,n,o):e===429?new Ur(e,s,n,o):e>=500?new Br(e,s,n,o):new t(e,s,n,o)}},X=class extends Y{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},kt=class extends Y{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Be=class extends kt{constructor({message:e}={}){super({message:e??"Request timed out."})}},Lr=class extends Y{},jr=class extends Y{},zr=class extends Y{},Dr=class extends Y{},Fr=class extends Y{},qr=class extends Y{},Ur=class extends Y{},Br=class extends Y{},Kr=class extends k{constructor(){super("Could not parse response content as the length limit was reached")}},Wr=class extends k{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Ke=class extends Error{constructor(e){super(e)}},Jt=class extends Y{constructor(e,r,n){let o="OAuth2 authentication error",s;if(r&&typeof r=="object"){let a=r;s=a.error;let i=a.error_description;i&&typeof i=="string"?o=i:s&&(o=s)}super(e,r,o,n),this.error_code=s}},Io=class extends k{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var xm=/^[a-z][a-z0-9+.-]*:/i,xu=t=>xm.test(t),de=t=>(de=Array.isArray,de(t)),qa=de;function xs(t){return typeof t!="object"?{}:t??{}}function Ua(t){if(!t)return!0;for(let e in t)return!1;return!0}function Au(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function vo(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Iu=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new k(`${t} must be an integer`);if(e<0)throw new k(`${t} must be a positive integer`);return e};var vu=t=>{try{return JSON.parse(t)}catch{return}};var We=t=>new Promise(e=>setTimeout(e,t));var Ct="6.37.0";var Cu=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Am(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Im=()=>{let t=Am();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ct,"X-Stainless-OS":Su(Deno.build.os),"X-Stainless-Arch":Tu(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ct,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ct,"X-Stainless-OS":Su(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Tu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=vm();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ct,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ct,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function vm(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var Tu=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Su=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),ku,Eu=()=>ku??(ku=Im());function As(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ba(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Is(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ba({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function Ka(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Wa(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var Mu=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Va="RFC3986",Ga=t=>String(t),Ha={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Ga},Pu="RFC1738";var vs=(t,e)=>(vs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),vs(t,e)),Ve=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var Ja=1024,Ru=(t,e,r,n,o)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(i){return"%26%23"+parseInt(i.slice(2),16)+"%3B"});let a="";for(let i=0;i<s.length;i+=Ja){let u=s.length>=Ja?s.slice(i,i+Ja):s,l=[];for(let c=0;c<u.length;++c){let p=u.charCodeAt(c);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||o===Pu&&(p===40||p===41)){l[l.length]=u.charAt(c);continue}if(p<128){l[l.length]=Ve[p];continue}if(p<2048){l[l.length]=Ve[192|p>>6]+Ve[128|p&63];continue}if(p<55296||p>=57344){l[l.length]=Ve[224|p>>12]+Ve[128|p>>6&63]+Ve[128|p&63];continue}c+=1,p=65536+((p&1023)<<10|u.charCodeAt(c)&1023),l[l.length]=Ve[240|p>>18]+Ve[128|p>>12&63]+Ve[128|p>>6&63]+Ve[128|p&63]}a+=l.join("")}return a};function Nu(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function Za(t,e){if(de(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var Lu={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},ju=function(t,e){Array.prototype.push.apply(t,de(e)?e:[e])},$u,oe={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ru,encodeValuesOnly:!1,format:Va,formatter:Ga,indices:!1,serializeDate(t){return($u??($u=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function Sm(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var Qa={};function zu(t,e,r,n,o,s,a,i,u,l,c,p,m,g,y,A,C,h){let b=t,S=h,j=0,Q=!1;for(;(S=S.get(Qa))!==void 0&&!Q;){let E=S.get(t);if(j+=1,typeof E<"u"){if(E===j)throw new RangeError("Cyclic object value");Q=!0}typeof S.get(Qa)>"u"&&(j=0)}if(typeof l=="function"?b=l(e,b):b instanceof Date?b=m?.(b):r==="comma"&&de(b)&&(b=Za(b,function(E){return E instanceof Date?m?.(E):E})),b===null){if(s)return u&&!A?u(e,oe.encoder,C,"key",g):e;b=""}if(Sm(b)||Nu(b)){if(u){let E=A?e:u(e,oe.encoder,C,"key",g);return[y?.(E)+"="+y?.(u(b,oe.encoder,C,"value",g))]}return[y?.(e)+"="+y?.(String(b))]}let G=[];if(typeof b>"u")return G;let K;if(r==="comma"&&de(b))A&&u&&(b=Za(b,u)),K=[{value:b.length>0?b.join(",")||null:void 0}];else if(de(l))K=l;else{let E=Object.keys(b);K=c?E.sort(c):E}let z=i?String(e).replace(/\./g,"%2E"):String(e),T=n&&de(b)&&b.length===1?z+"[]":z;if(o&&de(b)&&b.length===0)return T+"[]";for(let E=0;E<K.length;++E){let F=K[E],J=typeof F=="object"&&typeof F.value<"u"?F.value:b[F];if(a&&J===null)continue;let Z=p&&i?F.replace(/\./g,"%2E"):F,$=de(b)?typeof r=="function"?r(T,Z):T:T+(p?"."+Z:"["+Z+"]");h.set(t,j);let W=new WeakMap;W.set(Qa,h),ju(G,zu(J,$,r,n,o,s,a,i,r==="comma"&&A&&de(b)?null:u,l,c,p,m,g,y,A,C,W))}return G}function km(t=oe){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||oe.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Va;if(typeof t.format<"u"){if(!vs(Ha,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=Ha[r],o=oe.filter;(typeof t.filter=="function"||de(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Lu?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=oe.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:oe.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:oe.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:oe.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:oe.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?oe.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:oe.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:oe.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:oe.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:oe.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:oe.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:oe.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:oe.strictNullHandling}}function Du(t,e={}){let r=t,n=km(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):de(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof r!="object"||r===null)return"";let i=Lu[n.arrayFormat],u=i==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);let l=new WeakMap;for(let m=0;m<o.length;++m){let g=o[m];n.skipNulls&&r[g]===null||ju(a,zu(r[g],g,i,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}let c=a.join(n.delimiter),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),c.length>0?p+c:""}function Fu(t){return Du(t,{arrayFormat:"brackets"})}function Bu(t){let e=0;for(let o of t)e+=o.length;let r=new Uint8Array(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}var qu;function Vr(t){let e;return(qu??(e=new globalThis.TextEncoder,qu=e.encode.bind(e)))(t)}var Uu;function Ya(t){let e;return(Uu??(e=new globalThis.TextDecoder,Uu=e.decode.bind(e)))(t)}var ve,Te,Zt=class{constructor(){ve.set(this,void 0),Te.set(this,void 0),O(this,ve,new Uint8Array,"f"),O(this,Te,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Vr(e):e;O(this,ve,Bu([w(this,ve,"f"),r]),"f");let n=[],o;for(;(o=Em(w(this,ve,"f"),w(this,Te,"f")))!=null;){if(o.carriage&&w(this,Te,"f")==null){O(this,Te,o.index,"f");continue}if(w(this,Te,"f")!=null&&(o.index!==w(this,Te,"f")+1||o.carriage)){n.push(Ya(w(this,ve,"f").subarray(0,w(this,Te,"f")-1))),O(this,ve,w(this,ve,"f").subarray(w(this,Te,"f")),"f"),O(this,Te,null,"f");continue}let s=w(this,Te,"f")!==null?o.preceding-1:o.preceding,a=Ya(w(this,ve,"f").subarray(0,s));n.push(a),O(this,ve,w(this,ve,"f").subarray(o.index),"f"),O(this,Te,null,"f")}return n}flush(){return w(this,ve,"f").length?this.decode(`
@@ -91,19 +91,19 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
91
91
  ]))`;continue}else if(o[l]==="$"){s+=`($|(?=[\r
92
92
  ]))`;continue}}if(n.s&&o[l]==="."){s+=i?`${o[l]}\r
93
93
  `:`[${o[l]}\r
94
- ]`;continue}s+=o[l],o[l]==="\\"?a=!0:i&&o[l]==="]"?i=!1:!i&&o[l]==="["&&(i=!0)}try{let l=new RegExp(s)}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 s};function ea(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===q.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:P(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:P(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===q.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Xs(t.keyType._def,e)).reduce((o,[s,a])=>s==="type"?o:{...o,[s]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===q.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function rd(t,e){if(e.mapStrategy==="record")return ea(t,e);let r=P(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=P(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function nd(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function od(){return{not:{}}}function sd(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ko={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function id(t,e){if(e.target==="openApi3")return ad(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ko&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let a=Ko[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return ad(t,e)}var ad=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>P(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function ld(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:Ko[t.innerType._def.typeName],nullable:!0}:{type:[Ko[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=P(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=P(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function ud(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Ci(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?V(r,"minimum",n.value,n.message,e):V(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),V(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?V(r,"maximum",n.value,n.message,e):V(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),V(r,"maximum",n.value,n.message,e));break;case"multipleOf":V(r,"multipleOf",n.value,n.message,e);break}return r}function xh(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":P(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":P(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function cd(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,s])=>{if(s===void 0||s._def===void 0)return n;let a=[...e.currentPath,"properties",o],i=P(s._def,{...e,currentPath:a,propertyPath:a});if(i===void 0)return n;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${a.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:{...n.properties,[o]:i},required:s.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]}},{properties:{},required:[]}),additionalProperties:xh(t,e)};return r.required.length||delete r.required,r}var dd=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return P(t.innerType._def,{...e,currentPath:e.currentPath});let r=P(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}};var pd=(t,e)=>{if(e.pipeStrategy==="input")return P(t.in._def,e);if(e.pipeStrategy==="output")return P(t.out._def,e);let r=P(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=P(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function md(t,e){return P(t.type._def,e)}function fd(t,e){let n={type:"array",uniqueItems:!0,items:P(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&V(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&V(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function hd(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>P(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:P(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>P(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function gd(){return{not:{}}}function yd(){return{}}var _d=(t,e)=>P(t.innerType._def,e);function P(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Fc)return a}if(n&&!r){let a=Ah(n,e);if(a!==void 0)return"$ref"in a&&e.seenRefs.add(a.$ref),a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=vh(t,t.typeName,e,r);return s&&Th(t,e,s),o.jsonSchema=s,s}var Ah=(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:Ih(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Ih=(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("/")},vh=(t,e,r,n)=>{switch(e){case q.ZodString:return Xs(t,r);case q.ZodNumber:return ud(t,r);case q.ZodObject:return cd(t,r);case q.ZodBigInt:return Vc(t,r);case q.ZodBoolean:return Gc();case q.ZodDate:return Ei(t,r);case q.ZodUndefined:return gd();case q.ZodNull:return sd(r);case q.ZodArray:return Wc(t,r);case q.ZodUnion:case q.ZodDiscriminatedUnion:return id(t,r);case q.ZodIntersection:return Xc(t,r);case q.ZodTuple:return hd(t,r);case q.ZodRecord:return ea(t,r);case q.ZodLiteral:return ed(t,r);case q.ZodEnum:return Yc(t);case q.ZodNativeEnum:return nd(t);case q.ZodNullable:return ld(t,r);case q.ZodOptional:return dd(t,r);case q.ZodMap:return rd(t,r);case q.ZodSet:return fd(t,r);case q.ZodLazy:return P(t.getter()._def,r);case q.ZodPromise:return md(t,r);case q.ZodNaN:case q.ZodNever:return od();case q.ZodEffects:return Qc(t,r,n);case q.ZodAny:return Kc();case q.ZodUnknown:return yd();case q.ZodDefault:return Zc(t,r);case q.ZodBranded:return Hc(t,r);case q.ZodReadonly:return _d(t,r);case q.ZodCatch:return Jc(t,r);case q.ZodPipeline:return pd(t,r);case q.ZodFunction:case q.ZodVoid:case q.ZodSymbol:return;default:return(o=>{})(e)}},Th=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Mi=(t,e)=>{let r=Bc(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=P(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let a=(()=>{if(Uc(r.definitions))return;let u={},l=new Set;for(let c=0;c<500;c++){let p=Object.entries(r.definitions).filter(([m])=>!l.has(m));if(p.length===0)break;for(let[m,g]of p)u[m]=P(Bo(g),{...r,currentPath:[...r.basePath,r.definitionPath,m]},!0)??{},l.add(m)}return u})(),i=n===void 0?a?{...o,[r.definitionPath]:a}:o:r.nameStrategy==="duplicate-ref"?{...o,...a||r.seenRefs.size?{[r.definitionPath]:{...a,...r.seenRefs.size?{[n]:o}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...a,[n]:o}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),i};function wd(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 ft(e,[],e)}function Pi(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Pi(e))return!0;for(let e of t.anyOf??[])if(Pi(e))return!0;return!1}function ft(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!Tr(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(Tr(n))for(let[m,g]of Object.entries(n))ft(g,[...e,"$defs",m],r);let o=t.definitions;if(Tr(o))for(let[m,g]of Object.entries(o))ft(g,[...e,"definitions",m],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let a=t.required??[],i=t.properties;if(Tr(i)){for(let[m,g]of Object.entries(i))if(!Pi(g)&&!a.includes(m))throw new Error(`Zod field at \`${[...e,"properties",m].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(i),t.properties=Object.fromEntries(Object.entries(i).map(([m,g])=>[m,ft(g,[...e,"properties",m],r)]))}let u=t.items;Tr(u)&&(t.items=ft(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((m,g)=>ft(m,[...e,"anyOf",String(g)],r)));let c=t.allOf;if(Array.isArray(c))if(c.length===1){let m=ft(c[0],[...e,"allOf","0"],r);Object.assign(t,m),delete t.allOf}else t.allOf=c.map((m,g)=>ft(m,[...e,"allOf",String(g)],r));t.default===null&&delete t.default;let p=t.$ref;if(p&&kh(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);let m=Sh(r,p);if(typeof m=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!Tr(m))throw new Error(`Expected \`$ref: ${p}\` to resolve to an object but got ${JSON.stringify(m)}`);return Object.assign(t,{...m,...t}),delete t.$ref,ft(t,e,r)}return t}function Sh(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),n=t;for(let o of r){if(!Tr(n))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(n)}`);let s=n[o];if(s===void 0)throw new Error(`Key ${o} not found while resolving ${e}`);n=s}return n}function Tr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function kh(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function Ch(t,e){return Mi(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Eh(t){return wd(Sl(t,{target:"draft-7"}))}function Oh(t){return"_zod"in t}function bd(t,e,r){return Yu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Oh(t)?Eh(t):Ch(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var xd=["jsonSchema","functionCalling","jsonMode"];function Ad(t,e){if(typeof e<"u"&&!xd.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${xd.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 Mh(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Id(t,e,r){if(kl(t))return bd(t,e,r);if(Mr(t))return Mh({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Fe(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>vl(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function vd(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(n=>typeof n?.image_url?.url=="string").map(n=>({type:"image",url:n.image_url.url}));return[{type:"text",text:t},...r]}return t}var Td={"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 Hn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var Sr=class extends po{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??Xe("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??Xe("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(!pt(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&&tt(t.json_schema.schema)?Id(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=Kt({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=Wt(r.defaultHeaders),this.client=new M(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return Ir(t)?zc(t.metadata.customTool):us(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Cc(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(n=>{if(Gn(n)||Ir(n))return n;if(Mc(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return fo(n)&&n.extras?.defer_loading===!0?{...o,defer_loading:!0}:o}),...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,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let o=await Promise.all(t.map(async s=>{let[a,i]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(mt(s))]),u=s.name!==void 0?n+await this.getNumTokens(s.name):0,l=a+r+i+u,c=s;if(c._getType()==="function"&&(l-=2),c.additional_kwargs?.function_call&&(l+=3),c?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(p){console.error("Error parsing function arguments",p,JSON.stringify(c.additional_kwargs.function_call)),l+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:o}}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 n=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let o=Ec(e);n+=await this.getNumTokens(o),n+=9}return e&&t.find(o=>o._getType()==="system")&&(n-=4),r==="none"?n+=1:typeof r=="object"&&(n+=await this.getNumTokens(r.name)+4),n}async moderateContent(t,e){let r=this._getClientOptions(e?.options),n={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(n,r)}catch(o){throw Qe(o)}})}get profile(){return Td[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,n,{schema:o,name:s,includeRaw:a}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let i=Ad(this.model,e?.method);if(i==="jsonMode"){n=Ca(o);let u=Fe(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...u}}})}else if(i==="jsonSchema"){let u=Fe(o),l={name:s??"extract",description:as(u),schema:tt(o)?o:u,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:l.name,description:l.description,...u}}}),tt(o)||_t(o)){let c=Ca(o);n=qe.from(async p=>"parsed"in p.additional_kwargs?p.additional_kwargs.parsed:c.invoke(p.content))}else n=new Pl}else{let u=s??"extract",l=Fe(o),c;tt(o)||_t(o)?c={name:u,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(c=o,u=o.name):(u=o.title??u,c={name:u,description:o.description??"",parameters:o}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:c}],tool_choice:{type:"function",function:{name:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...l}},...e?.strict!==void 0?{strict:e.strict}:{}}),n=Nl(o,u)}return $l(r,n,a)}};var ta={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=Aa({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||"",n;try{n=xa(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.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:n.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=xa(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=Aa({dataUrl:t.url}),r=Vn(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=Vn(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`)}},Ri=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let s=[],a=[];for(let l of n??[])try{s.push(cs(l,{returnId:!0}))}catch(c){a.push(Rr(l,c.message))}let i={function_call:t.function_call,tool_calls:n};r!==void 0&&(i.__raw_response=e),o!==void 0&&(i.reasoning_content=o);let u={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(i.audio=t.audio),new R({content:vd(t.content||"",e.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:a,additional_kwargs:i,response_metadata:u,id:e.id})}default:return new ns(t.content||"",t.role??"unknown")}},Ni=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let o=t.role??n,s=t.content??"",a;t.function_call?a={function_call:t.function_call}:t.tool_calls?a={tool_calls:t.tool_calls}:a={},r&&(a.__raw_response=e),t.reasoning_content!==void 0&&(a.reasoning_content=t.reasoning_content),t.audio&&(a.audio={...t.audio,index:e.choices[0].index});let i={model_provider:"openai",usage:{...e.usage}};if(o==="user")return new Ta({content:s,response_metadata:i});if(o==="assistant"){let u=[];if(Array.isArray(t.tool_calls))for(let l of t.tool_calls)u.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new et({content:s,tool_call_chunks:u,additional_kwargs:a,id:e.id,response_metadata:i})}else return o==="system"?new os({content:s,response_metadata:i}):o==="developer"?new os({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new wl({content:s,additional_kwargs:a,name:t.name,response_metadata:i}):o==="tool"?new va({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:i}):new _l({content:s,role:o,response_metadata:i})},Sd=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=bl(()=>{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=Vn(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}}}},kd=({message:t,model:e})=>{let r=mt(t);if(r==="system"&&pt(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="assistant")return{role:"assistant",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="tool"&&U.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")};function*n(o){for(let s of o){s.type==="text"&&(yield{type:"text",text:s.text});let a=Sd(s);a&&(yield a)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},Wo=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return kd({message:r});let n=mt(r);n==="system"&&pt(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(a=>ts(a)?rs(a,ta):typeof a=="object"&&a!==null&&"type"in a&&a.type==="tool_use"?[]:a),s={role:n,content:o};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),R.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Rl):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),U.isInstance(r)&&r.tool_call_id!=null&&(s.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[s,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:s});var ra=class extends Sr{constructor(t,e){super(Hn(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={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(a=>this._convertChatOpenAIToolToCompletionsTool(a,{strict:r})):void 0,tool_choice:Qs(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...n,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&&(o.prediction=t.prediction),this.service_tier!==void 0&&(o.service_tier=this.service_tier),t?.service_tier!==void 0&&(o.service_tier=t.service_tier);let s=this._getReasoningParams(t);return s!==void 0&&s.effort!==void 0&&(o.reasoning_effort=s.effort),pt(o.model)?o.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:o.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,o}async _generate(t,e,r){e.signal?.throwIfAborted();let n={},o=this.invocationParams(e),s=Wo({messages:t,model:this.model});if(o.stream){let a=this._streamResponseChunks(t,e,r),i={};for await(let g of a){g.message.response_metadata={...g.generationInfo,...g.message.response_metadata};let y=g.generationInfo?.completion??0;i[y]===void 0?i[y]=g:i[y]=i[y].concat(g)}let u=Object.entries(i).sort(([g],[y])=>parseInt(g,10)-parseInt(y,10)).map(([g,y])=>y),{functions:l,function_call:c}=this.invocationParams(e),p=await this._getEstimatedTokenCountFromPrompt(t,l,c),m=await this._getNumTokensFromGenerations(u);return n.input_tokens=p,n.output_tokens=m,n.total_tokens=p+m,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let a=await this.completionWithRetry({...o,stream:!1,messages:s},{signal:e?.signal,...e?.options}),{completion_tokens:i,prompt_tokens:u,total_tokens:l,prompt_tokens_details:c,completion_tokens_details:p}=a?.usage??{};i&&(n.output_tokens=(n.output_tokens??0)+i),u&&(n.input_tokens=(n.input_tokens??0)+u),l&&(n.total_tokens=(n.total_tokens??0)+l),(c?.audio_tokens!==null||c?.cached_tokens!==null)&&(n.input_token_details={...c?.audio_tokens!==null&&{audio:c?.audio_tokens},...c?.cached_tokens!==null&&{cache_read:c?.cached_tokens}}),(p?.audio_tokens!==null||p?.reasoning_tokens!==null)&&(n.output_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.reasoning_tokens!==null&&{reasoning:p?.reasoning_tokens}});let m=[];for(let g of a?.choices??[]){let y={text:g.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(g.message??{role:"assistant"},a)};y.generationInfo={...g.finish_reason?{finish_reason:g.finish_reason}:{},...g.logprobs?{logprobs:g.logprobs}:{}},yt(y.message)&&(y.message.usage_metadata=n),y.message=new R(Object.fromEntries(Object.entries(y.message).filter(([A])=>!A.startsWith("lc_")))),m.push(y)}return{generations:m,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamResponseChunks(t,e,r){let n=Wo({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s,a=await this.completionWithRetry(o,e),i;for await(let u of a){if(e.signal?.aborted)return;let l=u?.choices?.[0];if(u.usage&&(i=u.usage),!l)continue;let{delta:c}=l;if(!c)continue;let p=this._convertCompletionsDeltaToBaseMessageChunk(c,u,s);s=c.role??s;let m={prompt:e.promptIndex??0,completion:l.index??0};if(typeof p.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let g={...m};l.finish_reason!=null&&(g.finish_reason=l.finish_reason,g.system_fingerprint=u.system_fingerprint,g.model_name=u.model,g.service_tier=u.service_tier),this.logprobs&&(g.logprobs=l.logprobs);let y=new co({message:p,text:p.content,generationInfo:g});yield y,await r?.handleLLMNewToken(y.text??"",m,void 0,void 0,void 0,{chunk:y})}if(i){let u={...i.prompt_tokens_details?.audio_tokens!==null&&{audio:i.prompt_tokens_details?.audio_tokens},...i.prompt_tokens_details?.cached_tokens!==null&&{cache_read:i.prompt_tokens_details?.cached_tokens}},l={...i.completion_tokens_details?.audio_tokens!==null&&{audio:i.completion_tokens_details?.audio_tokens},...i.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:i.completion_tokens_details?.reasoning_tokens}},c=new co({message:new et({content:"",response_metadata:{usage:{...i}},usage_metadata:{input_tokens:i.prompt_tokens,output_tokens:i.completion_tokens,total_tokens:i.total_tokens,...Object.keys(u).length>0&&{input_token_details:u},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield c,await r?.handleLLMNewToken(c.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:c})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=this._getClientOptions(e),n=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(o){throw Qe(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return Ni({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Ri({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var na="__openai_function_call_ids__";function Nd(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 Rh(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 $i=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}},oa=t=>{if(t.error){let u=new Error(t.error.message);throw u.name=t.error.code,u}let e,r=[],n=[],o=[],s=t.output.map(u=>{if(u.type==="function_call"&&"parsed_arguments"in u){let l={...u};return delete l.parsed_arguments,l}return u}),a={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:s,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},i={};for(let u of t.output)if(u.type==="message")e=u.id,r.push(...u.content.flatMap(l=>l.type==="output_text"?("parsed"in l&&l.parsed!=null&&(i.parsed=l.parsed),{type:"text",text:l.text,annotations:l.annotations.map(Nd),...u.phase!==null?{phase:u.phase}:{}}):l.type==="refusal"?(i.refusal=l.refusal,[]):l));else if(u.type==="function_call"){let l={function:{name:u.name,arguments:u.arguments},id:u.call_id};try{n.push(cs(l,{returnId:!0}))}catch(c){let p;typeof c=="object"&&c!=null&&"message"in c&&typeof c.message=="string"&&(p=c.message),o.push(Rr(l,p))}i[na]??={},u.id&&(i[na][u.call_id]=u.id)}else if(u.type==="reasoning"){i.reasoning=u;let l=u.summary?.map(c=>c.text).filter(Boolean).join("");l&&r.push({type:"reasoning",reasoning:l})}else if(u.type==="custom_tool_call"){let l=Rc(u);l?n.push(l):o.push(Rr(u,"Malformed custom tool call"))}else if(u.type==="computer_call"){let l=Nc(u);l?n.push(l):o.push(Rr(u,"Malformed computer call"))}else u.type==="image_generation_call"?(u.result&&r.push({type:"image",mimeType:"image/png",data:u.result,id:u.id,metadata:{status:u.status}}),i.tool_outputs??=[],i.tool_outputs.push(u)):(i.tool_outputs??=[],i.tool_outputs.push(u));return new R({id:e,content:r,tool_calls:n,invalid_tool_calls:o,usage_metadata:$i(t.usage),additional_kwargs:i,response_metadata:a})},$d=t=>{let e=(t.summary.length>1?t.summary.reduce((r,n)=>{let o=r[r.length-1];return o.index===n.index?o.text+=n.text:r.push(n),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([n])=>n!=="index")));return{...t,summary:e}},Li=t=>{let e=[],r={},n,o=[],s={model_provider:"openai"},a={},i;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:[Nd(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){i=t.item.id;let u="phase"in t.item?t.item.phase:void 0;u&&e.push({type:"text",text:"",phase:u,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[na]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),a.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}}),a.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))a.tool_outputs=[t.item];else if(t.type==="response.created")s.id=t.response.id,s.model_name=t.response.model,s.model=t.response.model;else if(t.type==="response.completed"){let u=oa(t.response);n=$i(t.response.usage),t.response.text?.format?.type==="json_schema"&&u.text&&(a.parsed??=JSON.parse(u.text));for(let[l,c]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=u.response_metadata.output:s[l]=c)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")o.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")a.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let u=t.item.summary?t.item.summary.map((c,p)=>({...c,index:p})):void 0;a.reasoning={id:t.item.id,type:t.item.type,...u?{summary:u}:{}};let l=t.item.summary?.map(c=>c.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")a.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")a.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 co({text:e.map(u=>u.text).join(""),message:new et({id:i,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:a,response_metadata:s}),generationInfo:r})},Ld=t=>{let e=R.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Ne(()=>{try{let h=mt(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"assistant"}catch{return"assistant"}}),o,s=new Set,a=new Set,i=new Map,u=new Map;function*l(){if(!o)return;let h=o.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield o),o=void 0}let c=(h,b)=>{o||(o={type:"message",role:n,content:[],...b?{phase:b}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...h]:[...h]:o.content.push(...h)},p=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},m=h=>{let b=Ne(()=>{let S=h.metadata?.detail;return S==="low"||S==="high"||S==="auto"?S:"auto"});if(h.fileId)return{type:"input_image",detail:b,file_id:h.fileId};if(h.url)return{type:"input_image",detail:b,image_url:h.url};if(h.data){let S=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_image",detail:b,image_url:`data:${h.mimeType??"image/png"};base64,${S}`}}},g=h=>{if(h.fileId){let b=Si(h);return{type:"input_file",file_id:h.fileId,...b?{filename:b}:{}}}if(h.url){let b=Si(h);return{...b?{filename:b}:{},type:"input_file",file_url:h.url}}if(h.data){let b=Vn(h),S=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,${S}`,filename:b}}},y=h=>{let b=Ne(()=>{if(Array.isArray(h.summary)){let Q=h.summary?.map(G=>G?.text).filter(G=>typeof G=="string")??[];if(Q.length>0)return Q}return h.reasoning?[h.reasoning]:[]}),S=b.length>0?b.map(Q=>({type:"summary_text",text:Q})):[{type:"summary_text",text:""}],j={type:"reasoning",id:h.id??"",summary:S};return h.reasoning&&(j.content=[{type:"reasoning_text",text:h.reasoning}]),j},A=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:p(h.args)}),C=h=>{let b=p(h.output),S=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:b,...S?{status:S}:{}}};for(let h of t.contentBlocks)if(h.type==="text"){let b=Ne(()=>{if("extras"in h&&typeof h.extras=="object"&&h.extras!==null&&"phase"in h.extras)return h.extras.phase});c([{type:"input_text",text:h.text}],b)}else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*l(),yield y(h);else if(h.type==="tool_call"){yield*l();let b=h.id??"";b&&(s.add(b),i.delete(b)),yield A(h)}else if(h.type==="tool_call_chunk"){if(h.id){let b=i.get(h.id)??{name:h.name,args:[]};h.name&&(b.name=h.name),h.args&&b.args.push(h.args),i.set(h.id,b)}}else if(h.type==="server_tool_call"){yield*l();let b=h.id??"";b&&(a.add(b),u.delete(b)),yield A(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){let b=u.get(h.id)??{name:h.name,args:[]};h.name&&(b.name=h.name),h.args&&b.args.push(h.args),u.set(h.id,b)}}else if(h.type==="server_tool_call_result")yield*l(),yield C(h);else if(h.type!=="audio")if(h.type==="file"){let b=g(h);b&&c([b])}else if(h.type==="image"){let b=m(h);b&&c([b])}else if(h.type==="video"){let b=g(h);b&&c([b])}else h.type==="text-plain"?h.text&&c([{type:"input_text",text:h.text}]):h.type==="non_standard"&&e&&(yield*l(),yield h.value)}yield*l();for(let[h,b]of i){if(!h||s.has(h))continue;let S=b.args.join("");!b.name&&!S||(yield{type:"function_call",call_id:h,name:b.name??"",arguments:S})}for(let[h,b]of u){if(!h||a.has(h))continue;let S=b.args.join("");!b.name&&!S||(yield{type:"function_call",call_id:h,name:b.name??"",arguments:S})}}return Array.from(r())},sa=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return Ld(n);let s=n.additional_kwargs,a=mt(n);if(a==="system"&&pt(r)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){let i=n;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof i.content=="string")return{type:"input_image",image_url:i.content};if(Array.isArray(i.content)){let l=i.content.find(m=>m.type==="input_image");if(l)return l;let c=i.content.find(m=>m.type==="computer_screenshot");if(c)return c;let p=i.content.find(m=>m.type==="image_url");if(p)return{type:"input_image",image_url:typeof p.image_url=="string"?p.image_url:p.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:i.tool_call_id};if(i.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:i.tool_call_id,output:i.content};let u=Array.isArray(i.content)&&i.content.every(l=>typeof l=="object"&&l!==null&&"type"in l&&(l.type==="input_file"||l.type==="input_image"||l.type==="input_text"));return{type:"function_call_output",call_id:i.tool_call_id,id:i.id?.startsWith("fc_")?i.id:void 0,output:u?i.content:typeof i.content!="string"?JSON.stringify(i.content):i.content}}if(a==="assistant"){if(!e&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(y=>"type"in y))return o?.output;let i=[],u=s?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let y=$d(u);i.push(y)}let{content:c}=n;if(s?.refusal&&(typeof c=="string"&&(c=[{type:"output_text",text:c,annotations:[]}]),c=[...c,{type:"refusal",refusal:s.refusal}]),typeof c=="string"||c.length>0){let y={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:Ne(()=>typeof c=="string"?c:c.flatMap(A=>{if(A.type==="text"){let C=A;return{type:"output_text",text:C.text,annotations:(C.annotations??[]).map(Rh)}}return A.type==="output_text"||A.type==="refusal"?A:[]})),phase:Ne(()=>{if(Array.isArray(c))return c.find(A=>"phase"in A&&typeof A.phase=="string")?.phase})};i.push(y)}let p=s?.[na];R.isInstance(n)&&n.tool_calls?.length?i.push(...n.tool_calls.map(y=>Lc(y)?{type:"custom_tool_call",id:y.call_id,call_id:y.id??"",input:y.args.input,name:y.name}:$c(y)?{type:"computer_call",id:y.call_id,call_id:y.id??"",action:y.args.action}:{type:"function_call",name:y.name,arguments:JSON.stringify(y.args),call_id:y.id,...e?{}:{id:p?.[y.id]}})):s?.tool_calls&&i.push(...s.tool_calls.map(y=>({type:"function_call",name:y.function.name,call_id:y.id,arguments:y.function.arguments,...e?{}:{id:p?.[y.id]}})));let m=o?.output?.length?o?.output:s.tool_outputs,g=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(m!=null){let y=m?.filter(A=>g.includes(A.type));y.length>0&&i.push(...y)}return i}if(a==="user"||a==="system"||a==="developer"){if(typeof n.content=="string")return{type:"message",role:a,content:n.content};let i=[],u=n.content.flatMap(l=>(l.type==="mcp_approval_response"&&i.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),ts(l)?rs(l,ta):l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Ne(()=>{if(typeof l.image_url=="string")return l.image_url;if(typeof l.image_url=="object"&&l.image_url!==null&&"url"in l.image_url)return l.image_url.url}),detail:Ne(()=>{if(typeof l.image_url=="string")return"auto";if(typeof l.image_url=="object"&&l.image_url!==null&&"detail"in l.image_url)return l.image_url.detail})}:l.type==="input_text"||l.type==="input_image"||l.type==="input_file"?l:[]));return u.length>0&&i.push({type:"message",role:a,content:u}),i}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});var aa=class extends Sr{constructor(t,e){super(Hn(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:Pc(t?.tool_choice)?t?.tool_choice:(()=>{let o=Qs(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,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},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let o=this._streamResponseChunks(t,e,r),s;for await(let a of o)a.message.response_metadata={...a.generationInfo,...a.message.response_metadata},s=s?.concat(a)??a;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let o=await this.completionWithRetry({input:sa({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:oa(o)}],llmOutput:{id:o.id,estimatedTokenUsage:o.usage?{promptTokens:o.usage.input_tokens,completionTokens:o.usage.output_tokens,totalTokens:o.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:sa({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(let o of n){if(e.signal?.aborted)return;let s=Li(o);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}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(n){throw Qe(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if(Gn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(Ir(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(us(n)){let o={};for(let[s,a]of Object.entries(n))s!=="type"&&s!=="function"&&(o[s]=a);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...o})}else Ys(n)&&r.push(jc(n));return r}};var ia=class jd extends Sr{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 n=Hn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new aa(n),this.completions=n?.completions??new ra(n)}_useResponsesApi(e){let r=e?.tools?.some(Gn),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,o=e?.tools?.some(Ys)||e?.tools?.some(Ir);return this.useResponsesApi||r||n||o||Tc(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,n){return this._useResponsesApi(r)?this.responses._generate(e,r,n):this.completions._generate(e,r,n)}async*_streamResponseChunks(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),n)}withConfig(e){let r=new jd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var zh=I.object({type:I.literal("screenshot")}),Dh=I.object({type:I.literal("click"),x:I.number(),y:I.number(),button:I.enum(["left","right","wheel","back","forward"]).default("left")}),Fh=I.object({type:I.literal("double_click"),x:I.number(),y:I.number(),button:I.enum(["left","right","wheel","back","forward"]).default("left")}),qh=I.object({type:I.literal("drag"),path:I.array(I.object({x:I.number(),y:I.number()}))}),Uh=I.object({type:I.literal("keypress"),keys:I.array(I.string())}),Bh=I.object({type:I.literal("move"),x:I.number(),y:I.number()}),Kh=I.object({type:I.literal("scroll"),x:I.number(),y:I.number(),scroll_x:I.number(),scroll_y:I.number()}),Wh=I.object({type:I.literal("type"),text:I.string()}),Vh=I.object({type:I.literal("wait"),duration:I.number().optional()}),Gh=I.union([zh,Dh,Fh,qh,Uh,Bh,Kh,Wh,Vh]),K1=I.object({action:Gh});var Hh=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()}),H1=I.union([Hh]);var Y1=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 Jh=I.object({type:I.literal("create_file"),path:I.string(),diff:I.string()}),Zh=I.object({type:I.literal("update_file"),path:I.string(),diff:I.string()}),Qh=I.object({type:I.literal("delete_file"),path:I.string()}),rq=I.union([Jh,Zh,Qh]);var Fd={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},tg={default:"text-embedding-ada-002"},ji=new Map,la=null,rg=()=>{let t=Dd.getDefault().helperServices;if(!t?.aiModels?.url)throw new Error("AI Models Service URL is not defined in the portal's helper services.");return t.aiModels.url},ng=async t=>{let e=rg();ji.size===0&&(la||(la=(async()=>{try{let n=await fetch(`${e}/models`);if(!n.ok)throw new Error("Failed to fetch AI service discovery data.");(await n.json()).models.forEach(o=>ji.set(o.name,o))}catch(n){throw la=null,n}})()),await la);let r=ji.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},og=async(t="default")=>await ng(Fd[t]);var Zn=(t,e)=>e,qd=(t,e)=>({...t,...e}),Ud=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let o=n.split(`
94
+ ]`;continue}s+=o[l],o[l]==="\\"?a=!0:i&&o[l]==="]"?i=!1:!i&&o[l]==="["&&(i=!0)}try{let l=new RegExp(s)}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 s};function ea(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===q.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:P(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:P(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===q.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Xs(t.keyType._def,e)).reduce((o,[s,a])=>s==="type"?o:{...o,[s]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===q.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function rd(t,e){if(e.mapStrategy==="record")return ea(t,e);let r=P(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=P(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function nd(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function od(){return{not:{}}}function sd(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ko={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function id(t,e){if(e.target==="openApi3")return ad(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ko&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let a=Ko[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return ad(t,e)}var ad=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>P(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function ld(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:Ko[t.innerType._def.typeName],nullable:!0}:{type:[Ko[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=P(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=P(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function ud(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Ci(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?V(r,"minimum",n.value,n.message,e):V(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),V(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?V(r,"maximum",n.value,n.message,e):V(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),V(r,"maximum",n.value,n.message,e));break;case"multipleOf":V(r,"multipleOf",n.value,n.message,e);break}return r}function xh(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":P(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":P(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function cd(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,s])=>{if(s===void 0||s._def===void 0)return n;let a=[...e.currentPath,"properties",o],i=P(s._def,{...e,currentPath:a,propertyPath:a});if(i===void 0)return n;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${a.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:{...n.properties,[o]:i},required:s.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]}},{properties:{},required:[]}),additionalProperties:xh(t,e)};return r.required.length||delete r.required,r}var dd=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return P(t.innerType._def,{...e,currentPath:e.currentPath});let r=P(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}};var pd=(t,e)=>{if(e.pipeStrategy==="input")return P(t.in._def,e);if(e.pipeStrategy==="output")return P(t.out._def,e);let r=P(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=P(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function md(t,e){return P(t.type._def,e)}function fd(t,e){let n={type:"array",uniqueItems:!0,items:P(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&V(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&V(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function hd(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>P(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:P(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>P(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function gd(){return{not:{}}}function yd(){return{}}var _d=(t,e)=>P(t.innerType._def,e);function P(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Fc)return a}if(n&&!r){let a=Ah(n,e);if(a!==void 0)return"$ref"in a&&e.seenRefs.add(a.$ref),a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=vh(t,t.typeName,e,r);return s&&Th(t,e,s),o.jsonSchema=s,s}var Ah=(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:Ih(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Ih=(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("/")},vh=(t,e,r,n)=>{switch(e){case q.ZodString:return Xs(t,r);case q.ZodNumber:return ud(t,r);case q.ZodObject:return cd(t,r);case q.ZodBigInt:return Vc(t,r);case q.ZodBoolean:return Gc();case q.ZodDate:return Ei(t,r);case q.ZodUndefined:return gd();case q.ZodNull:return sd(r);case q.ZodArray:return Wc(t,r);case q.ZodUnion:case q.ZodDiscriminatedUnion:return id(t,r);case q.ZodIntersection:return Xc(t,r);case q.ZodTuple:return hd(t,r);case q.ZodRecord:return ea(t,r);case q.ZodLiteral:return ed(t,r);case q.ZodEnum:return Yc(t);case q.ZodNativeEnum:return nd(t);case q.ZodNullable:return ld(t,r);case q.ZodOptional:return dd(t,r);case q.ZodMap:return rd(t,r);case q.ZodSet:return fd(t,r);case q.ZodLazy:return P(t.getter()._def,r);case q.ZodPromise:return md(t,r);case q.ZodNaN:case q.ZodNever:return od();case q.ZodEffects:return Qc(t,r,n);case q.ZodAny:return Kc();case q.ZodUnknown:return yd();case q.ZodDefault:return Zc(t,r);case q.ZodBranded:return Hc(t,r);case q.ZodReadonly:return _d(t,r);case q.ZodCatch:return Jc(t,r);case q.ZodPipeline:return pd(t,r);case q.ZodFunction:case q.ZodVoid:case q.ZodSymbol:return;default:return(o=>{})(e)}},Th=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Mi=(t,e)=>{let r=Bc(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=P(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let a=(()=>{if(Uc(r.definitions))return;let u={},l=new Set;for(let c=0;c<500;c++){let p=Object.entries(r.definitions).filter(([m])=>!l.has(m));if(p.length===0)break;for(let[m,g]of p)u[m]=P(Bo(g),{...r,currentPath:[...r.basePath,r.definitionPath,m]},!0)??{},l.add(m)}return u})(),i=n===void 0?a?{...o,[r.definitionPath]:a}:o:r.nameStrategy==="duplicate-ref"?{...o,...a||r.seenRefs.size?{[r.definitionPath]:{...a,...r.seenRefs.size?{[n]:o}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...a,[n]:o}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),i};function wd(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 ft(e,[],e)}function Pi(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Pi(e))return!0;for(let e of t.anyOf??[])if(Pi(e))return!0;return!1}function ft(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!Tr(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(Tr(n))for(let[m,g]of Object.entries(n))ft(g,[...e,"$defs",m],r);let o=t.definitions;if(Tr(o))for(let[m,g]of Object.entries(o))ft(g,[...e,"definitions",m],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let a=t.required??[],i=t.properties;if(Tr(i)){for(let[m,g]of Object.entries(i))if(!Pi(g)&&!a.includes(m))throw new Error(`Zod field at \`${[...e,"properties",m].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(i),t.properties=Object.fromEntries(Object.entries(i).map(([m,g])=>[m,ft(g,[...e,"properties",m],r)]))}let u=t.items;Tr(u)&&(t.items=ft(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((m,g)=>ft(m,[...e,"anyOf",String(g)],r)));let c=t.allOf;if(Array.isArray(c))if(c.length===1){let m=ft(c[0],[...e,"allOf","0"],r);Object.assign(t,m),delete t.allOf}else t.allOf=c.map((m,g)=>ft(m,[...e,"allOf",String(g)],r));t.default===null&&delete t.default;let p=t.$ref;if(p&&kh(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);let m=Sh(r,p);if(typeof m=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!Tr(m))throw new Error(`Expected \`$ref: ${p}\` to resolve to an object but got ${JSON.stringify(m)}`);return Object.assign(t,{...m,...t}),delete t.$ref,ft(t,e,r)}return t}function Sh(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),n=t;for(let o of r){if(!Tr(n))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(n)}`);let s=n[o];if(s===void 0)throw new Error(`Key ${o} not found while resolving ${e}`);n=s}return n}function Tr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function kh(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function Ch(t,e){return Mi(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Eh(t){return wd(Sl(t,{target:"draft-7"}))}function Oh(t){return"_zod"in t}function bd(t,e,r){return Yu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Oh(t)?Eh(t):Ch(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var xd=["jsonSchema","functionCalling","jsonMode"];function Ad(t,e){if(typeof e<"u"&&!xd.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${xd.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 Mh(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Id(t,e,r){if(kl(t))return bd(t,e,r);if(Mr(t))return Mh({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Fe(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>vl(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function vd(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(n=>typeof n?.image_url?.url=="string").map(n=>({type:"image",url:n.image_url.url}));return[{type:"text",text:t},...r]}return t}var Td={"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 Hn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var Sr=class extends po{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??Xe("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??Xe("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(!pt(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&&tt(t.json_schema.schema)?Id(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=Kt({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=Wt(r.defaultHeaders),this.client=new M(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return Ir(t)?zc(t.metadata.customTool):us(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Cc(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(n=>{if(Gn(n)||Ir(n))return n;if(Mc(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return fo(n)&&n.extras?.defer_loading===!0?{...o,defer_loading:!0}:o}),...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,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let o=await Promise.all(t.map(async s=>{let[a,i]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(mt(s))]),u=s.name!==void 0?n+await this.getNumTokens(s.name):0,l=a+r+i+u,c=s;if(c._getType()==="function"&&(l-=2),c.additional_kwargs?.function_call&&(l+=3),c?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(p){console.error("Error parsing function arguments",p,JSON.stringify(c.additional_kwargs.function_call)),l+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:o}}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 n=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let o=Ec(e);n+=await this.getNumTokens(o),n+=9}return e&&t.find(o=>o._getType()==="system")&&(n-=4),r==="none"?n+=1:typeof r=="object"&&(n+=await this.getNumTokens(r.name)+4),n}async moderateContent(t,e){let r=this._getClientOptions(e?.options),n={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(n,r)}catch(o){throw Qe(o)}})}get profile(){return Td[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,n,{schema:o,name:s,includeRaw:a}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let i=Ad(this.model,e?.method);if(i==="jsonMode"){n=Ca(o);let u=Fe(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...u}}})}else if(i==="jsonSchema"){let u=Fe(o),l={name:s??"extract",description:as(u),schema:tt(o)?o:u,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:l.name,description:l.description,...u}}}),tt(o)||_t(o)){let c=Ca(o);n=qe.from(async p=>"parsed"in p.additional_kwargs?p.additional_kwargs.parsed:c.invoke(p.content))}else n=new Pl}else{let u=s??"extract",l=Fe(o),c;tt(o)||_t(o)?c={name:u,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(c=o,u=o.name):(u=o.title??u,c={name:u,description:o.description??"",parameters:o}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:c}],tool_choice:{type:"function",function:{name:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...l}},...e?.strict!==void 0?{strict:e.strict}:{}}),n=Nl(o,u)}return $l(r,n,a)}};var ta={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=Aa({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||"",n;try{n=xa(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.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:n.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=xa(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=Aa({dataUrl:t.url}),r=Vn(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=Vn(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`)}},Ri=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let s=[],a=[];for(let l of n??[])try{s.push(cs(l,{returnId:!0}))}catch(c){a.push(Rr(l,c.message))}let i={function_call:t.function_call,tool_calls:n};r!==void 0&&(i.__raw_response=e),o!==void 0&&(i.reasoning_content=o);let u={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(i.audio=t.audio),new R({content:vd(t.content||"",e.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:a,additional_kwargs:i,response_metadata:u,id:e.id})}default:return new ns(t.content||"",t.role??"unknown")}},Ni=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let o=t.role??n,s=t.content??"",a;t.function_call?a={function_call:t.function_call}:t.tool_calls?a={tool_calls:t.tool_calls}:a={},r&&(a.__raw_response=e),t.reasoning_content!==void 0&&(a.reasoning_content=t.reasoning_content),t.audio&&(a.audio={...t.audio,index:e.choices[0].index});let i={model_provider:"openai",usage:{...e.usage}};if(o==="user")return new Ta({content:s,response_metadata:i});if(o==="assistant"){let u=[];if(Array.isArray(t.tool_calls))for(let l of t.tool_calls)u.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new et({content:s,tool_call_chunks:u,additional_kwargs:a,id:e.id,response_metadata:i})}else return o==="system"?new os({content:s,response_metadata:i}):o==="developer"?new os({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new wl({content:s,additional_kwargs:a,name:t.name,response_metadata:i}):o==="tool"?new va({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:i}):new _l({content:s,role:o,response_metadata:i})},Sd=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=bl(()=>{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=Vn(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}}}},kd=({message:t,model:e})=>{let r=mt(t);if(r==="system"&&pt(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="assistant")return{role:"assistant",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="tool"&&U.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")};function*n(o){for(let s of o){s.type==="text"&&(yield{type:"text",text:s.text});let a=Sd(s);a&&(yield a)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},Wo=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return kd({message:r});let n=mt(r);n==="system"&&pt(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(a=>ts(a)?rs(a,ta):typeof a=="object"&&a!==null&&"type"in a&&a.type==="tool_use"?[]:a),s={role:n,content:o};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),R.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Rl):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),U.isInstance(r)&&r.tool_call_id!=null&&(s.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[s,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:s});var ra=class extends Sr{constructor(t,e){super(Hn(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={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(a=>this._convertChatOpenAIToolToCompletionsTool(a,{strict:r})):void 0,tool_choice:Qs(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...n,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&&(o.prediction=t.prediction),this.service_tier!==void 0&&(o.service_tier=this.service_tier),t?.service_tier!==void 0&&(o.service_tier=t.service_tier);let s=this._getReasoningParams(t);return s!==void 0&&s.effort!==void 0&&(o.reasoning_effort=s.effort),pt(o.model)?o.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:o.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,o}async _generate(t,e,r){e.signal?.throwIfAborted();let n={},o=this.invocationParams(e),s=Wo({messages:t,model:this.model});if(o.stream){let a=this._streamResponseChunks(t,e,r),i={};for await(let g of a){g.message.response_metadata={...g.generationInfo,...g.message.response_metadata};let y=g.generationInfo?.completion??0;i[y]===void 0?i[y]=g:i[y]=i[y].concat(g)}let u=Object.entries(i).sort(([g],[y])=>parseInt(g,10)-parseInt(y,10)).map(([g,y])=>y),{functions:l,function_call:c}=this.invocationParams(e),p=await this._getEstimatedTokenCountFromPrompt(t,l,c),m=await this._getNumTokensFromGenerations(u);return n.input_tokens=p,n.output_tokens=m,n.total_tokens=p+m,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let a=await this.completionWithRetry({...o,stream:!1,messages:s},{signal:e?.signal,...e?.options}),{completion_tokens:i,prompt_tokens:u,total_tokens:l,prompt_tokens_details:c,completion_tokens_details:p}=a?.usage??{};i&&(n.output_tokens=(n.output_tokens??0)+i),u&&(n.input_tokens=(n.input_tokens??0)+u),l&&(n.total_tokens=(n.total_tokens??0)+l),(c?.audio_tokens!==null||c?.cached_tokens!==null)&&(n.input_token_details={...c?.audio_tokens!==null&&{audio:c?.audio_tokens},...c?.cached_tokens!==null&&{cache_read:c?.cached_tokens}}),(p?.audio_tokens!==null||p?.reasoning_tokens!==null)&&(n.output_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.reasoning_tokens!==null&&{reasoning:p?.reasoning_tokens}});let m=[];for(let g of a?.choices??[]){let y={text:g.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(g.message??{role:"assistant"},a)};y.generationInfo={...g.finish_reason?{finish_reason:g.finish_reason}:{},...g.logprobs?{logprobs:g.logprobs}:{}},yt(y.message)&&(y.message.usage_metadata=n),y.message=new R(Object.fromEntries(Object.entries(y.message).filter(([A])=>!A.startsWith("lc_")))),m.push(y)}return{generations:m,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamResponseChunks(t,e,r){let n=Wo({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s,a=await this.completionWithRetry(o,e),i;for await(let u of a){if(e.signal?.aborted)return;let l=u?.choices?.[0];if(u.usage&&(i=u.usage),!l)continue;let{delta:c}=l;if(!c)continue;let p=this._convertCompletionsDeltaToBaseMessageChunk(c,u,s);s=c.role??s;let m={prompt:e.promptIndex??0,completion:l.index??0};if(typeof p.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let g={...m};l.finish_reason!=null&&(g.finish_reason=l.finish_reason,g.system_fingerprint=u.system_fingerprint,g.model_name=u.model,g.service_tier=u.service_tier),this.logprobs&&(g.logprobs=l.logprobs);let y=new co({message:p,text:p.content,generationInfo:g});yield y,await r?.handleLLMNewToken(y.text??"",m,void 0,void 0,void 0,{chunk:y})}if(i){let u={...i.prompt_tokens_details?.audio_tokens!==null&&{audio:i.prompt_tokens_details?.audio_tokens},...i.prompt_tokens_details?.cached_tokens!==null&&{cache_read:i.prompt_tokens_details?.cached_tokens}},l={...i.completion_tokens_details?.audio_tokens!==null&&{audio:i.completion_tokens_details?.audio_tokens},...i.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:i.completion_tokens_details?.reasoning_tokens}},c=new co({message:new et({content:"",response_metadata:{usage:{...i}},usage_metadata:{input_tokens:i.prompt_tokens,output_tokens:i.completion_tokens,total_tokens:i.total_tokens,...Object.keys(u).length>0&&{input_token_details:u},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield c,await r?.handleLLMNewToken(c.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:c})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=this._getClientOptions(e),n=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(o){throw Qe(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return Ni({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Ri({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var na="__openai_function_call_ids__";function Nd(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 Rh(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 $i=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}},oa=t=>{if(t.error){let u=new Error(t.error.message);throw u.name=t.error.code,u}let e,r=[],n=[],o=[],s=t.output.map(u=>{if(u.type==="function_call"&&"parsed_arguments"in u){let l={...u};return delete l.parsed_arguments,l}return u}),a={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:s,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},i={};for(let u of t.output)if(u.type==="message")e=u.id,r.push(...u.content.flatMap(l=>l.type==="output_text"?("parsed"in l&&l.parsed!=null&&(i.parsed=l.parsed),{type:"text",text:l.text,annotations:l.annotations.map(Nd),...u.phase!==null?{phase:u.phase}:{}}):l.type==="refusal"?(i.refusal=l.refusal,[]):l));else if(u.type==="function_call"){let l={function:{name:u.name,arguments:u.arguments},id:u.call_id};try{n.push(cs(l,{returnId:!0}))}catch(c){let p;typeof c=="object"&&c!=null&&"message"in c&&typeof c.message=="string"&&(p=c.message),o.push(Rr(l,p))}i[na]??={},u.id&&(i[na][u.call_id]=u.id)}else if(u.type==="reasoning"){i.reasoning=u;let l=u.summary?.map(c=>c.text).filter(Boolean).join("");l&&r.push({type:"reasoning",reasoning:l})}else if(u.type==="custom_tool_call"){let l=Rc(u);l?n.push(l):o.push(Rr(u,"Malformed custom tool call"))}else if(u.type==="computer_call"){let l=Nc(u);l?n.push(l):o.push(Rr(u,"Malformed computer call"))}else u.type==="image_generation_call"?(u.result&&r.push({type:"image",mimeType:"image/png",data:u.result,id:u.id,metadata:{status:u.status}}),i.tool_outputs??=[],i.tool_outputs.push(u)):(i.tool_outputs??=[],i.tool_outputs.push(u));return new R({id:e,content:r,tool_calls:n,invalid_tool_calls:o,usage_metadata:$i(t.usage),additional_kwargs:i,response_metadata:a})},$d=t=>{let e=(t.summary.length>1?t.summary.reduce((r,n)=>{let o=r[r.length-1];return o.index===n.index?o.text+=n.text:r.push(n),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([n])=>n!=="index")));return{...t,summary:e}},Li=t=>{let e=[],r={},n,o=[],s={model_provider:"openai"},a={},i;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:[Nd(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){i=t.item.id;let u="phase"in t.item?t.item.phase:void 0;u&&e.push({type:"text",text:"",phase:u,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[na]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),a.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}}),a.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))a.tool_outputs=[t.item];else if(t.type==="response.created")s.id=t.response.id,s.model_name=t.response.model,s.model=t.response.model;else if(t.type==="response.completed"){let u=oa(t.response);n=$i(t.response.usage),t.response.text?.format?.type==="json_schema"&&u.text&&(a.parsed??=JSON.parse(u.text));for(let[l,c]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=u.response_metadata.output:s[l]=c)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")o.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")a.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let u=t.item.summary?t.item.summary.map((c,p)=>({...c,index:p})):void 0;a.reasoning={id:t.item.id,type:t.item.type,...u?{summary:u}:{}};let l=t.item.summary?.map(c=>c.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")a.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")a.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 co({text:e.map(u=>u.text).join(""),message:new et({id:i,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:a,response_metadata:s}),generationInfo:r})},Ld=t=>{let e=R.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Ne(()=>{try{let h=mt(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"assistant"}catch{return"assistant"}}),o,s=new Set,a=new Set,i=new Map,u=new Map;function*l(){if(!o)return;let h=o.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield o),o=void 0}let c=(h,b)=>{o||(o={type:"message",role:n,content:[],...b?{phase:b}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...h]:[...h]:o.content.push(...h)},p=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},m=h=>{let b=Ne(()=>{let S=h.metadata?.detail;return S==="low"||S==="high"||S==="auto"?S:"auto"});if(h.fileId)return{type:"input_image",detail:b,file_id:h.fileId};if(h.url)return{type:"input_image",detail:b,image_url:h.url};if(h.data){let S=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_image",detail:b,image_url:`data:${h.mimeType??"image/png"};base64,${S}`}}},g=h=>{if(h.fileId){let b=Si(h);return{type:"input_file",file_id:h.fileId,...b?{filename:b}:{}}}if(h.url){let b=Si(h);return{...b?{filename:b}:{},type:"input_file",file_url:h.url}}if(h.data){let b=Vn(h),S=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,${S}`,filename:b}}},y=h=>{let b=Ne(()=>{if(Array.isArray(h.summary)){let Q=h.summary?.map(G=>G?.text).filter(G=>typeof G=="string")??[];if(Q.length>0)return Q}return h.reasoning?[h.reasoning]:[]}),S=b.length>0?b.map(Q=>({type:"summary_text",text:Q})):[{type:"summary_text",text:""}],j={type:"reasoning",id:h.id??"",summary:S};return h.reasoning&&(j.content=[{type:"reasoning_text",text:h.reasoning}]),j},A=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:p(h.args)}),C=h=>{let b=p(h.output),S=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:b,...S?{status:S}:{}}};for(let h of t.contentBlocks)if(h.type==="text"){let b=Ne(()=>{if("extras"in h&&typeof h.extras=="object"&&h.extras!==null&&"phase"in h.extras)return h.extras.phase});c([{type:"input_text",text:h.text}],b)}else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*l(),yield y(h);else if(h.type==="tool_call"){yield*l();let b=h.id??"";b&&(s.add(b),i.delete(b)),yield A(h)}else if(h.type==="tool_call_chunk"){if(h.id){let b=i.get(h.id)??{name:h.name,args:[]};h.name&&(b.name=h.name),h.args&&b.args.push(h.args),i.set(h.id,b)}}else if(h.type==="server_tool_call"){yield*l();let b=h.id??"";b&&(a.add(b),u.delete(b)),yield A(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){let b=u.get(h.id)??{name:h.name,args:[]};h.name&&(b.name=h.name),h.args&&b.args.push(h.args),u.set(h.id,b)}}else if(h.type==="server_tool_call_result")yield*l(),yield C(h);else if(h.type!=="audio")if(h.type==="file"){let b=g(h);b&&c([b])}else if(h.type==="image"){let b=m(h);b&&c([b])}else if(h.type==="video"){let b=g(h);b&&c([b])}else h.type==="text-plain"?h.text&&c([{type:"input_text",text:h.text}]):h.type==="non_standard"&&e&&(yield*l(),yield h.value)}yield*l();for(let[h,b]of i){if(!h||s.has(h))continue;let S=b.args.join("");!b.name&&!S||(yield{type:"function_call",call_id:h,name:b.name??"",arguments:S})}for(let[h,b]of u){if(!h||a.has(h))continue;let S=b.args.join("");!b.name&&!S||(yield{type:"function_call",call_id:h,name:b.name??"",arguments:S})}}return Array.from(r())},sa=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return Ld(n);let s=n.additional_kwargs,a=mt(n);if(a==="system"&&pt(r)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){let i=n;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof i.content=="string")return{type:"input_image",image_url:i.content};if(Array.isArray(i.content)){let l=i.content.find(m=>m.type==="input_image");if(l)return l;let c=i.content.find(m=>m.type==="computer_screenshot");if(c)return c;let p=i.content.find(m=>m.type==="image_url");if(p)return{type:"input_image",image_url:typeof p.image_url=="string"?p.image_url:p.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:i.tool_call_id};if(i.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:i.tool_call_id,output:i.content};let u=Array.isArray(i.content)&&i.content.every(l=>typeof l=="object"&&l!==null&&"type"in l&&(l.type==="input_file"||l.type==="input_image"||l.type==="input_text"));return{type:"function_call_output",call_id:i.tool_call_id,id:i.id?.startsWith("fc_")?i.id:void 0,output:u?i.content:typeof i.content!="string"?JSON.stringify(i.content):i.content}}if(a==="assistant"){if(!e&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(y=>"type"in y))return o?.output;let i=[],u=s?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let y=$d(u);i.push(y)}let{content:c}=n;if(s?.refusal&&(typeof c=="string"&&(c=[{type:"output_text",text:c,annotations:[]}]),c=[...c,{type:"refusal",refusal:s.refusal}]),typeof c=="string"||c.length>0){let y={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:Ne(()=>typeof c=="string"?c:c.flatMap(A=>{if(A.type==="text"){let C=A;return{type:"output_text",text:C.text,annotations:(C.annotations??[]).map(Rh)}}return A.type==="output_text"||A.type==="refusal"?A:[]})),phase:Ne(()=>{if(Array.isArray(c))return c.find(A=>"phase"in A&&typeof A.phase=="string")?.phase})};i.push(y)}let p=s?.[na];R.isInstance(n)&&n.tool_calls?.length?i.push(...n.tool_calls.map(y=>Lc(y)?{type:"custom_tool_call",id:y.call_id,call_id:y.id??"",input:y.args.input,name:y.name}:$c(y)?{type:"computer_call",id:y.call_id,call_id:y.id??"",action:y.args.action}:{type:"function_call",name:y.name,arguments:JSON.stringify(y.args),call_id:y.id,...e?{}:{id:p?.[y.id]}})):s?.tool_calls&&i.push(...s.tool_calls.map(y=>({type:"function_call",name:y.function.name,call_id:y.id,arguments:y.function.arguments,...e?{}:{id:p?.[y.id]}})));let m=o?.output?.length?o?.output:s.tool_outputs,g=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(m!=null){let y=m?.filter(A=>g.includes(A.type));y.length>0&&i.push(...y)}return i}if(a==="user"||a==="system"||a==="developer"){if(typeof n.content=="string")return{type:"message",role:a,content:n.content};let i=[],u=n.content.flatMap(l=>(l.type==="mcp_approval_response"&&i.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),ts(l)?rs(l,ta):l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Ne(()=>{if(typeof l.image_url=="string")return l.image_url;if(typeof l.image_url=="object"&&l.image_url!==null&&"url"in l.image_url)return l.image_url.url}),detail:Ne(()=>{if(typeof l.image_url=="string")return"auto";if(typeof l.image_url=="object"&&l.image_url!==null&&"detail"in l.image_url)return l.image_url.detail})}:l.type==="input_text"||l.type==="input_image"||l.type==="input_file"?l:[]));return u.length>0&&i.push({type:"message",role:a,content:u}),i}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});var aa=class extends Sr{constructor(t,e){super(Hn(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:Pc(t?.tool_choice)?t?.tool_choice:(()=>{let o=Qs(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,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},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let o=this._streamResponseChunks(t,e,r),s;for await(let a of o)a.message.response_metadata={...a.generationInfo,...a.message.response_metadata},s=s?.concat(a)??a;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let o=await this.completionWithRetry({input:sa({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:oa(o)}],llmOutput:{id:o.id,estimatedTokenUsage:o.usage?{promptTokens:o.usage.input_tokens,completionTokens:o.usage.output_tokens,totalTokens:o.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:sa({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(let o of n){if(e.signal?.aborted)return;let s=Li(o);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}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(n){throw Qe(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if(Gn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(Ir(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(us(n)){let o={};for(let[s,a]of Object.entries(n))s!=="type"&&s!=="function"&&(o[s]=a);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...o})}else Ys(n)&&r.push(jc(n));return r}};var ia=class jd extends Sr{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 n=Hn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new aa(n),this.completions=n?.completions??new ra(n)}_useResponsesApi(e){let r=e?.tools?.some(Gn),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,o=e?.tools?.some(Ys)||e?.tools?.some(Ir);return this.useResponsesApi||r||n||o||Tc(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,n){return this._useResponsesApi(r)?this.responses._generate(e,r,n):this.completions._generate(e,r,n)}async*_streamResponseChunks(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),n)}withConfig(e){let r=new jd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var zh=I.object({type:I.literal("screenshot")}),Dh=I.object({type:I.literal("click"),x:I.number(),y:I.number(),button:I.enum(["left","right","wheel","back","forward"]).default("left")}),Fh=I.object({type:I.literal("double_click"),x:I.number(),y:I.number(),button:I.enum(["left","right","wheel","back","forward"]).default("left")}),qh=I.object({type:I.literal("drag"),path:I.array(I.object({x:I.number(),y:I.number()}))}),Uh=I.object({type:I.literal("keypress"),keys:I.array(I.string())}),Bh=I.object({type:I.literal("move"),x:I.number(),y:I.number()}),Kh=I.object({type:I.literal("scroll"),x:I.number(),y:I.number(),scroll_x:I.number(),scroll_y:I.number()}),Wh=I.object({type:I.literal("type"),text:I.string()}),Vh=I.object({type:I.literal("wait"),duration:I.number().optional()}),Gh=I.union([zh,Dh,Fh,qh,Uh,Bh,Kh,Wh,Vh]),W1=I.object({action:Gh});var Hh=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()}),J1=I.union([Hh]);var X1=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 Jh=I.object({type:I.literal("create_file"),path:I.string(),diff:I.string()}),Zh=I.object({type:I.literal("update_file"),path:I.string(),diff:I.string()}),Qh=I.object({type:I.literal("delete_file"),path:I.string()}),nq=I.union([Jh,Zh,Qh]);var Fd={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},rg={default:"text-embedding-ada-002"},ji=new Map,la=null,ng=()=>{let t=Dd.getDefault().helperServices;if(!t?.aiModels?.url)throw new Error("AI Models Service URL is not defined in the portal's helper services.");return t.aiModels.url},og=async t=>{let e=ng();ji.size===0&&(la||(la=(async()=>{try{(await Xh(`${e}/models`)).data.models.forEach(n=>ji.set(n.name,n))}catch(n){throw la=null,n}})()),await la);let r=ji.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},sg=async(t="default")=>await og(Fd[t]);var Zn=(t,e)=>e,qd=(t,e)=>({...t,...e}),Ud=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let o=n.split(`
95
95
 
96
96
  `);return o[o.length-1]?.trim()===r?t:`${t}
97
97
 
98
- ${r}`},Bd=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),kr=()=>({agentExecutionContext:N({reducer:qd,default:Bd}),outputMessage:N({reducer:Ud,default:()=>""}),summary:N({reducer:Zn,default:()=>""}),status:N({reducer:Zn})}),ua=()=>({...kr(),sharedStatePatch:N({reducer:Zn})}),sg=N.Root({agentExecutionContext:N({default:Bd,reducer:qd}),currentIntent:N({default:()=>"none",reducer:Zn}),lastExecutedAgent:N({default:()=>"",reducer:Zn}),requiresFollowUp:N({default:()=>!0,reducer:Zn}),stepCount:N({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:N({default:()=>"",reducer:Ud})});var ag=t=>typeof t=="string"&&t.length>0?t:void 0,ig=()=>ll(),lg=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,ug=t=>{let e=t?.configurable;return{conversationId:ag(e?.thread_id),abortSignal:t?.signal,requestId:ig(),requestSource:lg(eg.applicationName)}},cg=async({config:t})=>{let e=Dd.getDefault(),r=(await Xh.getCredential(`${e.url}/sharing`))?.token;return async(n,o)=>{let{conversationId:s,abortSignal:a,requestId:i,requestSource:u}=ug(t),l=new Headers(o?.headers);l.delete("Authorization"),l.delete("api-key"),r&&r.length>0&&(l.set("X-Esri-Authorization",`Bearer ${r}`),l.set("X-Esri-Request-Source",u)),s&&s.length>0&&l.set("X-Esri-Conversation-Id",s),i.length>0&&l.set("X-Esri-Request-Id",i);let c=a&&o?.signal?AbortSignal.any([a,o.signal]):o?.signal??a;return await fetch(n,{...o,headers:l,signal:c})}},zi=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:n}=t,o=Fd[e],s=await og(e);return new ia({modelName:o,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:s,fetch:await cg({config:n})}})};var dg=I.object({id:I.string().min(1),name:I.string().min(1),description:I.string().min(1)});I.array(dg);var Kd="0.1",Jn=1536,Wd="openai",Vd=tg.default,Gd=`Name: {name}
98
+ ${r}`},Bd=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),kr=()=>({agentExecutionContext:N({reducer:qd,default:Bd}),outputMessage:N({reducer:Ud,default:()=>""}),summary:N({reducer:Zn,default:()=>""}),status:N({reducer:Zn})}),ua=()=>({...kr(),sharedStatePatch:N({reducer:Zn})}),ag=N.Root({agentExecutionContext:N({default:Bd,reducer:qd}),currentIntent:N({default:()=>"none",reducer:Zn}),lastExecutedAgent:N({default:()=>"",reducer:Zn}),requiresFollowUp:N({default:()=>!0,reducer:Zn}),stepCount:N({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:N({default:()=>"",reducer:Ud})});var ig=t=>typeof t=="string"&&t.length>0?t:void 0,lg=()=>ll(),ug=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,cg=t=>{let e=t?.configurable;return{conversationId:ig(e?.thread_id),abortSignal:t?.signal,requestId:lg(),requestSource:ug(tg.applicationName)}},dg=async({config:t})=>{let e=Dd.getDefault(),r=(await eg.getCredential(`${e.url}/sharing`))?.token;return async(n,o)=>{let{conversationId:s,abortSignal:a,requestId:i,requestSource:u}=cg(t),l=new Headers(o?.headers);for(let p of[...l.keys()]){let m=p.toLowerCase();(m==="authorization"||m==="api-key"||m.startsWith("x-stainless-"))&&l.delete(p)}r&&r.length>0&&l.set("X-Esri-Authorization",`Bearer ${r}`),e.isPortal||(u&&u.length>0&&l.set("X-Esri-Request-Source",u),s&&s.length>0&&l.set("X-Esri-Conversation-Id",s),i.length>0&&l.set("X-Esri-Request-Id",i));let c=a&&o?.signal?AbortSignal.any([a,o.signal]):o?.signal??a;return await fetch(n,{...o,headers:l,signal:c})}},zi=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:n}=t,o=Fd[e],s=await sg(e);return new ia({modelName:o,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:s,fetch:await dg({config:n})}})};var pg=I.object({id:I.string().min(1),name:I.string().min(1),description:I.string().min(1)});I.array(pg);var Kd="0.1",Jn=1536,Wd="openai",Vd=rg.default,Gd=`Name: {name}
99
99
  Title: {title}
100
100
  Description: {description}`,Hd=`Name: {name}
101
101
  Alias: {alias}
102
- Description: {description}`,Jd=I.object({schemaVersion:I.literal(Kd),modified:I.number().int().nonnegative(),embeddings:I.object({modelProvider:I.literal(Wd),model:I.literal(Vd),dimensions:I.literal(Jn),templates:I.object({layer:I.string().default(Gd),field:I.string().default(Hd)})}),layers:I.array(I.object({id:I.string().min(1),name:I.string().min(1),title:I.string().catch(""),description:I.string().catch(""),vector:I.array(I.number()).length(Jn,{message:`Layer vector must be exactly ${Jn} dimensions`}),fields:I.array(I.object({name:I.string().min(1),alias:I.string().catch(""),description:I.string().catch(""),vector:I.array(I.number()).length(Jn,{message:`Field vector must be exactly ${Jn} dimensions`})}))})).default([])});var pg=(t,e)=>{let r=Ll.fromTemplate(t);return mo.fromMessages([r,...e])};var Vo=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:a,config:i}=t,u=pg(e,o??[]),l=(await zi({modelTier:r,temperature:n,config:i})).withStructuredOutput(a);return await u.pipe(l).invoke(s??{},i)};var mg=d.object({name:d.string(),description:d.string(),valueType:d.string(),alias:d.string()}),IU=d.object({fields:d.array(mg)});var vU=d.object({title:d.string(),description:d.string(),name:d.string().nullable()});var Qd=t=>Array.isArray(t)&&t.every(lo),hg=t=>typeof t=="object"&&t!=null&&"messages"in t&&Qd(t.messages),gg=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,ht=class extends jl{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:n,handleToolErrors:o}=e??{};super({name:r,tags:n,func:(s,a)=>this.run(s,a)}),this.tools=t,this.handleToolErrors=o??this.handleToolErrors}async runTool(t,e){let r=this.tools.find(n=>n.name===t.name);try{if(r===void 0)throw new Error(`Tool "${t.name}" not found.`);let n=await r.invoke({...t,type:"tool_call"},e);return lo(n)&&n.getType()==="tool"||ue(n)?n:new U({status:"success",name:r.name,content:typeof n=="string"?n:JSON.stringify(n),tool_call_id:t.id})}catch(n){if(!this.handleToolErrors||io(n))throw n;return new U({status:"error",content:`Error: ${n.message}
103
- Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(gg(t))r=[await this.runTool(t.lg_tool_call,e)];else{let s;if(Qd(t))s=t;else if(hg(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(yt(l)){i=l;break}}if(i==null||!yt(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e))??[])}if(!r.some(ue))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)ue(s)?s.graph===re.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>ml(a))?o?o.goto.push(...s.goto):o=new re({graph:re.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var TB=N.Root({llmInputMessages:N({reducer:(t,e)=>ho([],e),default:()=>[]})});var Go=(t,e)=>e??t,Yg=N.Root({...ua(),intent:N({reducer:Go}),vectorSearchLayerResults:N({reducer:Go,default:()=>[]}),vectorSearchFieldResults:N({reducer:Go}),navigationInternalState:N({reducer:Go,default:()=>({toolCallMessage:void 0})})});async function Xg(t,e){let r=Cr.getDefault().helperServices,n=r.geocode.find(c=>c.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${Di.assetsPath?.endsWith("/")?Di.assetsPath:`${Di.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await wg(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!a?.extent||!a.location)throw new Error(`Could not find location for: ${t}`);let i=new bg({url:s,width:24,height:24}),u=new _g({geometry:a.location,symbol:i});e.graphics.removeAll(),e.graphics.add(u),await e.goTo(a.extent);let l={address:a.address??"",location:a.location?a.location.toJSON():null,extent:a.extent?a.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var ey=["mapView"];function Ye(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=ey.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function ty({address:t},e){let{mapView:r}=Ye(e);return await Xg(t,r)}var ry=d.object({address:d.string().describe("The full address or place name to locate.")}),ny=D(ty,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:ry});async function oy(t,e){let r=e.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let n=r.find(s=>s.name===t);if(!n)throw new Error(`Bookmark with name "${t}" not found.`);let o=n.viewpoint;if(!o)throw new Error(`Bookmark with name "${t}" does not have a valid viewpoint.`);return await e.goTo(o),{text:`Navigated to bookmark: ${t}`}}async function sy({bookmarkName:t},e){let{mapView:r}=Ye(e);return await Promise.resolve(oy(t,r))}var ay=I.object({bookmarkName:I.string().describe("The name of the bookmark to navigate to.")}),iy=D(sy,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:ay});async function ly(t,e,r){let n=r.map?.allLayers.find(a=>a.id===t);if(!n)return{text:`Error: Layer with id ${t} not found`};let o=e?.trim()?e:"1=1",s=n.createQuery();s.where=o;try{let{extent:a,count:i}=await n.queryExtent(s);if(i===0)return{text:`No features found in ${n.title} matching: ${o}`,where:o};if(a)await r.goTo(a);else return{text:`Error: Unable to determine extent for ${n.title}`,where:o};let u={layerId:t,layerTitle:n.title??t,where:o,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${n.title} matching: ${o}`,where:o,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(a){return console.error("Error in goToFeatures:",a),{text:`Error: ${a instanceof Error?a.message:"Unknown error"}`,where:o}}}async function uy({layerId:t,where:e},r){let{mapView:n}=Ye(r);return await ly(t,e,n)}var cy=I.object({layerId:I.string().describe("The layerId of the layer to zoom to."),where:I.string().describe("ArcGIS SQL-92 WHERE expression used for `query.where` on the selected layer. Use only fields from that layer and return a boolean filter expression (for example comparisons, LIKE, IN, BETWEEN, IS NULL, AND/OR/NOT). Do NOT include subqueries/nested SELECT, JOIN, GROUP BY, HAVING, ORDER BY, or semicolons.")}),dy=D(uy,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:cy});async function py(t){let e=new xg({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await t.goTo(e),{text:"Successfully zoomed to world extent"}}async function my(t,e){let{mapView:r}=Ye(e);return await py(r)}var fy=I.object({}),hy=D(my,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:fy});async function gy(t){let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;if(e)await t.goTo(e);else throw new Error("Initial extent is undefined");return{text:"Successfully zoomed to home extent"}}async function yy(t,e){let{mapView:r}=Ye(e);return await gy(r)}var _y=d.object({}),wy=D(yy,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:_y});async function by(t,e){await e.when();let r=e.map?.allLayers.find(o=>o.id===t);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${t}`),{text:`Could not find layer for: ${t}`};let n;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&e.map?.activeLinkChartLayer?n=e.map.diagramNodesExtent:n=r.fullExtent,n?(await e.goTo(n),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function xy({layerId:t},e){let{mapView:r}=Ye(e);return await by(t,r)}var Ay=I.object({layerId:I.string().describe("The id of the layer to navigate to")}),Iy=D(xy,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:Ay});async function vy(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function Ty({scale:t},e){let{mapView:r}=Ye(e);return await vy(t,r)}var Sy=d.object({scale:d.number().describe("The map scale of the view to go to.")}),ky=D(Ty,{name:"goToScale",description:"Go to the specified view scale.",schema:Sy});async function Cy(t,e,r){let n={target:new ap({longitude:t.longitude,latitude:t.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(n.zoom=r.zoom),r?.scale!==void 0&&(n.scale=r.scale),await e.goTo(n),{text:`Successfully navigated to: ${[`(${t.latitude}\xB0, ${t.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function Ey({center:t,zoom:e,scale:r},n){let{mapView:o}=Ye(n);return await Cy(t,o,{zoom:e,scale:r})}var Oy=d.object({center:d.object({longitude:d.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:d.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:d.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:d.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),My=D(Ey,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:Oy});async function Py(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function Ry({zoom:t},e){let{mapView:r}=Ye(e);return await Py(t,r)}var Ny=d.object({zoom:d.number().min(1).max(20).describe("The zoom level of the view to go to.")}),$y=D(Ry,{name:"goToZoom",description:'Go to the specified zoom level. If input is generic (e.g. "zoom in", then only zoom to the next appropriate level - increase level for zooming in and decrease for zooming out.).',schema:Ny}),np=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./R2XPTETT.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./6RA33SDH.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./EZ7YC5N5.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./65JPRIL4.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./JWUQZ52F.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./3AFLX4RZ.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./IBYY5ORN.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./WHLL7DNC.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./R53CO5LK.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./QOCYNLQ7.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./SX4KDMYV.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./ITFWXO7A.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./TKQAFRBM.js").then(t=>t.default)});async function gt(t){let e=Object.entries(np).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
102
+ Description: {description}`,Jd=I.object({schemaVersion:I.literal(Kd),modified:I.number().int().nonnegative(),embeddings:I.object({modelProvider:I.literal(Wd),model:I.literal(Vd),dimensions:I.literal(Jn),templates:I.object({layer:I.string().default(Gd),field:I.string().default(Hd)})}),layers:I.array(I.object({id:I.string().min(1),name:I.string().min(1),title:I.string().catch(""),description:I.string().catch(""),vector:I.array(I.number()).length(Jn,{message:`Layer vector must be exactly ${Jn} dimensions`}),fields:I.array(I.object({name:I.string().min(1),alias:I.string().catch(""),description:I.string().catch(""),vector:I.array(I.number()).length(Jn,{message:`Field vector must be exactly ${Jn} dimensions`})}))})).default([])});var mg=(t,e)=>{let r=Ll.fromTemplate(t);return mo.fromMessages([r,...e])};var Vo=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:a,config:i}=t,u=mg(e,o??[]),l=(await zi({modelTier:r,temperature:n,config:i})).withStructuredOutput(a);return await u.pipe(l).invoke(s??{},i)};var fg=d.object({name:d.string(),description:d.string(),valueType:d.string(),alias:d.string()}),TU=d.object({fields:d.array(fg)});var SU=d.object({title:d.string(),description:d.string(),name:d.string().nullable()});var Qd=t=>Array.isArray(t)&&t.every(lo),gg=t=>typeof t=="object"&&t!=null&&"messages"in t&&Qd(t.messages),yg=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,ht=class extends jl{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:n,handleToolErrors:o}=e??{};super({name:r,tags:n,func:(s,a)=>this.run(s,a)}),this.tools=t,this.handleToolErrors=o??this.handleToolErrors}async runTool(t,e){let r=this.tools.find(n=>n.name===t.name);try{if(r===void 0)throw new Error(`Tool "${t.name}" not found.`);let n=await r.invoke({...t,type:"tool_call"},e);return lo(n)&&n.getType()==="tool"||ue(n)?n:new U({status:"success",name:r.name,content:typeof n=="string"?n:JSON.stringify(n),tool_call_id:t.id})}catch(n){if(!this.handleToolErrors||io(n))throw n;return new U({status:"error",content:`Error: ${n.message}
103
+ Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(yg(t))r=[await this.runTool(t.lg_tool_call,e)];else{let s;if(Qd(t))s=t;else if(gg(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(yt(l)){i=l;break}}if(i==null||!yt(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e))??[])}if(!r.some(ue))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)ue(s)?s.graph===re.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>ml(a))?o?o.goto.push(...s.goto):o=new re({graph:re.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var kB=N.Root({llmInputMessages:N({reducer:(t,e)=>ho([],e),default:()=>[]})});var Go=(t,e)=>e??t,Xg=N.Root({...ua(),intent:N({reducer:Go}),vectorSearchLayerResults:N({reducer:Go,default:()=>[]}),vectorSearchFieldResults:N({reducer:Go}),navigationInternalState:N({reducer:Go,default:()=>({toolCallMessage:void 0})})});async function ey(t,e){let r=Cr.getDefault().helperServices,n=r.geocode.find(c=>c.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${Di.assetsPath?.endsWith("/")?Di.assetsPath:`${Di.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await bg(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!a?.extent||!a.location)throw new Error(`Could not find location for: ${t}`);let i=new xg({url:s,width:24,height:24}),u=new wg({geometry:a.location,symbol:i});e.graphics.removeAll(),e.graphics.add(u),await e.goTo(a.extent);let l={address:a.address??"",location:a.location?a.location.toJSON():null,extent:a.extent?a.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var ty=["mapView"];function Ye(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=ty.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function ry({address:t},e){let{mapView:r}=Ye(e);return await ey(t,r)}var ny=d.object({address:d.string().describe("The full address or place name to locate.")}),oy=D(ry,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:ny});async function sy(t,e){let r=e.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let n=r.find(s=>s.name===t);if(!n)throw new Error(`Bookmark with name "${t}" not found.`);let o=n.viewpoint;if(!o)throw new Error(`Bookmark with name "${t}" does not have a valid viewpoint.`);return await e.goTo(o),{text:`Navigated to bookmark: ${t}`}}async function ay({bookmarkName:t},e){let{mapView:r}=Ye(e);return await Promise.resolve(sy(t,r))}var iy=I.object({bookmarkName:I.string().describe("The name of the bookmark to navigate to.")}),ly=D(ay,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:iy});async function uy(t,e,r){let n=r.map?.allLayers.find(a=>a.id===t);if(!n)return{text:`Error: Layer with id ${t} not found`};let o=e?.trim()?e:"1=1",s=n.createQuery();s.where=o;try{let{extent:a,count:i}=await n.queryExtent(s);if(i===0)return{text:`No features found in ${n.title} matching: ${o}`,where:o};if(a)await r.goTo(a);else return{text:`Error: Unable to determine extent for ${n.title}`,where:o};let u={layerId:t,layerTitle:n.title??t,where:o,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${n.title} matching: ${o}`,where:o,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(a){return console.error("Error in goToFeatures:",a),{text:`Error: ${a instanceof Error?a.message:"Unknown error"}`,where:o}}}async function cy({layerId:t,where:e},r){let{mapView:n}=Ye(r);return await uy(t,e,n)}var dy=I.object({layerId:I.string().describe("The layerId of the layer to zoom to."),where:I.string().describe("ArcGIS SQL-92 WHERE expression used for `query.where` on the selected layer. Use only fields from that layer and return a boolean filter expression (for example comparisons, LIKE, IN, BETWEEN, IS NULL, AND/OR/NOT). Do NOT include subqueries/nested SELECT, JOIN, GROUP BY, HAVING, ORDER BY, or semicolons.")}),py=D(cy,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:dy});async function my(t){let e=new Ag({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await t.goTo(e),{text:"Successfully zoomed to world extent"}}async function fy(t,e){let{mapView:r}=Ye(e);return await my(r)}var hy=I.object({}),gy=D(fy,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:hy});async function yy(t){let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;if(e)await t.goTo(e);else throw new Error("Initial extent is undefined");return{text:"Successfully zoomed to home extent"}}async function _y(t,e){let{mapView:r}=Ye(e);return await yy(r)}var wy=d.object({}),by=D(_y,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:wy});async function xy(t,e){await e.when();let r=e.map?.allLayers.find(o=>o.id===t);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${t}`),{text:`Could not find layer for: ${t}`};let n;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&e.map?.activeLinkChartLayer?n=e.map.diagramNodesExtent:n=r.fullExtent,n?(await e.goTo(n),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function Ay({layerId:t},e){let{mapView:r}=Ye(e);return await xy(t,r)}var Iy=I.object({layerId:I.string().describe("The id of the layer to navigate to")}),vy=D(Ay,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:Iy});async function Ty(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function Sy({scale:t},e){let{mapView:r}=Ye(e);return await Ty(t,r)}var ky=d.object({scale:d.number().describe("The map scale of the view to go to.")}),Cy=D(Sy,{name:"goToScale",description:"Go to the specified view scale.",schema:ky});async function Ey(t,e,r){let n={target:new ap({longitude:t.longitude,latitude:t.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(n.zoom=r.zoom),r?.scale!==void 0&&(n.scale=r.scale),await e.goTo(n),{text:`Successfully navigated to: ${[`(${t.latitude}\xB0, ${t.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function Oy({center:t,zoom:e,scale:r},n){let{mapView:o}=Ye(n);return await Ey(t,o,{zoom:e,scale:r})}var My=d.object({center:d.object({longitude:d.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:d.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:d.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:d.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),Py=D(Oy,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:My});async function Ry(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function Ny({zoom:t},e){let{mapView:r}=Ye(e);return await Ry(t,r)}var $y=d.object({zoom:d.number().min(1).max(20).describe("The zoom level of the view to go to.")}),Ly=D(Ny,{name:"goToZoom",description:'Go to the specified zoom level. If input is generic (e.g. "zoom in", then only zoom to the next appropriate level - increase level for zooming in and decrease for zooming out.).',schema:$y}),np=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./R2XPTETT.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./6RA33SDH.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./EZ7YC5N5.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./65JPRIL4.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./JWUQZ52F.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./3AFLX4RZ.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./IBYY5ORN.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./WHLL7DNC.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./R53CO5LK.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./QOCYNLQ7.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./SX4KDMYV.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./ITFWXO7A.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./TKQAFRBM.js").then(t=>t.default)});async function gt(t){let e=Object.entries(np).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
104
104
  Available prompts:
105
105
  ${Object.keys(np).join(`
106
- `)}`);return await e[1]()}var Xn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function Ly(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s?a=Ig({basemapTheme:await ep(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:a=vg({basemapTheme:await ep(n),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:n,attributes:e.map(i=>({field:i,label:r.fields.find(u=>u.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:a}}async function jy(t){return await Ag(t)}async function zy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"chart-size":"chart",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=await Ly(u),c=await jy(l);return i.renderer=c.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var Dy=["mapView"];function je(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=Dy.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function Fy({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await zy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var qy=d.object({layerId:d.string().describe("The id of the layer to apply the chart renderer to"),fields:d.array(d.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),includeSize:d.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),Uy=D(Fy,{name:"chart",description:`Label: Charts
106
+ `)}`);return await e[1]()}var Xn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function jy(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s?a=vg({basemapTheme:await ep(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:a=Tg({basemapTheme:await ep(n),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:n,attributes:e.map(i=>({field:i,label:r.fields.find(u=>u.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:a}}async function zy(t){return await Ig(t)}async function Dy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"chart-size":"chart",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=await jy(u),c=await zy(l);return i.renderer=c.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var Fy=["mapView"];function je(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=Fy.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function qy({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await Dy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var Uy=d.object({layerId:d.string().describe("The id of the layer to apply the chart renderer to"),fields:d.array(d.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),includeSize:d.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),By=D(qy,{name:"chart",description:`Label: Charts
107
107
  Description: Show the values of two or more categories as a proportion of the total using a pie chart.
108
108
  Keywords: pie, chart, all categories, breakdown, proportion
109
109
  Example: Show the total number of homes built in each decade using a pie chart for each feature.
@@ -113,19 +113,19 @@ ${Object.keys(np).join(`
113
113
  Description: Show the values of two or more categories as a proportion of the total using a pie chart and use size to capture the total amount or magnitude.
114
114
  Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
115
115
  Example: Show the total number of homes built in each decade using a pie chart for each feature and vary the size of each chart based on the total of all categories.
116
- Fields: This style requires 2-8 number fields.`,schema:qy});function By(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,a=e[0],i;return s&&(i=Ji({geometryType:r.geometryType,includedTags:s,theme:o||"high-to-low"})[0]),{layer:r,view:n,startTime:a,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function Ky(t){return await Tg(t)}async function Wy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=By(u),c=await Ky(l);return i.renderer=c.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function Vy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await Wy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Gy=d.object({layerId:d.string().describe("The id of the layer to apply the color-age renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Hy=D(Vy,{name:"color-age",description:`Label: Age (color)
116
+ Fields: This style requires 2-8 number fields.`,schema:Uy});function Ky(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,a=e[0],i;return s&&(i=Ji({geometryType:r.geometryType,includedTags:s,theme:o||"high-to-low"})[0]),{layer:r,view:n,startTime:a,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function Wy(t){return await Sg(t)}async function Vy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Ky(u),c=await Wy(l);return i.renderer=c.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function Gy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await Vy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Hy=d.object({layerId:d.string().describe("The id of the layer to apply the color-age renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Jy=D(Gy,{name:"color-age",description:`Label: Age (color)
117
117
  Description: Use colors along a continuous color ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
118
118
  Keywords: since, age, how old, how long
119
119
  Example: Show the age of each feature based on its reported date.
120
- Fields: This style requires at least one field with a date type.`,schema:Gy});function Jy(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,a=e[1],i=e[0],u;return o&&(u=Ji({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:i,normalizationField:a,theme:s,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:u}}async function Zy(t){return await Sg(t)}async function Qy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Jy(u),c=await Zy(l);return i.renderer=c.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color renderer: ${l instanceof Error?l.message:String(l)}`}}async function Yy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await Qy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Xy=d.object({layerId:d.string().describe("The id of the layer to apply the color renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the color renderer"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),e_=D(Yy,{name:"color",description:`Label: Counts and Amounts (color)
120
+ Fields: This style requires at least one field with a date type.`,schema:Hy});function Zy(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,a=e[1],i=e[0],u;return o&&(u=Ji({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:i,normalizationField:a,theme:s,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:u}}async function Qy(t){return await kg(t)}async function Yy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Zy(u),c=await Qy(l);return i.renderer=c.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color renderer: ${l instanceof Error?l.message:String(l)}`}}async function Xy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await Yy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var e_=d.object({layerId:d.string().describe("The id of the layer to apply the color renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the color renderer"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),t_=D(Xy,{name:"color",description:`Label: Counts and Amounts (color)
121
121
  Description: Vary color along a continuous color ramp to represent numeric or ranked data.
122
122
  Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
123
123
  Example: Color each feature based on the population density.
124
- Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:Xy});function t_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,a,i,u=e[0];return o&&(i=Ji({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:u,normalizationField:a,theme:s,colorOptions:{colorScheme:i}}}async function r_(t){return await kg(t)}async function n_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-size-univariate",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=t_(u),c=await r_(l);return i.renderer=c.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-size-univariate renderer: ${l instanceof Error?l.message:String(l)}`}}async function o_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await n_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var s_=d.object({layerId:d.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:d.array(d.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),a_=D(o_,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
124
+ Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:e_});function r_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,a,i,u=e[0];return o&&(i=Ji({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:u,normalizationField:a,theme:s,colorOptions:{colorScheme:i}}}async function n_(t){return await Cg(t)}async function o_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-size-univariate",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=r_(u),c=await n_(l);return i.renderer=c.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-size-univariate renderer: ${l instanceof Error?l.message:String(l)}`}}async function s_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await o_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var a_=d.object({layerId:d.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:d.array(d.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),i_=D(s_,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
125
125
  Description: Vary symbol size and color based on the values of two numeric attributes.
126
126
  Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
127
127
  Example: Color each feature based on the percentage of the population that owns a home and vary the size of each point based on total population.
128
- Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:s_});function i_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=Eg({includedTags:o,numColors:Math.min(e.length,8)})[0]),{layer:r,view:n,legendOptions:{unit:"units"},attributes:e.map(a=>({field:a,label:r.fields.find(i=>i.name===a)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:s}}async function l_(t){return await Cg(t)}async function u_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=i_(i),l=await l_(u);return a.renderer=l.renderer,a.visible=!0,`Dot Density renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying dot density renderer: ${u instanceof Error?u.message:String(u)}`}}async function c_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=je(n);return await _e({type:"show-legend",data:{layerIds:[t]}},n),await u_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var d_=d.object({layerId:d.string().describe("The id of the layer to apply the dot density renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),p_=D(c_,{name:"dot-density",description:`Dot Density
128
+ Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:a_});function l_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=Og({includedTags:o,numColors:Math.min(e.length,8)})[0]),{layer:r,view:n,legendOptions:{unit:"units"},attributes:e.map(a=>({field:a,label:r.fields.find(i=>i.name===a)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:s}}async function u_(t){return await Eg(t)}async function c_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=l_(i),l=await u_(u);return a.renderer=l.renderer,a.visible=!0,`Dot Density renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying dot density renderer: ${u instanceof Error?u.message:String(u)}`}}async function d_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=je(n);return await _e({type:"show-legend",data:{layerIds:[t]}},n),await c_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var p_=d.object({layerId:d.string().describe("The id of the layer to apply the dot density renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),m_=D(d_,{name:"dot-density",description:`Dot Density
129
129
  Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
130
130
  **Use cases:**
131
131
  - Population distribution visualization
@@ -136,11 +136,11 @@ ${Object.keys(np).join(`
136
136
  - Visualize distribution of different crops across regions
137
137
  - Display demographic patterns within census tracts
138
138
  **Fields:** Requires 2-8 number fields.
139
- **Keywords:** density, how much, how many, total, number, amount`,schema:d_});function m_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a=e[0];return o&&(s=Mg({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:a,heatmapScheme:s}}async function f_(t){return await Og(t)}async function h_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"heatmap",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=m_(i),l=await f_(u);return a.renderer=l.renderer,a.visible=!0,`Heatmap renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying heatmap renderer: ${u instanceof Error?u.message:String(u)}`}}async function g_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=je(n);return await _e({type:"show-legend",data:{layerIds:[t]}},n),await h_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var y_=d.object({layerId:d.string().describe("The id of the layer to apply the heatmap renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),__=D(g_,{name:"heatmap",description:`Label: Heat Map
139
+ **Keywords:** density, how much, how many, total, number, amount`,schema:p_});function f_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a=e[0];return o&&(s=Pg({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:a,heatmapScheme:s}}async function h_(t){return await Mg(t)}async function g_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"heatmap",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=f_(i),l=await h_(u);return a.renderer=l.renderer,a.visible=!0,`Heatmap renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying heatmap renderer: ${u instanceof Error?u.message:String(u)}`}}async function y_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=je(n);return await _e({type:"show-legend",data:{layerIds:[t]}},n),await g_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var __=d.object({layerId:d.string().describe("The id of the layer to apply the heatmap renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),w_=D(y_,{name:"heatmap",description:`Label: Heat Map
140
140
  Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
141
141
  Keywords: density, heatmap, hot spots, pattern, cluster
142
142
  Example: Create a heatmap
143
- Fields: This typically requires zero or one field of type number.`,schema:y_});function w_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s&&(a=Rg({geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,10)})[0]),{layer:r,view:n,fields:e.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:a}}async function b_(t){return await Pg(t)}async function x_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"predominance-size":"predominance",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=w_(u),c=await b_(l);return i.renderer=c.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying predominance renderer: ${l instanceof Error?l.message:String(l)}`}}async function A_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await x_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var I_=d.object({layerId:d.string().describe("The id of the layer to apply the predominance renderer to"),fields:d.array(d.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),includeSize:d.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),v_=D(A_,{name:"predominance",description:`Label: Predominant category
143
+ Fields: This typically requires zero or one field of type number.`,schema:__});function b_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s&&(a=Ng({geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,10)})[0]),{layer:r,view:n,fields:e.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:a}}async function x_(t){return await Rg(t)}async function A_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"predominance-size":"predominance",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=b_(u),c=await x_(l);return i.renderer=c.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying predominance renderer: ${l instanceof Error?l.message:String(l)}`}}async function I_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await A_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var v_=d.object({layerId:d.string().describe("The id of the layer to apply the predominance renderer to"),fields:d.array(d.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),includeSize:d.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),T_=D(I_,{name:"predominance",description:`Label: Predominant category
144
144
  Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
145
145
  Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
146
146
  Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
@@ -150,15 +150,15 @@ Fields: This typically requires zero or one field of type number.`,schema:y_});f
150
150
  Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value. Also varies the size of each symbol based on the total of all categories.
151
151
  Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
152
152
  Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
153
- Fields: This style relies on 2-10 number fields.`,schema:I_});function T_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a={field:e[0]},i={field:e[1]};return o&&(s=$g({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:a,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function S_(t){return await Ng(t)}async function k_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"relationship",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=T_(i),l=await S_(u);return a.renderer=l.renderer,a.visible=!0,`Relationship renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying relationship renderer: ${u instanceof Error?u.message:String(u)}`}}async function C_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=je(n);return await _e({type:"show-legend",data:{layerIds:[t]}},n),await k_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var E_=d.object({layerId:d.string().describe("The id of the layer to apply the relationship renderer to"),fields:d.array(d.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),O_=D(C_,{name:"relationship",description:`Label: Relationship
153
+ Fields: This style relies on 2-10 number fields.`,schema:v_});function S_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a={field:e[0]},i={field:e[1]};return o&&(s=Lg({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:a,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function k_(t){return await $g(t)}async function C_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"relationship",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=S_(i),l=await k_(u);return a.renderer=l.renderer,a.visible=!0,`Relationship renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying relationship renderer: ${u instanceof Error?u.message:String(u)}`}}async function E_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=je(n);return await _e({type:"show-legend",data:{layerIds:[t]}},n),await C_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var O_=d.object({layerId:d.string().describe("The id of the layer to apply the relationship renderer to"),fields:d.array(d.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),M_=D(E_,{name:"relationship",description:`Label: Relationship
154
154
  Description: Overlays two color ramps to represent the relationship between two numeric attributes.
155
155
  Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
156
156
  Example: Show the relationship between tree height and carbon storage
157
- Fields: This style requires two number fields.`,schema:E_});function M_(t){let{fields:e,layer:r,view:n,theme:o}=t,s=e[0];return{layer:r,view:n,startTime:s,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function P_(t){return await Lg(t)}async function R_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"size-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=M_(u),c=await P_(l);return i.renderer=c.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function N_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await R_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var $_=d.object({layerId:d.string().describe("The id of the layer to apply the size-age renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),L_=D(N_,{name:"size-age",description:`Label: Age (size)
157
+ Fields: This style requires two number fields.`,schema:O_});function P_(t){let{fields:e,layer:r,view:n,theme:o}=t,s=e[0];return{layer:r,view:n,startTime:s,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function R_(t){return await jg(t)}async function N_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"size-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=P_(u),c=await R_(l);return i.renderer=c.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function $_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await N_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var L_=d.object({layerId:d.string().describe("The id of the layer to apply the size-age renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),j_=D($_,{name:"size-age",description:`Label: Age (size)
158
158
  Description: Vary symbol sizes along a continuous ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
159
159
  Keywords: since, age, how old, how long
160
160
  Example: Change the size of features so older features are larger than new features.
161
- Fields: This style requires at least one field with a date type.`,schema:$_});function j_(t){let{fields:e,layer:r,view:n}=t,{theme:o}=t,s=e[1],a=e[0];return{layer:r,view:n,field:a,normalizationField:s,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function z_(t){return await jg(t)}async function D_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"size",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=j_(u),c=await z_(l);return i.renderer=c.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size renderer: ${l instanceof Error?l.message:String(l)}`}}async function F_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await D_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var q_=d.object({layerId:d.string().describe("The id of the layer to apply the size renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),U_=D(F_,{name:"size",description:`Label: Counts and Amounts (size)
161
+ Fields: This style requires at least one field with a date type.`,schema:L_});function z_(t){let{fields:e,layer:r,view:n}=t,{theme:o}=t,s=e[1],a=e[0];return{layer:r,view:n,field:a,normalizationField:s,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function D_(t){return await zg(t)}async function F_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"size",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=z_(u),c=await D_(l);return i.renderer=c.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size renderer: ${l instanceof Error?l.message:String(l)}`}}async function q_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await F_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var U_=d.object({layerId:d.string().describe("The id of the layer to apply the size renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),B_=D(q_,{name:"size",description:`Label: Counts and Amounts (size)
162
162
  Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
163
163
  Keywords: graduated size, proportional size, how much, total, number, amount, size
164
164
  Example: Vary the size of each point based on the total population.
@@ -168,11 +168,11 @@ Fields: This typically requires zero or one field of type number.`,schema:y_});f
168
168
  Description: Vary symbol sizes along a continuous ramp to represent dates.
169
169
  Keywords: graduated size, proportional size, classed size, how much, total, number, when
170
170
  Example: Vary the size of each feature based on the date a ticket was completed.
171
- Fields: This style requires a single field with a date type.`,schema:q_});function B_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],a=e[1],i=e[2],u;return o&&(u=Dg({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:a,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:u}}async function K_(t){return await zg(t)}async function W_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"type",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=B_(u),c=await K_(l);return i.renderer=c.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying type renderer: ${l instanceof Error?l.message:String(l)}`}}async function V_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await W_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var G_=d.object({layerId:d.string().describe("The id of the layer to apply the type renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),H_=D(V_,{name:"type",description:`Label: Types (unique symbols)
171
+ Fields: This style requires a single field with a date type.`,schema:U_});function K_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],a=e[1],i=e[2],u;return o&&(u=Fg({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:a,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:u}}async function W_(t){return await Dg(t)}async function V_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"type",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=K_(u),c=await W_(l);return i.renderer=c.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying type renderer: ${l instanceof Error?l.message:String(l)}`}}async function G_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=je(o);return await _e({type:"show-legend",data:{layerIds:[t]}},o),await V_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var H_=d.object({layerId:d.string().describe("The id of the layer to apply the type renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),J_=D(G_,{name:"type",description:`Label: Types (unique symbols)
172
172
  Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
173
173
  Keywords: categorical, category, type, unique, discrete, point of interest, region, group
174
174
  Example: Color each feature based on the region it belongs to
175
- Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:G_}),J_=N.Root({...kr(),vectorSearchLayerIds:N(),vectorSearchFieldResults:N(),layerFieldInfo:N(),selectedLayerId:N()}),Z_=N.Root({...kr(),vectorSearchLayerIds:N(),vectorSearchFieldResults:N(),layerFieldInfo:N(),queryResponse:N(),dataExplorationMessages:N({reducer:ho,default:()=>[]})}),Q_=["mapView"];function Vt(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=Q_.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var Y_=t=>{let e=t.map?.allLayers.filter(n=>n.type==="feature"),r=0;return e?.forEach(n=>{let o=n;o.featureEffect&&(o.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},X_=async(t,e)=>{let{mapView:r}=Vt(e);return Y_(r)},$K=D(X_,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:d.object({})}),ew=async t=>{t.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let n=r;n.featureEffect&&(n.featureEffect=null)});let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;return e?(await t.goTo(e),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},tw=async(t,e)=>{let{mapView:r}=Vt(e);return await ew(r)},LK=D(tw,{name:"resetMap",description:"Clears all feature effects/filters from the map AND zooms to the home extent (initial map view). Use when user says 'reset map', 'reset the map', 'start over', or wants to both clear filters and return to the initial view.",schema:d.object({})}),op=750;function ma(t){return"point"in t&&t.point!==void 0}function Ho(t){return"layerId"in t&&t.layerId!==void 0}var ga=async(t,e)=>{if(ma(t)){let{point:r}=t;return{geometry:new ap({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(Ho(t)){let r=e.map?.allLayers.find(s=>s.id===t.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${t.layerId}`};let n=r.title??r.id,o=t.where?.trim()||"1=1";try{let s=await r.queryFeatures({where:o,returnGeometry:!0,outSpatialReference:e.spatialReference,num:op+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>op)return{error:`Geometry filter for layer "${n}" matched too many features (${s.features.length}+). Please narrow the geometry layer filter.`};let a=s.features.map(u=>u.geometry).filter(u=>!!u);if(!a.length)return{error:"No valid geometries found for the matched geometry layer features."};let i=a.length===1?a[0]:lp.executeMany(a);return i?(i.spatialReference||(i.spatialReference=e.spatialReference),{geometry:i}):{error:"Failed to combine geometries from geometry layer."}}catch(s){return{error:`Failed to query geometry: ${String(s)}`}}}return{error:"Invalid geometry configuration provided"}},rw=async(t,e,r,n,o,s)=>{let a=t.map?.allLayers.find(u=>u.id===e);if(!a)return{success:!1,error:`Layer '${e}' not found.`};let i=a.createQuery();i.where=r??"1=1",n&&(i.geometry=n,i.spatialRelationship="intersects",o&&(i.distance=o),s&&(i.units=s));try{let{extent:u,count:l}=await a.queryExtent(i);return!u||l===0?{success:!1,error:`No features found for filter (where: ${i.where}${n?", spatial filter used":""})`}:(await t.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},nw=async(t,e,r,n,o,s)=>{let a=e.map?.allLayers.find(p=>p.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(o){let p=await ga(o,e);if("error"in p)return p.error;i=p.geometry}if(a.featureEffect=null,a.featureEffect=new Fg({filter:new ip({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),a.visible=!0,s)return`Applied feature effects to "${a.title??t.layerId}" within current map extent.`;let u=t.objectIds?.length?`${a.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await rw(e,t.layerId,u,i,o?.distance,o?.units),c=a.title??t.layerId;return l.success?`Applied feature effects to target layer "${a.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${c}" but no features matched. ${l.error}`},ow=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Gt=d.enum(ow),sw=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:n="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:a}=Vt(s);return await nw(t,a,n,o,e,r)},aw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),iw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),lw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer on which to set a feature effect."),where:d.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:d.array(d.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:d.union([aw,iw]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:d.boolean().optional().describe("Set to true when the previous query used the current map extent as a spatial filter. This ensures the feature effect applies only to features visible in the current view. Default is false."),includedEffect:d.string().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:d.string().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),jK=D(sw,{name:"setFeatureEffect",description:"Sets a feature effect on a given layer with given filter parameters and feature effects to emphasize certain features that meet a filter requirement. If no feature effect information is provided, then use the default effect provided.",schema:lw}),uw=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),cp=t=>{if(!t)return!1;let e=t.toLowerCase();return uw.has(e)},qi=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},cw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,dw=t=>{if(typeof t=="string"&&t)return t;let e=qi(t);return e?e.toISOString().slice(0,10):null};var pw=(t,e,r)=>{let n=e?.toLowerCase();if(n&&!cp(n))return t;if(n==="date-only"){let s=dw(t);return s?qg(s,ca("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return Ug(t,ca("long-time"));let s=qi(t);return s?tp(s,{...ca("long-time"),timeZone:"UTC"}):t}let o=qi(t);return o?tp(o,{...ca("short-date-short-time"),timeZone:cw(r)}):t},dp=(t,e,r)=>{if(t&&typeof t!="function"){let n="getField"in r&&r.getField?.(t),o=n&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(n.name):null;if(o?.type==="coded-value"){let s=o.codedValues.find(a=>a.code===e);return s?s.name:null}}return null},mw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,fw=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}if(typeof t=="string"&&t){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},hw=(t,e)=>{if(typeof t!="number")return t;let r={};e.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=e.minimumFractionDigits),e.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=e.maximumFractionDigits),e.useGrouping==="always"?r.useGrouping=!0:e.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(t)}catch{return t}},gw=(t,e,r)=>{let n=fw(t);if(!n)return t;let o={};e.dateStyle?o.dateStyle=e.dateStyle:(e.year&&(o.year=e.year),e.month&&(o.month=e.month)),e.timeStyle&&(o.timeStyle=e.timeStyle),e.timeStyle&&e.hour12==="always"?o.hour12=!0:e.timeStyle&&e.hour12==="never"&&(o.hour12=!1),o.timeZone=mw(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},pp=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,mp=(t,e,r,n,o)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?hw(r,s):s?.type==="date-time"?!n||cp(n)?gw(r,s,o):r:pw(r,n,o)},yw=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=dp(e,r,t)??r;return mp(t,e,s,o?.type,n)},_w=(t,e)=>pp(t,e),fp=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(a=>a.attributes[n]),s=e.features.map(a=>{let i=a.attributes,u={};return t.fields.forEach(l=>{if(!Object.hasOwn(i,l.name))return;let c=i[l.name];if(l.name===n){u[l.name]=c;return}let p=dp(l.name,c,t)??c,m=pp(t,l.name);u[m]=mp(t,l.name,p,l.type,r)}),u});return{objectIds:o,attributes:s}},ww=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},bw=async(t,e,r,n)=>{let o=n.map?.allLayers.find(c=>c.id===t),s=ww(o,e,r.where),a=(await o.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=yw(o,e,i,n.timeZone),l=_w(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:r.where}}};async function xw({layerId:t,fieldName:e,query:r},n){let{mapView:o}=Vt(n),s=await bw(t,e,r,o);return JSON.stringify(s,null,2)}var Aw=d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:d.string().describe("The name of the field/attribute from which to get a field value."),query:d.object({where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),Iw=D(xw,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Aw}),Zi=(t,e,r)=>{if(!(r?t.hasAllFeaturesInView:t.hasAllFeatures))return!1;let n=new Set((t.availableFields??[]).map(o=>o.toLowerCase()));return n.has("*")?!0:e.every(o=>n.has(o.toLowerCase()))};function fa(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var vw=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:a}=t,i=o.map?.allLayers.find(h=>h.id===e.layerId);if(!i)throw new Error(`Layer '${e.layerId}' not found.`);let u=await o.whenLayerView(i),l=s.get(e.layerId)?.fieldRegistry.get(r),c=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let p,m;if(a){let h=await ga(a,o);if("error"in h)throw new Error(h.error);if(!h.geometry)throw Ho(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(Ho(a)){let b=o.map?.allLayers.find(S=>S.id===a.layerId);p={geometryLayerName:b?.title??b?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else ma(a)&&(p={point:a.point,distance:a.distance,units:a.units,applied:!0});m=new ip({geometry:h.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let g=Zi(u,[r],!1),y=null,A=null,C=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let h={layer:i,useFeaturesInView:g,view:g?o:void 0,field:r,sqlWhere:fa(i.definitionExpression,e.where),...m&&{filter:m},outStatisticTypes:{include:[n]}};y=await Bg(h);let b=["string","small-integer","integer"],S=l.domain?.type==="coded-value"?l.domain:null;(b.includes(l.type)||S)&&(A=(await Kg({layer:i,useFeaturesInView:g,view:g?o:void 0,field:r,sqlWhere:fa(i.definitionExpression,e.where),...m&&{filter:m}})).uniqueValueInfos.sort((j,Q)=>Q.count-j.count).slice(0,C)),A&&l.domain?.type==="coded-value"&&(A=A.map(j=>({...j,value:S?S.getName(j.value)??j.value:j.value})))}catch(h){console.error("Statistics error:",h)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${n} = ${typeof y?.[n]=="number"?y[n]:"N/A"}`,details:{fieldName:r,fieldAlias:c,statisticType:n,statistic:y?.[n]??null,summaryStatistics:y,uniqueValues:A,where:e.where,spatialFilterInfo:p}}};async function Tw({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Xn(o,"layersAndFieldsRegistry"),{mapView:a}=Vt(o),i=await vw({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(i,null,2)}var Sw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),kw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),Cw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:d.union([Sw,kw]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:d.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:d.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),Ew=D(Tw,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
175
+ Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:H_}),Z_=N.Root({...kr(),vectorSearchLayerIds:N(),vectorSearchFieldResults:N(),layerFieldInfo:N(),selectedLayerId:N()}),Q_=N.Root({...kr(),vectorSearchLayerIds:N(),vectorSearchFieldResults:N(),layerFieldInfo:N(),queryResponse:N(),dataExplorationMessages:N({reducer:ho,default:()=>[]})}),Y_=["mapView"];function Vt(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=Y_.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var X_=t=>{let e=t.map?.allLayers.filter(n=>n.type==="feature"),r=0;return e?.forEach(n=>{let o=n;o.featureEffect&&(o.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},ew=async(t,e)=>{let{mapView:r}=Vt(e);return X_(r)},jK=D(ew,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:d.object({})}),tw=async t=>{t.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let n=r;n.featureEffect&&(n.featureEffect=null)});let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;return e?(await t.goTo(e),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},rw=async(t,e)=>{let{mapView:r}=Vt(e);return await tw(r)},zK=D(rw,{name:"resetMap",description:"Clears all feature effects/filters from the map AND zooms to the home extent (initial map view). Use when user says 'reset map', 'reset the map', 'start over', or wants to both clear filters and return to the initial view.",schema:d.object({})}),op=750;function ma(t){return"point"in t&&t.point!==void 0}function Ho(t){return"layerId"in t&&t.layerId!==void 0}var ga=async(t,e)=>{if(ma(t)){let{point:r}=t;return{geometry:new ap({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(Ho(t)){let r=e.map?.allLayers.find(s=>s.id===t.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${t.layerId}`};let n=r.title??r.id,o=t.where?.trim()||"1=1";try{let s=await r.queryFeatures({where:o,returnGeometry:!0,outSpatialReference:e.spatialReference,num:op+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>op)return{error:`Geometry filter for layer "${n}" matched too many features (${s.features.length}+). Please narrow the geometry layer filter.`};let a=s.features.map(u=>u.geometry).filter(u=>!!u);if(!a.length)return{error:"No valid geometries found for the matched geometry layer features."};let i=a.length===1?a[0]:lp.executeMany(a);return i?(i.spatialReference||(i.spatialReference=e.spatialReference),{geometry:i}):{error:"Failed to combine geometries from geometry layer."}}catch(s){return{error:`Failed to query geometry: ${String(s)}`}}}return{error:"Invalid geometry configuration provided"}},nw=async(t,e,r,n,o,s)=>{let a=t.map?.allLayers.find(u=>u.id===e);if(!a)return{success:!1,error:`Layer '${e}' not found.`};let i=a.createQuery();i.where=r??"1=1",n&&(i.geometry=n,i.spatialRelationship="intersects",o&&(i.distance=o),s&&(i.units=s));try{let{extent:u,count:l}=await a.queryExtent(i);return!u||l===0?{success:!1,error:`No features found for filter (where: ${i.where}${n?", spatial filter used":""})`}:(await t.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},ow=async(t,e,r,n,o,s)=>{let a=e.map?.allLayers.find(p=>p.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(o){let p=await ga(o,e);if("error"in p)return p.error;i=p.geometry}if(a.featureEffect=null,a.featureEffect=new qg({filter:new ip({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),a.visible=!0,s)return`Applied feature effects to "${a.title??t.layerId}" within current map extent.`;let u=t.objectIds?.length?`${a.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await nw(e,t.layerId,u,i,o?.distance,o?.units),c=a.title??t.layerId;return l.success?`Applied feature effects to target layer "${a.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${c}" but no features matched. ${l.error}`},sw=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Gt=d.enum(sw),aw=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:n="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:a}=Vt(s);return await ow(t,a,n,o,e,r)},iw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),lw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),uw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer on which to set a feature effect."),where:d.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:d.array(d.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:d.union([iw,lw]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:d.boolean().optional().describe("Set to true when the previous query used the current map extent as a spatial filter. This ensures the feature effect applies only to features visible in the current view. Default is false."),includedEffect:d.string().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:d.string().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),DK=D(aw,{name:"setFeatureEffect",description:"Sets a feature effect on a given layer with given filter parameters and feature effects to emphasize certain features that meet a filter requirement. If no feature effect information is provided, then use the default effect provided.",schema:uw}),cw=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),cp=t=>{if(!t)return!1;let e=t.toLowerCase();return cw.has(e)},qi=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},dw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,pw=t=>{if(typeof t=="string"&&t)return t;let e=qi(t);return e?e.toISOString().slice(0,10):null};var mw=(t,e,r)=>{let n=e?.toLowerCase();if(n&&!cp(n))return t;if(n==="date-only"){let s=pw(t);return s?Ug(s,ca("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return Bg(t,ca("long-time"));let s=qi(t);return s?tp(s,{...ca("long-time"),timeZone:"UTC"}):t}let o=qi(t);return o?tp(o,{...ca("short-date-short-time"),timeZone:dw(r)}):t},dp=(t,e,r)=>{if(t&&typeof t!="function"){let n="getField"in r&&r.getField?.(t),o=n&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(n.name):null;if(o?.type==="coded-value"){let s=o.codedValues.find(a=>a.code===e);return s?s.name:null}}return null},fw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,hw=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}if(typeof t=="string"&&t){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},gw=(t,e)=>{if(typeof t!="number")return t;let r={};e.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=e.minimumFractionDigits),e.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=e.maximumFractionDigits),e.useGrouping==="always"?r.useGrouping=!0:e.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(t)}catch{return t}},yw=(t,e,r)=>{let n=hw(t);if(!n)return t;let o={};e.dateStyle?o.dateStyle=e.dateStyle:(e.year&&(o.year=e.year),e.month&&(o.month=e.month)),e.timeStyle&&(o.timeStyle=e.timeStyle),e.timeStyle&&e.hour12==="always"?o.hour12=!0:e.timeStyle&&e.hour12==="never"&&(o.hour12=!1),o.timeZone=fw(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},pp=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,mp=(t,e,r,n,o)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?gw(r,s):s?.type==="date-time"?!n||cp(n)?yw(r,s,o):r:mw(r,n,o)},_w=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=dp(e,r,t)??r;return mp(t,e,s,o?.type,n)},ww=(t,e)=>pp(t,e),fp=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(a=>a.attributes[n]),s=e.features.map(a=>{let i=a.attributes,u={};return t.fields.forEach(l=>{if(!Object.hasOwn(i,l.name))return;let c=i[l.name];if(l.name===n){u[l.name]=c;return}let p=dp(l.name,c,t)??c,m=pp(t,l.name);u[m]=mp(t,l.name,p,l.type,r)}),u});return{objectIds:o,attributes:s}},bw=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},xw=async(t,e,r,n)=>{let o=n.map?.allLayers.find(c=>c.id===t),s=bw(o,e,r.where),a=(await o.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=_w(o,e,i,n.timeZone),l=ww(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:r.where}}};async function Aw({layerId:t,fieldName:e,query:r},n){let{mapView:o}=Vt(n),s=await xw(t,e,r,o);return JSON.stringify(s,null,2)}var Iw=d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:d.string().describe("The name of the field/attribute from which to get a field value."),query:d.object({where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),vw=D(Aw,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Iw}),Zi=(t,e,r)=>{if(!(r?t.hasAllFeaturesInView:t.hasAllFeatures))return!1;let n=new Set((t.availableFields??[]).map(o=>o.toLowerCase()));return n.has("*")?!0:e.every(o=>n.has(o.toLowerCase()))};function fa(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var Tw=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:a}=t,i=o.map?.allLayers.find(h=>h.id===e.layerId);if(!i)throw new Error(`Layer '${e.layerId}' not found.`);let u=await o.whenLayerView(i),l=s.get(e.layerId)?.fieldRegistry.get(r),c=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let p,m;if(a){let h=await ga(a,o);if("error"in h)throw new Error(h.error);if(!h.geometry)throw Ho(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(Ho(a)){let b=o.map?.allLayers.find(S=>S.id===a.layerId);p={geometryLayerName:b?.title??b?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else ma(a)&&(p={point:a.point,distance:a.distance,units:a.units,applied:!0});m=new ip({geometry:h.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let g=Zi(u,[r],!1),y=null,A=null,C=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let h={layer:i,useFeaturesInView:g,view:g?o:void 0,field:r,sqlWhere:fa(i.definitionExpression,e.where),...m&&{filter:m},outStatisticTypes:{include:[n]}};y=await Kg(h);let b=["string","small-integer","integer"],S=l.domain?.type==="coded-value"?l.domain:null;(b.includes(l.type)||S)&&(A=(await Wg({layer:i,useFeaturesInView:g,view:g?o:void 0,field:r,sqlWhere:fa(i.definitionExpression,e.where),...m&&{filter:m}})).uniqueValueInfos.sort((j,Q)=>Q.count-j.count).slice(0,C)),A&&l.domain?.type==="coded-value"&&(A=A.map(j=>({...j,value:S?S.getName(j.value)??j.value:j.value})))}catch(h){console.error("Statistics error:",h)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${n} = ${typeof y?.[n]=="number"?y[n]:"N/A"}`,details:{fieldName:r,fieldAlias:c,statisticType:n,statistic:y?.[n]??null,summaryStatistics:y,uniqueValues:A,where:e.where,spatialFilterInfo:p}}};async function Sw({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Xn(o,"layersAndFieldsRegistry"),{mapView:a}=Vt(o),i=await Tw({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(i,null,2)}var kw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),Cw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),Ew=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:d.union([kw,Cw]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:d.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:d.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),Ow=D(Sw,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
176
176
 
177
177
  USE THIS TOOL FOR:
178
178
  - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
@@ -184,7 +184,7 @@ DO NOT USE FOR:
184
184
  - "Show / list / find features" \u2014 use queryFeatures instead
185
185
  - Simple counts of features matching a condition \u2014 use queryFeatures instead
186
186
 
187
- Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:Cw}),Ow=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),Mw=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(m=>m.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(n){let m=await ga(n,r);if("error"in m)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:m.error}};if(!m.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in n?n.where:"unknown criteria"}`}};u=m.geometry}else o&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,c=s.objectIdField,p=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,c])];try{let m;if(l){let A=new Wg({where:t.where||"1=1",outFields:p,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new Vg({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});m=await s.queryTopFeatures(A)}else{let A=s.createQuery();A.where=fa(s.definitionExpression,t.where||"1=1"),A.outFields=p.length?p:["*"],A.orderByFields=e.orderByFields,A.returnGeometry=!1,A.num=e.topCount,u&&(A.geometry=u,A.spatialRelationship="intersects"),n?.distance&&(A.distance=n.distance),n?.units&&(A.units=n.units),A.outSpatialReference=r.spatialReference;let C=[...new Set([...t.outFields,...Ow(e.orderByFields)])],h=Zi(a,C,o??!1);try{m=h?await a.queryFeatures(A):await s.queryFeatures(A)}catch(b){console.warn("Client-side query failed, falling back to server:",b),m=await s.queryFeatures(A)}}let g=m.features.map(A=>A.attributes[c]),{attributes:y}=fp(s,m,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:y,objectIds:g,objectIdField:c,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(m){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:m instanceof Error?m.message:String(m)}}}},Pw=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=Vt(o),a=await Mw(t,e,s,r,n);return JSON.stringify(a,null,2)},Rw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),Nw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),$w=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:d.array(d.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:d.array(d.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:d.union([Rw,Nw]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),topFilter:d.object({topCount:d.number().describe("Number of top features to return per group."),orderByFields:d.array(d.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:d.array(d.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:d.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at'. Default is false (queries entire layer).")}),Lw=D(Pw,{name:"getTopFeatures",description:'Returns top N features ranked by an existing field value. Use for "highest", "lowest", "top N" questions where ranking is based on a field that already exists in the data (e.g., population, value, date, depth). orderByFields must be actual field names with ASC/DESC. Do NOT use aggregate functions like COUNT(), SUM(), AVG() - those require getStatistics.',schema:$w}),Fi=25,jw=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),zw=async(t,e,r,n)=>{let o=e.map?.allLayers.find(C=>C.id===t.layerId),s=await e.whenLayerView(o),a=o.title??t.layerId,i;if(r){let C=await ga(r,e);if("error"in C){let h={error:C.error};if(Ho(r)){let b=e.map?.allLayers.find(S=>S.id===r.layerId);h.geometryLayerName=b?.title??b?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else ma(r)&&(h.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:h}}if(!C.geometry){let h={};if(Ho(r)){let b=e.map?.allLayers.find(S=>S.id===r.layerId);h.error=`No features found matching: ${r.where}`,h.geometryLayerName=b?.title??b?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else ma(r)&&(h.error="Failed to create point geometry",h.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:h}}i=C.geometry}else n&&(i=e.extent.clone());let u=[...new Set([...t.outFields,...jw(t.orderByFields)])],l=Zi(s,u,n??!1),c=o.objectIdField,p=o.createQuery();p.where=fa(o.definitionExpression,t.where||"1=1"),p.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,c])],p.orderByFields=t.orderByFields,i&&(p.geometry=i,p.spatialRelationship="intersects"),r?.distance&&(p.distance=r.distance),r?.units&&(p.units=r.units),p.outSpatialReference=e.spatialReference;let m,g;try{m=l?await s.queryFeatureCount(p):await o.queryFeatureCount(p),m>0&&m<=Fi&&(g=l?await s.queryFeatures(p):await o.queryFeatures(p))}catch(C){console.warn("Client-side query failed, falling back to server:",C),m=await o.queryFeatureCount(p),m>0&&m<=Fi&&(g=await o.queryFeatures(p))}let{objectIds:y,attributes:A}=g?fp(o,g,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:a,summary:`${m} features found`,details:{totalCount:m,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...y&&{objectIds:y,objectIdField:c},...A&&{attributes:A},...m>Fi&&{note:`${m} features found.`}}}};async function Dw({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=Vt(n),s=await zw(t,o,e,r);return JSON.stringify(s,null,2)}var Fw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),qw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),Uw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("SQL-92 where clause. IMPORTANT: When using geometryFilter.point for point-in-polygon queries, set this to '1=1' to return all features that intersect the point. Only add attribute filters if the user specifically requests them in addition to the spatial query."),orderByFields:d.array(d.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:d.array(d.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:d.union([Fw,qw]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),useCurrentExtent:d.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),Bw=D(Dw,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
187
+ Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:Ew}),Mw=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),Pw=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(m=>m.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(n){let m=await ga(n,r);if("error"in m)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:m.error}};if(!m.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in n?n.where:"unknown criteria"}`}};u=m.geometry}else o&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,c=s.objectIdField,p=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,c])];try{let m;if(l){let A=new Vg({where:t.where||"1=1",outFields:p,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new Gg({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});m=await s.queryTopFeatures(A)}else{let A=s.createQuery();A.where=fa(s.definitionExpression,t.where||"1=1"),A.outFields=p.length?p:["*"],A.orderByFields=e.orderByFields,A.returnGeometry=!1,A.num=e.topCount,u&&(A.geometry=u,A.spatialRelationship="intersects"),n?.distance&&(A.distance=n.distance),n?.units&&(A.units=n.units),A.outSpatialReference=r.spatialReference;let C=[...new Set([...t.outFields,...Mw(e.orderByFields)])],h=Zi(a,C,o??!1);try{m=h?await a.queryFeatures(A):await s.queryFeatures(A)}catch(b){console.warn("Client-side query failed, falling back to server:",b),m=await s.queryFeatures(A)}}let g=m.features.map(A=>A.attributes[c]),{attributes:y}=fp(s,m,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:y,objectIds:g,objectIdField:c,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(m){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:m instanceof Error?m.message:String(m)}}}},Rw=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=Vt(o),a=await Pw(t,e,s,r,n);return JSON.stringify(a,null,2)},Nw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),$w=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),Lw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:d.array(d.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:d.array(d.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:d.union([Nw,$w]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),topFilter:d.object({topCount:d.number().describe("Number of top features to return per group."),orderByFields:d.array(d.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:d.array(d.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:d.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at'. Default is false (queries entire layer).")}),jw=D(Rw,{name:"getTopFeatures",description:'Returns top N features ranked by an existing field value. Use for "highest", "lowest", "top N" questions where ranking is based on a field that already exists in the data (e.g., population, value, date, depth). orderByFields must be actual field names with ASC/DESC. Do NOT use aggregate functions like COUNT(), SUM(), AVG() - those require getStatistics.',schema:Lw}),Fi=25,zw=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),Dw=async(t,e,r,n)=>{let o=e.map?.allLayers.find(C=>C.id===t.layerId),s=await e.whenLayerView(o),a=o.title??t.layerId,i;if(r){let C=await ga(r,e);if("error"in C){let h={error:C.error};if(Ho(r)){let b=e.map?.allLayers.find(S=>S.id===r.layerId);h.geometryLayerName=b?.title??b?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else ma(r)&&(h.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:h}}if(!C.geometry){let h={};if(Ho(r)){let b=e.map?.allLayers.find(S=>S.id===r.layerId);h.error=`No features found matching: ${r.where}`,h.geometryLayerName=b?.title??b?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else ma(r)&&(h.error="Failed to create point geometry",h.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:h}}i=C.geometry}else n&&(i=e.extent.clone());let u=[...new Set([...t.outFields,...zw(t.orderByFields)])],l=Zi(s,u,n??!1),c=o.objectIdField,p=o.createQuery();p.where=fa(o.definitionExpression,t.where||"1=1"),p.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,c])],p.orderByFields=t.orderByFields,i&&(p.geometry=i,p.spatialRelationship="intersects"),r?.distance&&(p.distance=r.distance),r?.units&&(p.units=r.units),p.outSpatialReference=e.spatialReference;let m,g;try{m=l?await s.queryFeatureCount(p):await o.queryFeatureCount(p),m>0&&m<=Fi&&(g=l?await s.queryFeatures(p):await o.queryFeatures(p))}catch(C){console.warn("Client-side query failed, falling back to server:",C),m=await o.queryFeatureCount(p),m>0&&m<=Fi&&(g=await o.queryFeatures(p))}let{objectIds:y,attributes:A}=g?fp(o,g,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:a,summary:`${m} features found`,details:{totalCount:m,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...y&&{objectIds:y,objectIdField:c},...A&&{attributes:A},...m>Fi&&{note:`${m} features found.`}}}};async function Fw({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=Vt(n),s=await Dw(t,o,e,r);return JSON.stringify(s,null,2)}var qw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),Uw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),Bw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("SQL-92 where clause. IMPORTANT: When using geometryFilter.point for point-in-polygon queries, set this to '1=1' to return all features that intersect the point. Only add attribute filters if the user specifically requests them in addition to the spatial query."),orderByFields:d.array(d.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:d.array(d.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:d.union([qw,Uw]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),useCurrentExtent:d.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),Kw=D(Fw,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
188
188
 
189
189
  USE THIS TOOL FOR:
190
190
  - "Show / display / list features where..." \u2014 finding and listing features
@@ -193,26 +193,26 @@ USE THIS TOOL FOR:
193
193
  - Spatial queries \u2014 finding features near/within/intersecting other features
194
194
  - Any question where the user wants to SEE or COUNT matching features
195
195
 
196
- This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:Uw}),hp=[Iw,Ew,Lw,Bw];var zK=new ht(hp,{handleToolErrors:!1});var Kw=N.Root({...kr(),helpInternalState:N({reducer:Go,default:()=>({toolCallMessage:void 0})})}),Ww=(t,e)=>{let r=Array.from(t.values()).find(({layerItem:s})=>s.title?.toLowerCase().includes(e.toLowerCase()));if(!r){let s=Array.from(t.values()).map(a=>a.layerItem.title).join(", ");return`Could not find a layer matching "${e}". Available layers: ${s}`}let n=Array.from(r.fieldRegistry.values()),o=n.map(s=>`- **${s.alias||s.name}** (\`${s.name}\`, ${s.type})${s.description?`: ${s.description}`:""}`).join(`
196
+ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:Bw}),hp=[vw,Ow,jw,Kw];var FK=new ht(hp,{handleToolErrors:!1});var Ww=N.Root({...kr(),helpInternalState:N({reducer:Go,default:()=>({toolCallMessage:void 0})})}),Vw=(t,e)=>{let r=Array.from(t.values()).find(({layerItem:s})=>s.title?.toLowerCase().includes(e.toLowerCase()));if(!r){let s=Array.from(t.values()).map(a=>a.layerItem.title).join(", ");return`Could not find a layer matching "${e}". Available layers: ${s}`}let n=Array.from(r.fieldRegistry.values()),o=n.map(s=>`- **${s.alias||s.name}** (\`${s.name}\`, ${s.type})${s.description?`: ${s.description}`:""}`).join(`
197
197
  `);return`**${r.layerItem.title}** has ${n.length} field(s):
198
198
 
199
- ${o}`},Vw=async({layerTitle:t},e)=>{let r=Xn(e,"layersAndFieldsRegistry");return Ww(r,t)},Gw=D(Vw,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:d.object({layerTitle:d.string().describe("The title or partial title of the layer to list fields for.")})}),Hw=N.Root({...kr(),intent:N({reducer:(t,e)=>e}),arcgisKnowledgeMessages:N({reducer:ho,default:()=>[]}),arcgisKnowledgeToolResult:N({reducer:(t,e)=>e,default:()=>null})});function gp(t){let e=t.map?.allLayers.filter(r=>r.type==="knowledge-graph");if(!e||e?.length!==1)throw new Error("The Knowledge Agent currently only supports maps with exactly one Knowledge Graph Layer.")}function eo(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function ya(t){!t||eo(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function Zo(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("ArcgisKnowledgeAgent context missing");if(!("view"in e))throw new Error("View context missing");let r=e.view;return r.map&&!("activeLinkChartLayer"in r.map)&&gp(r),{view:r}}async function to(t){let e=t?.configurable?.context;if(Jw(t)==="knowledgeGraph")return e;{let r=e.view.map;if(r&&"activeLinkChartLayer"in r){let n=r.knowledgeGraph?.url;if(!n)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await rp(n)}}else{gp(e.view);let n=(e.view.map?.allLayers.find(o=>o.type==="knowledge-graph")).url;if(!n)throw new Error("Knowledge graph url missing from map.");return{knowledgeGraph:await rp(n)}}}}function Jw(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("ArcgisKnowledgeAgent context missing");if("knowledgeGraph"in e&&"view"in e)throw new Error("Knowledge Graph context should only have a view or knowledgeGraph, but never both.");if("knowledgeGraph"in e)return"knowledgeGraph";if("view"in e)return"view";throw new Error("ArcgisKnowledgeAgent context must have either a view or knowledgeGraph property.")}var Ui=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=ha.fromDataModel(e)}},ha=class t{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(e){let r=new t;for(let n of e.entityTypes)r.entityTypes.push(Jo.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(Bi.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:Zw(e.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:e.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(e.spatialReference)),r}static getDataModelTypesSummary(e){let r=e.entityTypes.map(o=>o.name).join(", "),n=e.relationshipTypes.map(o=>o.name).join(", ");return`Entity Types: ${r}.
200
- Relationship Types: ${n}.`}},Jo=class t{constructor(){this.name="",this.properties=[]}static fromEntityType(e){let r=new t;r.name=e.name,r.alias=e.alias?e.alias:void 0,r.role=Qw(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:Yw(n.role),geometryDef:n.fieldType==="esriFieldTypeGeometry"?{geometryType:n.geometryType??"esriGeometryAny",hasM:n.hasM?n.hasM:void 0,hasZ:n.hasZ?n.hasZ:void 0}:void 0};r.properties.push(o)}return r}},Bi=class extends Jo{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=Jo.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},Zw=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},Qw=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function Yw(t){switch(t){case"esriGraphPropertyRegular":return"Regular";case"esriGraphPropertyDocumentName":return"Document_Name";case"esriGraphPropertyDocumentTitle":return"Document_Title";case"esriGraphPropertyDocumentUrl":return"Document_Url";case"esriGraphPropertyDocumentText":return"Document_Text";case"esriGraphPropertyDocumentKeywords":return"Document_Keywords";case"esriGraphPropertyDocumentContentType":return"Document_ContentType";case"esriGraphPropertyDocumentMetadata":return"Document_Metadata";case"esriGraphPropertyDocumentFileExtension":return"Document_FileExtension";case"esriGraphPropertyProvenanceInstanceId":return"Provenance_InstanceId";case"esriGraphPropertyProvenanceSourceType":return"Provenance_SourceType";case"esriGraphPropertyProvenanceSourceName":return"Provenance_SourceName";case"esriGraphPropertyProvenanceSource":return"Provenance_Source";case"esriGraphPropertyProvenanceComment":return"Provenance_Comment";case"esriGraphPropertyProvenanceTypeName":return"Provenance_TypeName";case"esriGraphPropertyProvenancePropertyName":return"Provenance_PropertyName";default:return"Regular"}}function _a(t){return t?.signal}async function Xw(t,e){let r=await gt("arcgis_knowledge_cypher_query_prompt");return e?`${t} ${r}
199
+ ${o}`},Gw=async({layerTitle:t},e)=>{let r=Xn(e,"layersAndFieldsRegistry");return Vw(r,t)},Hw=D(Gw,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:d.object({layerTitle:d.string().describe("The title or partial title of the layer to list fields for.")})}),Jw=N.Root({...kr(),intent:N({reducer:(t,e)=>e}),arcgisKnowledgeMessages:N({reducer:ho,default:()=>[]}),arcgisKnowledgeToolResult:N({reducer:(t,e)=>e,default:()=>null})});function gp(t){let e=t.map?.allLayers.filter(r=>r.type==="knowledge-graph");if(!e||e?.length!==1)throw new Error("The Knowledge Agent currently only supports maps with exactly one Knowledge Graph Layer.")}function eo(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function ya(t){!t||eo(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function Zo(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("ArcgisKnowledgeAgent context missing");if(!("view"in e))throw new Error("View context missing");let r=e.view;return r.map&&!("activeLinkChartLayer"in r.map)&&gp(r),{view:r}}async function to(t){let e=t?.configurable?.context;if(Zw(t)==="knowledgeGraph")return e;{let r=e.view.map;if(r&&"activeLinkChartLayer"in r){let n=r.knowledgeGraph?.url;if(!n)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await rp(n)}}else{gp(e.view);let n=(e.view.map?.allLayers.find(o=>o.type==="knowledge-graph")).url;if(!n)throw new Error("Knowledge graph url missing from map.");return{knowledgeGraph:await rp(n)}}}}function Zw(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("ArcgisKnowledgeAgent context missing");if("knowledgeGraph"in e&&"view"in e)throw new Error("Knowledge Graph context should only have a view or knowledgeGraph, but never both.");if("knowledgeGraph"in e)return"knowledgeGraph";if("view"in e)return"view";throw new Error("ArcgisKnowledgeAgent context must have either a view or knowledgeGraph property.")}var Ui=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=ha.fromDataModel(e)}},ha=class t{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(e){let r=new t;for(let n of e.entityTypes)r.entityTypes.push(Jo.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(Bi.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:Qw(e.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:e.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(e.spatialReference)),r}static getDataModelTypesSummary(e){let r=e.entityTypes.map(o=>o.name).join(", "),n=e.relationshipTypes.map(o=>o.name).join(", ");return`Entity Types: ${r}.
200
+ Relationship Types: ${n}.`}},Jo=class t{constructor(){this.name="",this.properties=[]}static fromEntityType(e){let r=new t;r.name=e.name,r.alias=e.alias?e.alias:void 0,r.role=Yw(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:Xw(n.role),geometryDef:n.fieldType==="esriFieldTypeGeometry"?{geometryType:n.geometryType??"esriGeometryAny",hasM:n.hasM?n.hasM:void 0,hasZ:n.hasZ?n.hasZ:void 0}:void 0};r.properties.push(o)}return r}},Bi=class extends Jo{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=Jo.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},Qw=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},Yw=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function Xw(t){switch(t){case"esriGraphPropertyRegular":return"Regular";case"esriGraphPropertyDocumentName":return"Document_Name";case"esriGraphPropertyDocumentTitle":return"Document_Title";case"esriGraphPropertyDocumentUrl":return"Document_Url";case"esriGraphPropertyDocumentText":return"Document_Text";case"esriGraphPropertyDocumentKeywords":return"Document_Keywords";case"esriGraphPropertyDocumentContentType":return"Document_ContentType";case"esriGraphPropertyDocumentMetadata":return"Document_Metadata";case"esriGraphPropertyDocumentFileExtension":return"Document_FileExtension";case"esriGraphPropertyProvenanceInstanceId":return"Provenance_InstanceId";case"esriGraphPropertyProvenanceSourceType":return"Provenance_SourceType";case"esriGraphPropertyProvenanceSourceName":return"Provenance_SourceName";case"esriGraphPropertyProvenanceSource":return"Provenance_Source";case"esriGraphPropertyProvenanceComment":return"Provenance_Comment";case"esriGraphPropertyProvenanceTypeName":return"Provenance_TypeName";case"esriGraphPropertyProvenancePropertyName":return"Provenance_PropertyName";default:return"Regular"}}function _a(t){return t?.signal}async function eb(t,e){let r=await gt("arcgis_knowledge_cypher_query_prompt");return e?`${t} ${r}
201
201
 
202
202
  Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
203
203
 
204
204
  Attempt Number: ${e.attemptCount}
205
205
  Execution Error: ${e.executionError}
206
206
  Failed Query:
207
- ${e.failedGraphQuery}`:`${t} ${r}`}async function eb(t,e,r,n){let{graphQuery:o,explanation:s}=await Qi(t,e,r,n);return{graphQuery:o,explanation:s}}async function Qi(t,e,r,n,o){let s={message:await Xw(t,o),context:new Ui(e)},a=_a(n);await ee({text:"Attempting to generate a cypher query from your prompt..."},n);let i=await Xd(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:Yd.findCredential(Cr.getDefault().url)?.token??""},signal:a});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});let u=!1,l=Date.now(),c=i.data.sequenceNumber,p="",m="",g=1;for(;!u;){await new Promise(A=>setTimeout(A,1e3)),await ee({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,g)}`},n),g=g%3+1;let y=await Xd(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:c}),headers:{"Content-Type":"application/json",token:Yd.findCredential(Cr.getDefault().url)?.token??""},signal:a});if(y.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${y.httpStatus}`,{cause:y.data});if(y.data.context?.kind){if(y.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${y.data.message}`,{cause:y.data});p=y.data.context.graphQuery,m=y.data.message||"",u=!0}else if(!y.data.hasMore)u=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");c=y.data.sequenceNumber}return{graphQuery:p,explanation:m}}function tb(t,e){Qn(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function Qn(t,e){if(!(!t||typeof t!="object")){if(nb(t))for(let r of t.path)Qn(r,e);else if(rb(t))e(t);else if(Array.isArray(t))for(let r of t)Qn(r,e);else if(ob(t))for(let r of Object.values(t.properties??{}))Qn(r,e)}}function rb(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function nb(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function ob(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function sb(t,e){let r=[],n=[],o=[[e.dataModel.entityTypes,r],[e.dataModel.relationshipTypes,n]];for(let[s,a]of o)for(let i of s){let u=t.getMemberIdsByType(i.name);a.push(...u)}return{entityIds:r,relationshipIds:n}}function ab(t,e){let r={entityIds:new Array,relationshipIds:new Array},n=[],o=t?.allLayers.find(i=>i.type==="knowledge-graph")?.inclusionModeDefinition;if(!o)return{allNamedTypesFullyDynamic:!0,bindParameters:r,nonDynamicTypes:n};let s=[[e.dataModel.entityTypes,r.entityIds],[e.dataModel.relationshipTypes,r.relationshipIds]],a=!0;for(let[i,u]of s)for(let l of i){let c=o.namedTypeDefinitions.get(l.name);if(!c){a=!1,n.push(l.name);continue}if(!c.useAllData){a=!1,n.push(l.name);for(let[p]of c.members||[])u.push(p)}}return{allNamedTypesFullyDynamic:a,bindParameters:r,nonDynamicTypes:n}}var Yn=3;function yp(t,e=100){let r={};for(let n of Object.entries(t.properties??{})){let[o,s]=n;typeof s=="string"&&s.length>e?r[o]=`${s.slice(0,e)}... (truncated, original length: ${s.length})`:r[o]=s}return t.properties=r,t}function ro(t){return typeof t!="object"||t===null?String(t):"details"in t&&typeof t.details=="object"&&t.details!==null&&"errorMessage"in t.details&&typeof t.details.errorMessage=="string"?t.details.errorMessage:"message"in t&&typeof t.message=="string"?t.message:String(t)}var ib=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:n,requestOptions:o,queryRowLimit:s,queryTimeoutMs:a})=>{let i=null,u=r,l=new AbortController,c=o?.signal,p=()=>{l.abort(c?.reason)};c&&(c.aborted?l.abort(c.reason):c.addEventListener("abort",p,{once:!0}));try{let m=await Hg(t,e,o);i=m.resultHeader;let g=m.resultRowsStream.getReader(),y=0,A=Date.now(),C=!1;for(;;){let{done:h,value:b}=await g.read();if(h)break;if(!C&&a&&Date.now()-A>a)return l.abort(),{type:"timeout"};for(let S of b){if(y++,s&&y>s)return l.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:u};u=n(u,S)}}}catch(m){return l.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:ro(m),error:m}}finally{c?.removeEventListener("abort",p)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function _p({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:o,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u,config:l}){let c;for(let p=1;p<=Yn;p++){let m;try{m=await Qi(t,r.dataModel,n,l,c)}catch(C){return{type:"generation-error",errorMessage:ro(C),error:C}}await ee({text:`Attempting to execute query: ${m.graphQuery.substring(0,500)}${m.graphQuery.length>500?"...":""}`},l);let g=await lb(m.graphQuery,e),y=await ib({kg:r,queryParams:new up({openCypherQuery:m.graphQuery,bindParameters:g}),targetStructure:o,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u}),A=y.type==="aborted"?"Query execution was aborted.":y.type==="timeout"?"Query execution timed out.":y.type==="error"?`Query failed with error: ${y.errorMessage}`:"";if(y.type==="success")return{type:"success",graphQuery:m.graphQuery,explanation:m.explanation,rowLimitReached:y.rowLimitReached,resultHeader:y.resultHeader,processedResult:y.processedResult};if(y.type==="aborted")return{type:"aborted",errorMessage:A,graphQuery:m.graphQuery,explanation:m.explanation};if(p>=Yn)return y.type==="timeout"?{type:"timeout",errorMessage:A,graphQuery:m.graphQuery,explanation:m.explanation}:{type:"execution-error",errorMessage:A,error:y.error,graphQuery:m.graphQuery,explanation:m.explanation};c={failedGraphQuery:m.graphQuery,executionError:A,attemptCount:p},await ee({text:`Attempt ${p} failed with error: ${A}. Retrying...`},l)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${Yn} attempts.`)}var lb=async(t,e)=>{if(!e)return{};let{bindParameters:r,parseErrors:n}=await Qg(t);if(n)return e;let o={};for(let s of r)s in e&&(o[s]=e[s]);return o},ub=async({kg:t,searchQuery:e,typeCategoryFilter:r,namedTypesFilter:n,searchResultLimit:o,requestOptions:s})=>{let a=[],i=[r];r==="both"&&!t.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let u=o??1/0;try{for(let l of i){let c=u-a.length;if(c<=0)break;let p=(await Jg(t,new Zg({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:n??void 0,num:c}),s)).resultRowsStream.getReader(),m=!1;for(;!m;){let{done:g,value:y}=await p.read();if(g){m=!0;break}for(let A of y)for(let C of A)a.push(C)}}}catch(l){let c=ro(l);return s?.signal?.aborted?{type:"aborted",errorMessage:c,error:l}:{type:"error",errorMessage:c,error:l}}return{type:"success",results:a}},wp="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function bp({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:n=!1}){let o=[t];if(n&&o.push(wp),!eo(e)){let c=await gt("arcgis_knowledge_current_lc_context"),p=sb(e.map,r);return o.push(c),{enhancedPrompt:o.join(`
207
+ ${e.failedGraphQuery}`:`${t} ${r}`}async function tb(t,e,r,n){let{graphQuery:o,explanation:s}=await Qi(t,e,r,n);return{graphQuery:o,explanation:s}}async function Qi(t,e,r,n,o){let s={message:await eb(t,o),context:new Ui(e)},a=_a(n);await ee({text:"Attempting to generate a cypher query from your prompt..."},n);let i=await Xd(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:Yd.findCredential(Cr.getDefault().url)?.token??""},signal:a});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});let u=!1,l=Date.now(),c=i.data.sequenceNumber,p="",m="",g=1;for(;!u;){await new Promise(A=>setTimeout(A,1e3)),await ee({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,g)}`},n),g=g%3+1;let y=await Xd(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:c}),headers:{"Content-Type":"application/json",token:Yd.findCredential(Cr.getDefault().url)?.token??""},signal:a});if(y.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${y.httpStatus}`,{cause:y.data});if(y.data.context?.kind){if(y.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${y.data.message}`,{cause:y.data});p=y.data.context.graphQuery,m=y.data.message||"",u=!0}else if(!y.data.hasMore)u=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");c=y.data.sequenceNumber}return{graphQuery:p,explanation:m}}function rb(t,e){Qn(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function Qn(t,e){if(!(!t||typeof t!="object")){if(ob(t))for(let r of t.path)Qn(r,e);else if(nb(t))e(t);else if(Array.isArray(t))for(let r of t)Qn(r,e);else if(sb(t))for(let r of Object.values(t.properties??{}))Qn(r,e)}}function nb(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function ob(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function sb(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function ab(t,e){let r=[],n=[],o=[[e.dataModel.entityTypes,r],[e.dataModel.relationshipTypes,n]];for(let[s,a]of o)for(let i of s){let u=t.getMemberIdsByType(i.name);a.push(...u)}return{entityIds:r,relationshipIds:n}}function ib(t,e){let r={entityIds:new Array,relationshipIds:new Array},n=[],o=t?.allLayers.find(i=>i.type==="knowledge-graph")?.inclusionModeDefinition;if(!o)return{allNamedTypesFullyDynamic:!0,bindParameters:r,nonDynamicTypes:n};let s=[[e.dataModel.entityTypes,r.entityIds],[e.dataModel.relationshipTypes,r.relationshipIds]],a=!0;for(let[i,u]of s)for(let l of i){let c=o.namedTypeDefinitions.get(l.name);if(!c){a=!1,n.push(l.name);continue}if(!c.useAllData){a=!1,n.push(l.name);for(let[p]of c.members||[])u.push(p)}}return{allNamedTypesFullyDynamic:a,bindParameters:r,nonDynamicTypes:n}}var Yn=3;function yp(t,e=100){let r={};for(let n of Object.entries(t.properties??{})){let[o,s]=n;typeof s=="string"&&s.length>e?r[o]=`${s.slice(0,e)}... (truncated, original length: ${s.length})`:r[o]=s}return t.properties=r,t}function ro(t){return typeof t!="object"||t===null?String(t):"details"in t&&typeof t.details=="object"&&t.details!==null&&"errorMessage"in t.details&&typeof t.details.errorMessage=="string"?t.details.errorMessage:"message"in t&&typeof t.message=="string"?t.message:String(t)}var lb=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:n,requestOptions:o,queryRowLimit:s,queryTimeoutMs:a})=>{let i=null,u=r,l=new AbortController,c=o?.signal,p=()=>{l.abort(c?.reason)};c&&(c.aborted?l.abort(c.reason):c.addEventListener("abort",p,{once:!0}));try{let m=await Jg(t,e,o);i=m.resultHeader;let g=m.resultRowsStream.getReader(),y=0,A=Date.now(),C=!1;for(;;){let{done:h,value:b}=await g.read();if(h)break;if(!C&&a&&Date.now()-A>a)return l.abort(),{type:"timeout"};for(let S of b){if(y++,s&&y>s)return l.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:u};u=n(u,S)}}}catch(m){return l.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:ro(m),error:m}}finally{c?.removeEventListener("abort",p)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function _p({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:o,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u,config:l}){let c;for(let p=1;p<=Yn;p++){let m;try{m=await Qi(t,r.dataModel,n,l,c)}catch(C){return{type:"generation-error",errorMessage:ro(C),error:C}}await ee({text:`Attempting to execute query: ${m.graphQuery.substring(0,500)}${m.graphQuery.length>500?"...":""}`},l);let g=await ub(m.graphQuery,e),y=await lb({kg:r,queryParams:new up({openCypherQuery:m.graphQuery,bindParameters:g}),targetStructure:o,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u}),A=y.type==="aborted"?"Query execution was aborted.":y.type==="timeout"?"Query execution timed out.":y.type==="error"?`Query failed with error: ${y.errorMessage}`:"";if(y.type==="success")return{type:"success",graphQuery:m.graphQuery,explanation:m.explanation,rowLimitReached:y.rowLimitReached,resultHeader:y.resultHeader,processedResult:y.processedResult};if(y.type==="aborted")return{type:"aborted",errorMessage:A,graphQuery:m.graphQuery,explanation:m.explanation};if(p>=Yn)return y.type==="timeout"?{type:"timeout",errorMessage:A,graphQuery:m.graphQuery,explanation:m.explanation}:{type:"execution-error",errorMessage:A,error:y.error,graphQuery:m.graphQuery,explanation:m.explanation};c={failedGraphQuery:m.graphQuery,executionError:A,attemptCount:p},await ee({text:`Attempt ${p} failed with error: ${A}. Retrying...`},l)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${Yn} attempts.`)}var ub=async(t,e)=>{if(!e)return{};let{bindParameters:r,parseErrors:n}=await Yg(t);if(n)return e;let o={};for(let s of r)s in e&&(o[s]=e[s]);return o},cb=async({kg:t,searchQuery:e,typeCategoryFilter:r,namedTypesFilter:n,searchResultLimit:o,requestOptions:s})=>{let a=[],i=[r];r==="both"&&!t.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let u=o??1/0;try{for(let l of i){let c=u-a.length;if(c<=0)break;let p=(await Zg(t,new Qg({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:n??void 0,num:c}),s)).resultRowsStream.getReader(),m=!1;for(;!m;){let{done:g,value:y}=await p.read();if(g){m=!0;break}for(let A of y)for(let C of A)a.push(C)}}}catch(l){let c=ro(l);return s?.signal?.aborted?{type:"aborted",errorMessage:c,error:l}:{type:"error",errorMessage:c,error:l}}return{type:"success",results:a}},wp="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function bp({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:n=!1}){let o=[t];if(n&&o.push(wp),!eo(e)){let c=await gt("arcgis_knowledge_current_lc_context"),p=ab(e.map,r);return o.push(c),{enhancedPrompt:o.join(`
208
208
 
209
- `),bindParameters:p,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:a,bindParameters:i,nonDynamicTypes:u}=ab(s,r);if(a)return{enhancedPrompt:o.join(`
209
+ `),bindParameters:p,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:a,bindParameters:i,nonDynamicTypes:u}=ib(s,r);if(a)return{enhancedPrompt:o.join(`
210
210
 
211
211
  `),bindParameters:i,allNamedTypesFullyDynamic:!0};let l=(await gt("arcgis_knowledge_current_map_context")).replaceAll("{nonDynamicTypes}",JSON.stringify(u));return o.push(l),{enhancedPrompt:o.join(`
212
212
 
213
- `),bindParameters:i,allNamedTypesFullyDynamic:a}}async function cb(t,e,r,n,o,s){let{view:a}=o,i=await _p({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:new Map,targetStructureReducer:(m,g)=>{for(let y of g)tb(y,m);return m},requestOptions:{signal:_a(s),timeout:s?.timeout},config:s});if(i.type!=="success"){let m=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${m}`)}let{graphQuery:u,explanation:l,processedResult:c}=i,p=Array.from(c.values());return await ee({text:`Query Results parsed into ${p.length} unique relationships and entities. Atempting to add to link chart...`},s),!eo(a)&&a?.map?(await a.map.addRecords(p),await ya(a),{generatedQuery:u,explanation:l,addedIdTypePairs:p}):(await a?.map?.allLayers.find(m=>m.type==="knowledge-graph")?.addRecords(p),{generatedQuery:u,explanation:l,addedIdTypePairs:p})}var da="addRecords",db=d.object({prompt:d.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to add records to the link chart.")}),pb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e),n=Zo(e),{view:o}=n,s=Cr.getDefault().helperServices,{enhancedPrompt:a,bindParameters:i,allNamedTypesFullyDynamic:u}=await bp({prompt:t,view:o,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(u)return{toolName:da,status:"success",summary:"No records have been added to the map because all data in the knowledge graph is contained in the map.",details:{generatedQuery:"N/A",explanation:"All named types in the knowledge graph are fully dynamic and therefore all data is already contained in the map. No records have been added.",addedIdTypePairs:[]}};try{let{generatedQuery:l,explanation:c,addedIdTypePairs:p}=await cb(a,i,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,n,e);return{toolName:da,status:"success",summary:`Records added successfully. Cypher Query used: ${l}
213
+ `),bindParameters:i,allNamedTypesFullyDynamic:a}}async function db(t,e,r,n,o,s){let{view:a}=o,i=await _p({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:new Map,targetStructureReducer:(m,g)=>{for(let y of g)rb(y,m);return m},requestOptions:{signal:_a(s),timeout:s?.timeout},config:s});if(i.type!=="success"){let m=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${m}`)}let{graphQuery:u,explanation:l,processedResult:c}=i,p=Array.from(c.values());return await ee({text:`Query Results parsed into ${p.length} unique relationships and entities. Atempting to add to link chart...`},s),!eo(a)&&a?.map?(await a.map.addRecords(p),await ya(a),{generatedQuery:u,explanation:l,addedIdTypePairs:p}):(await a?.map?.allLayers.find(m=>m.type==="knowledge-graph")?.addRecords(p),{generatedQuery:u,explanation:l,addedIdTypePairs:p})}var da="addRecords",pb=d.object({prompt:d.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to add records to the link chart.")}),mb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e),n=Zo(e),{view:o}=n,s=Cr.getDefault().helperServices,{enhancedPrompt:a,bindParameters:i,allNamedTypesFullyDynamic:u}=await bp({prompt:t,view:o,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(u)return{toolName:da,status:"success",summary:"No records have been added to the map because all data in the knowledge graph is contained in the map.",details:{generatedQuery:"N/A",explanation:"All named types in the knowledge graph are fully dynamic and therefore all data is already contained in the map. No records have been added.",addedIdTypePairs:[]}};try{let{generatedQuery:l,explanation:c,addedIdTypePairs:p}=await db(a,i,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,n,e);return{toolName:da,status:"success",summary:`Records added successfully. Cypher Query used: ${l}
214
214
 
215
- Number of records added: ${p.length}`,details:{generatedQuery:l,explanation:c,addedIdTypePairs:p}}}catch(l){let c=ro(l);return{toolName:da,status:"error",errorMessage:`Failed to add records to the link chart. ${c}`,error:l}}},mb=D(pb,{name:da,description:`Adds records (entities or relationships) to the current link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the records to be added to the link chart. The user should have explicitly requested to add records to the current link chart from their prompt. "add to new link chart" is not a valid prompt for this tool.
215
+ Number of records added: ${p.length}`,details:{generatedQuery:l,explanation:c,addedIdTypePairs:p}}}catch(l){let c=ro(l);return{toolName:da,status:"error",errorMessage:`Failed to add records to the link chart. ${c}`,error:l}}},fb=D(mb,{name:da,description:`Adds records (entities or relationships) to the current link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the records to be added to the link chart. The user should have explicitly requested to add records to the current link chart from their prompt. "add to new link chart" is not a valid prompt for this tool.
216
216
 
217
217
  example prompts:
218
218
  - "add all suppliers and the parts they produce to the link chart"
@@ -222,15 +222,15 @@ Number of records added: ${p.length}`,details:{generatedQuery:l,explanation:c,ad
222
222
  - "expand company x through all the buildings it owns"
223
223
  - "connect company x and company y"
224
224
  - "connect all buildings on the link chart"
225
- `,schema:db});async function fb(t,e){return await e.map?.applyLayout(t),await ya(e),{appliedLayout:t}}var Ki="applyLayout",hb=d.object({layout:d.enum(["organic-standard","organic-community","basic-grid","hierarchical-bottom-to-top","radial-root-centric","tree-left-to-right","geographic-organic-standard","chronological-mono-timeline","chronological-multi-timeline"]).describe("The layout mode to apply to the link chart. The value must be one of the following: organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline, chronological-multi-timeline")}),gb=async({layout:t},e)=>{let{view:r}=Zo(e);if(eo(r))return{toolName:Ki,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:n}=await fb(t,r);return{toolName:Ki,status:"success",summary:`Successfully applied layout: ${n}.`,details:{appliedLayout:n}}}},yb=D(gb,{name:Ki,description:"Apply a diagram layout to the link chart",schema:hb});async function _b(t,e){return e.map?.changeNonspatialDataDisplay(t),await ya(e),{appliedNonspatialDataDisplayMode:t}}var Wi="changeNonspatialVisibility",wb=d.object({setting:d.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),bb=async({setting:t},e)=>{let{view:r}=Zo(e);if(eo(r))return{toolName:Wi,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:n}=await _b(t,r);return{toolName:Wi,status:"success",summary:`Successfully applied nonspatial visibility setting: ${n}.`,details:{appliedNonspatialDataDisplayMode:n}}}},xb=D(bb,{name:Wi,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:wb});async function Ab(t,e,r,n,o){let s,a="";for(let i=1;i<=Yn;i++){let{graphQuery:u,explanation:l}=await Qi(t,e.dataModel,r,o,s);try{await ee({text:`Attempting to create link chart from derived query: ${u}`},o);let c=await Gg.fromCypherQuery(e,new up({openCypherQuery:u}));await ee({text:"Link chart created successfully, loading..."},o),await c.load();let p=n.map;return n.map=c,await n.when(),await sp.whenOnce(()=>!n.updating),c.entityCount===0&&c.relationshipCount===0?(n.map===c&&(n.map=p),c.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
225
+ `,schema:pb});async function hb(t,e){return await e.map?.applyLayout(t),await ya(e),{appliedLayout:t}}var Ki="applyLayout",gb=d.object({layout:d.enum(["organic-standard","organic-community","basic-grid","hierarchical-bottom-to-top","radial-root-centric","tree-left-to-right","geographic-organic-standard","chronological-mono-timeline","chronological-multi-timeline"]).describe("The layout mode to apply to the link chart. The value must be one of the following: organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline, chronological-multi-timeline")}),yb=async({layout:t},e)=>{let{view:r}=Zo(e);if(eo(r))return{toolName:Ki,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:n}=await hb(t,r);return{toolName:Ki,status:"success",summary:`Successfully applied layout: ${n}.`,details:{appliedLayout:n}}}},_b=D(yb,{name:Ki,description:"Apply a diagram layout to the link chart",schema:gb});async function wb(t,e){return e.map?.changeNonspatialDataDisplay(t),await ya(e),{appliedNonspatialDataDisplayMode:t}}var Wi="changeNonspatialVisibility",bb=d.object({setting:d.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),xb=async({setting:t},e)=>{let{view:r}=Zo(e);if(eo(r))return{toolName:Wi,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:n}=await wb(t,r);return{toolName:Wi,status:"success",summary:`Successfully applied nonspatial visibility setting: ${n}.`,details:{appliedNonspatialDataDisplayMode:n}}}},Ab=D(xb,{name:Wi,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:bb});async function Ib(t,e,r,n,o){let s,a="";for(let i=1;i<=Yn;i++){let{graphQuery:u,explanation:l}=await Qi(t,e.dataModel,r,o,s);try{await ee({text:`Attempting to create link chart from derived query: ${u}`},o);let c=await Hg.fromCypherQuery(e,new up({openCypherQuery:u}));await ee({text:"Link chart created successfully, loading..."},o),await c.load();let p=n.map;return n.map=c,await n.when(),await sp.whenOnce(()=>!n.updating),c.entityCount===0&&c.relationshipCount===0?(n.map===c&&(n.map=p),c.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
226
226
  ${u}
227
227
 
228
- Explanation: ${l}`}):(await ya(n),{type:"success",graphQuery:u,explanation:l})}catch(c){let p=ro(c);if(i>=Yn){a=p;break}s={failedGraphQuery:u,executionError:p,attemptCount:i},await ee({text:`Attempt ${i} to create link chart failed with error: ${p}. Retrying ...`},o)}}return{type:"error",errorMessage:`Failed to create link chart after ${Yn} attempts. Last error: ${a}`}}var pa="createLinkChart",Ib=d.object({prompt:d.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to create a link chart visualization. Only include information relevant to generating a cypher query. Do not suggest entity types, relationship types or properties. Do not include limits or formatting instructions for the query results unless specifically requested by the user. The prompt should be focused on the data the user wants to see in the link chart, not how to generate it.")}),vb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e),{view:n}=Zo(e);if(eo(n))return{toolName:pa,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=Cr.getDefault().helperServices,s=await Ab(`${t}
228
+ Explanation: ${l}`}):(await ya(n),{type:"success",graphQuery:u,explanation:l})}catch(c){let p=ro(c);if(i>=Yn){a=p;break}s={failedGraphQuery:u,executionError:p,attemptCount:i},await ee({text:`Attempt ${i} to create link chart failed with error: ${p}. Retrying ...`},o)}}return{type:"error",errorMessage:`Failed to create link chart after ${Yn} attempts. Last error: ${a}`}}var pa="createLinkChart",vb=d.object({prompt:d.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to create a link chart visualization. Only include information relevant to generating a cypher query. Do not suggest entity types, relationship types or properties. Do not include limits or formatting instructions for the query results unless specifically requested by the user. The prompt should be focused on the data the user wants to see in the link chart, not how to generate it.")}),Tb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e),{view:n}=Zo(e);if(eo(n))return{toolName:pa,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=Cr.getDefault().helperServices,s=await Ib(`${t}
229
229
 
230
230
  ${wp}`,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,n,e);if(s.type==="error")return{toolName:pa,status:"error",errorMessage:s.errorMessage,error:new Error};let{graphQuery:a,explanation:i}=s;return{toolName:pa,status:"success",summary:`Link chart created successfully. Cypher Query used to create the link chart:
231
231
  ${a}
232
232
 
233
- Explanation: ${i}`,details:{generatedQuery:a,explanation:i}}}},Tb=D(vb,{name:pa,description:"Creates a new link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the new link chart. The user should have explicitly requested the creation of a new link chart from their prompt using language like 'create new link chart' or 'add to new link chart'.",schema:Ib}),Vi="queryGraphData",Sb=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. Only include entity types, relationship types or properties if they are provided in the user prompt or prior steps. Do not suggest entity types, relationship types or properties. Do not include limits, information on what to return, instructions on how to write the query, or formatting instructions for the query results unless specifically requested by the user.")}),kb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e),n=Cr.getDefault().helperServices,o=t,s=null,a=null;try{({view:a}=Zo(e))}catch{}a&&({enhancedPrompt:o,bindParameters:s}=await bp({prompt:t,view:a,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let i=await _p({prompt:o,bindParameters:s,kg:r,graphQueryServiceUrl:`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(A,C)=>(A.push(C),A),requestOptions:{signal:_a(e),timeout:e?.timeout},config:e});if(i.type!=="success"){let A=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;return{toolName:Vi,status:"error",errorMessage:`Failed to query the knowledge graph. ${A}`,error:"error"in i?i.error:null}}let{graphQuery:u,explanation:l,processedResult:c,resultHeader:p}=i,m=p.headerKeys;for(let A of c)for(let C of A)Qn(C,h=>yp(h));let g=50,y=c.slice(0,g).map(A=>JSON.stringify(A));return{toolName:Vi,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
233
+ Explanation: ${i}`,details:{generatedQuery:a,explanation:i}}}},Sb=D(Tb,{name:pa,description:"Creates a new link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the new link chart. The user should have explicitly requested the creation of a new link chart from their prompt using language like 'create new link chart' or 'add to new link chart'.",schema:vb}),Vi="queryGraphData",kb=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. Only include entity types, relationship types or properties if they are provided in the user prompt or prior steps. Do not suggest entity types, relationship types or properties. Do not include limits, information on what to return, instructions on how to write the query, or formatting instructions for the query results unless specifically requested by the user.")}),Cb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e),n=Cr.getDefault().helperServices,o=t,s=null,a=null;try{({view:a}=Zo(e))}catch{}a&&({enhancedPrompt:o,bindParameters:s}=await bp({prompt:t,view:a,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let i=await _p({prompt:o,bindParameters:s,kg:r,graphQueryServiceUrl:`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(A,C)=>(A.push(C),A),requestOptions:{signal:_a(e),timeout:e?.timeout},config:e});if(i.type!=="success"){let A=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;return{toolName:Vi,status:"error",errorMessage:`Failed to query the knowledge graph. ${A}`,error:"error"in i?i.error:null}}let{graphQuery:u,explanation:l,processedResult:c,resultHeader:p}=i,m=p.headerKeys;for(let A of c)for(let C of A)Qn(C,h=>yp(h));let g=50,y=c.slice(0,g).map(A=>JSON.stringify(A));return{toolName:Vi,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
234
234
 
235
235
  \`\`\`cypher
236
236
  ${u}
@@ -247,16 +247,16 @@ ${y.length>g?`Showing top ${g} results:
247
247
 
248
248
  `}${y.join(`
249
249
  `)}
250
- `,details:{generatedQuery:u,explanation:l,resultHeader:p,queryResults:c}}},Cb=D(kb,{name:Vi,description:"Allows users to explore the data in their knowledge graph via cypher query. Generates and executes a cypher query based on the user's inquiry into the knowledge graph, and displays the results in the chat pane without modifying the user's link chart if any. Use this tool when the user is asking an exploratory question about their data as a whole that can be answered via cypher query, for example 'What are the top 5 suppliers by total parts cost?' or 'How many employees do we have in each department?'.",schema:Sb}),Gi="generateCypher",Eb=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),Ob=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e),n=Cr.getDefault().helperServices;try{let{graphQuery:o,explanation:s}=await eb(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:Gi,status:"success",summary:`Generated Graph Query:
250
+ `,details:{generatedQuery:u,explanation:l,resultHeader:p,queryResults:c}}},Eb=D(Cb,{name:Vi,description:"Allows users to explore the data in their knowledge graph via cypher query. Generates and executes a cypher query based on the user's inquiry into the knowledge graph, and displays the results in the chat pane without modifying the user's link chart if any. Use this tool when the user is asking an exploratory question about their data as a whole that can be answered via cypher query, for example 'What are the top 5 suppliers by total parts cost?' or 'How many employees do we have in each department?'.",schema:kb}),Gi="generateCypher",Ob=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),Mb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e),n=Cr.getDefault().helperServices;try{let{graphQuery:o,explanation:s}=await tb(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:Gi,status:"success",summary:`Generated Graph Query:
251
251
  ${o}
252
252
 
253
- Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=ro(o);return{toolName:Gi,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},Mb=D(Ob,{name:Gi,description:"Generates an Open Cypher query based on the user's prompt which represents an inquiry into the data of the knowledge service and its graph database, attempting to filter based on certain conditions and traverse specified relationships. The generated query should be syntactically correct and optimized for performance.",schema:Eb}),Pb=t=>{let e=t.dataModel,r=new Map;for(let i of e.searchIndexes)if(i.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[u,l]of i.searchProperties.entries()){let c=r.get(u)??new Set;l.propertyNames.forEach(p=>c.add(p)),r.set(u,c)}let n=e.entityTypes.filter(i=>r.has(i.name)),o=e.relationshipTypes.filter(i=>r.has(i.name)),s=`Entity Types:
253
+ Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=ro(o);return{toolName:Gi,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},Pb=D(Mb,{name:Gi,description:"Generates an Open Cypher query based on the user's prompt which represents an inquiry into the data of the knowledge service and its graph database, attempting to filter based on certain conditions and traverse specified relationships. The generated query should be syntactically correct and optimized for performance.",schema:Ob}),Rb=t=>{let e=t.dataModel,r=new Map;for(let i of e.searchIndexes)if(i.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[u,l]of i.searchProperties.entries()){let c=r.get(u)??new Set;l.propertyNames.forEach(p=>c.add(p)),r.set(u,c)}let n=e.entityTypes.filter(i=>r.has(i.name)),o=e.relationshipTypes.filter(i=>r.has(i.name)),s=`Entity Types:
254
254
  ${n.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
255
255
  `)}`,a=`Relationship Types:
256
256
  ${o.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
257
257
  `)}`;return`${s}
258
258
 
259
- ${a}`};async function Rb(t,e,r){let n=await gt("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:t,dataModelForSearch:Pb(e)},s=d.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),a=d.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),i=d.array(d.enum(e.dataModel.entityTypes.map(l=>l.name).concat(e.dataModel.relationshipTypes.map(l=>l.name)))).min(1),u=d.object({query:d.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:i.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:s,resultLimit:a});return await Vo({promptText:n,inputVariables:o,schema:u,config:r})}var Hi="searchGraphData",Nb=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph, from which a lucene search query will be generated and executed against the graph to return relevant results.")}),$b=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e);await ee({text:"Generating search query for the user inquiry"},e);let n=await Rb(t,r,e);await ee({text:"Executing graph search with generated search query"},e);let o=await ub({kg:r,searchQuery:n.query,typeCategoryFilter:n.typeCategoryFilter,namedTypesFilter:n.typeFilters,searchResultLimit:n.resultLimit,requestOptions:{signal:_a(e),timeout:e?.timeout}});if(o.type!=="success")return{toolName:Hi,status:"error",errorMessage:o.errorMessage,error:"error"in o?o.error:null};for(let i of o.results)Qn(i,u=>yp(u));let s=10,a=o.results.slice(0,s);return{toolName:Hi,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
259
+ ${a}`};async function Nb(t,e,r){let n=await gt("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:t,dataModelForSearch:Rb(e)},s=d.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),a=d.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),i=d.array(d.enum(e.dataModel.entityTypes.map(l=>l.name).concat(e.dataModel.relationshipTypes.map(l=>l.name)))).min(1),u=d.object({query:d.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:i.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:s,resultLimit:a});return await Vo({promptText:n,inputVariables:o,schema:u,config:r})}var Hi="searchGraphData",$b=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph, from which a lucene search query will be generated and executed against the graph to return relevant results.")}),Lb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await to(e);await ee({text:"Generating search query for the user inquiry"},e);let n=await Nb(t,r,e);await ee({text:"Executing graph search with generated search query"},e);let o=await cb({kg:r,searchQuery:n.query,typeCategoryFilter:n.typeCategoryFilter,namedTypesFilter:n.typeFilters,searchResultLimit:n.resultLimit,requestOptions:{signal:_a(e),timeout:e?.timeout}});if(o.type!=="success")return{toolName:Hi,status:"error",errorMessage:o.errorMessage,error:"error"in o?o.error:null};for(let i of o.results)Qn(i,u=>yp(u));let s=10,a=o.results.slice(0,s);return{toolName:Hi,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
260
260
  Query: ${n.query}
261
261
  Type Category Filter: ${n.typeCategoryFilter}
262
262
  Named Type Filters: ${n.typeFilters?n.typeFilters.join(", "):"None"}
@@ -267,7 +267,7 @@ ${a}`};async function Rb(t,e,r){let n=await gt("arcgis_knowledge_lucene_generati
267
267
  ${o.results.length>s?`Showing top ${s} results:
268
268
 
269
269
  `:""}${a.map(i=>JSON.stringify(i)).join(`
270
- `)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},Lb=D($b,{name:Hi,description:`
270
+ `)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},jb=D(Lb,{name:Hi,description:`
271
271
  Search the knowledge graph using one or more search texts, using lucene search syntax, against indexed string properties defined on their entities and relationships. Use this tool when the user asks a question about their knowledge graph data as a whole, that could be answered via lucene text search of properties stored on graph elements, e.g requiring fuzzy matching. Otherwise if the inquiry is looking for connected records (e.g. paths), data aggregations, etc explore the data via the queryGraphData tool.
272
272
  Example prompts:
273
273
  - "Find 'Bradley'"
@@ -276,7 +276,7 @@ ${a}`};async function Rb(t,e,r){let n=await gt("arcgis_knowledge_lucene_generati
276
276
  - "Find all references to 'delayed parts shipment'"
277
277
  - "Find all reports authored by someone with the title of 'Researcher'"
278
278
  - "Find the first 5 reports where summary mentions flood zoning near Sacramento, and the organization name is the City of Sacramento Utilities, and tags containing stormwater".
279
- - "Search for all john smiths and show their global ids`,schema:Nb});var tW=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
279
+ - "Search for all john smiths and show their global ids`,schema:$b});var nW=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
280
280
  This includes zooming, panning, centering, or geocoding based on user input. The agent is designed to handle explicit map movement requests. NOTE: DO NOT call this agent if the user asks "show me...", that is meant to be handled by another agent. If the query is about where a certain address is, call this agent.
281
281
 
282
282
  Supported actions:
@@ -295,11 +295,11 @@ ${a}`};async function Rb(t,e,r){let n=await gt("arcgis_knowledge_lucene_generati
295
295
  _Example: “Center the map on San Francisco at scale 50000”_
296
296
  _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
297
297
  _Example: “Go to the Downtown bookmark”_
298
- _Example: “Where is Mount Rainier?”_`;var MW=String.raw`- **layerStyling** — User wants to change how features are drawn or styled on the map based on their data, such as applying color, size, transparency, symbols, or charts according to field values.
298
+ _Example: “Where is Mount Rainier?”_`;var RW=String.raw`- **layerStyling** — User wants to change how features are drawn or styled on the map based on their data, such as applying color, size, transparency, symbols, or charts according to field values.
299
299
  _Example: “Color points by sales amount”_
300
300
  _Example: “Show population density with a color gradient”_
301
301
  _Example: “Create a relationship map between height and depth”_
302
- _Example: “Vary circle sizes according to population”_`;var t2=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
302
+ _Example: “Vary circle sizes according to population”_`;var n2=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
303
303
  The Data Exploration Agent will automatically zoom to the affected features for action taken by this agent. In this case, no need to call navigation tool separately.
304
304
  _Example: “Only show stations where Brand is Shell”_
305
305
  _Example: “Make Shell stations stand out on the map”_
@@ -309,7 +309,7 @@ ${a}`};async function Rb(t,e,r){let n=await gt("arcgis_knowledge_lucene_generati
309
309
  _Example: “What’s the average population?”_
310
310
  _Example: “Which values are in the status field?”_
311
311
 
312
- This agent does NOT handle help/metadata requests such as listing available layers, listing field names/columns/attributes for a layer, or capability guidance.`;var _2=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
312
+ This agent does NOT handle help/metadata requests such as listing available layers, listing field names/columns/attributes for a layer, or capability guidance.`;var b2=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
313
313
 
314
314
  _Example: “Tell me about this map”_
315
315
  _Example: “List all layers in this map”_
@@ -322,7 +322,7 @@ ${a}`};async function Rb(t,e,r){let n=await gt("arcgis_knowledge_lucene_generati
322
322
 
323
323
  IF the user asks map related queries, but those that are not performed by any of the agents, call this agent so we can respond that the requested action is not supported.
324
324
  _Example: "Create a chart"_
325
- _Example: "Create a table"_`;var L2=String.raw`The purpose of this agent is to work with Knowledge Graph data, a graph database technology that represents and stores data as interconnected entities (nodes) and relationships (edges).
325
+ _Example: "Create a table"_`;var z2=String.raw`The purpose of this agent is to work with Knowledge Graph data, a graph database technology that represents and stores data as interconnected entities (nodes) and relationships (edges).
326
326
  This agent has two categories of skills: those that work with an active link chart visualization of a subset of the data in the knowledge graph, and those that work with the knowledge graph data more generally against the entire dataset in the service and database.
327
327
  For link charts, the agent enables users to interact with a link chart by adding new entities (also called nodes) or relationships (also called edges), removing existing entities or relationships,
328
328
  expanding the graph from particular entities, finding relationships between specified entities on the link chart and adding them to the link chart, finding all relationships
@@ -360,7 +360,7 @@ _example: "Discover and add all the relationships originating at 'Entity E' to t
360
360
  _example: "Show me all entities with a name similar to 'Smith' and add them to the link chart"_
361
361
  _example: "Find reports in my graph that have a title similar to 'Quarterly Earnings'"_
362
362
  _example: "Find John Smith and all people he has made phone calls to in the last year"_
363
- _example: "What is the average age of all people who work for Esri?"_`;var Er=Vo;var ze=ee;var ba=()=>ua(),Xi=async(t,e)=>await _e(t,e),el=async({modelTier:t="default",temperature:e=0,config:r}={})=>await zi({modelTier:t,temperature:e,config:r});var Yo=t=>{for(let e=t.length-1;e>=0;e-=1){let r=t[e];if(r.type!=="human")continue;let n=r.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.map(o=>typeof o=="string"?o:"text"in o&&typeof o.text=="string"?o.text:"").join(" ").trim()}return""},Fb=()=>({latestItemId:null,memory:{}}),nl=t=>{let e=t?.agentExecutionContext.sharedState.portalItemAnalyticsSummaryMemory?.value;return e?{latestItemId:e.latestItemId,memory:e.memory}:Fb()},qb=d.object({intent:d.enum(["summarize","followUp","clarify"]),itemId:d.string().default(""),question:d.string().default("")}),Ub=d.object({summary:d.string(),followUpQuestions:d.array(d.string()).default([])}),Bb=d.object({answer:d.string(),isRelevant:d.boolean()}),Kb=async(t,e)=>{await ze({text:"Answering follow-up...",agentName:"analytics"},e);let r=nl(t),n=t.analyticsItemId??r.latestItemId,o=n?r.memory[n]:void 0,s=t.analyticsQuestion||Yo(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await Er({promptText:Wb,schema:Bb,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.fullContext)}})).answer}:{status:"success",outputMessage:"I don't have enough information yet. Please ask me to summarize the item first using summarize item <item id>."}},Wb=`
363
+ _example: "What is the average age of all people who work for Esri?"_`;var Er=Vo;var ze=ee;var ba=()=>ua(),Xi=async(t,e)=>await _e(t,e),el=async({modelTier:t="default",temperature:e=0,config:r}={})=>await zi({modelTier:t,temperature:e,config:r});var Yo=t=>{for(let e=t.length-1;e>=0;e-=1){let r=t[e];if(r.type!=="human")continue;let n=r.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.map(o=>typeof o=="string"?o:"text"in o&&typeof o.text=="string"?o.text:"").join(" ").trim()}return""},qb=()=>({latestItemId:null,memory:{}}),nl=t=>{let e=t?.agentExecutionContext.sharedState.portalItemAnalyticsSummaryMemory?.value;return e?{latestItemId:e.latestItemId,memory:e.memory}:qb()},Ub=d.object({intent:d.enum(["summarize","followUp","clarify"]),itemId:d.string().default(""),question:d.string().default("")}),Bb=d.object({summary:d.string(),followUpQuestions:d.array(d.string()).default([])}),Kb=d.object({answer:d.string(),isRelevant:d.boolean()}),Wb=async(t,e)=>{await ze({text:"Answering follow-up...",agentName:"analytics"},e);let r=nl(t),n=t.analyticsItemId??r.latestItemId,o=n?r.memory[n]:void 0,s=t.analyticsQuestion||Yo(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await Er({promptText:Vb,schema:Kb,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.fullContext)}})).answer}:{status:"success",outputMessage:"I don't have enough information yet. Please ask me to summarize the item first using summarize item <item id>."}},Vb=`
364
364
  You answer follow-up questions about an ArcGIS item.
365
365
 
366
366
  Ground your answer in the provided item context.
@@ -380,7 +380,7 @@ Item full context
380
380
 
381
381
  Question:
382
382
  {question}
383
- `;function no(t){let{portal:e,user:r}=t??{};if(!t||!e||!r)throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var Ep=D(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;no(n);let{result:o,error:s}=await zl(n.portal,r,{num:1});return s&&console.error("Error searching for portal item by title:",s),o?.results[0]?.id||null},{name:"resolvePortalItemIdByTitle",description:'Resolves an ArcGIS Portal item title to the best-match item id. Use this when a user references an item by title (including hash mentions like #title or #"title with spaces") instead of an explicit item id.',schema:d.object({itemTitle:d.string().describe("The portal item title to resolve to an item id.")})}),Vb=async(t,e)=>{await ze({text:"Analyzing intent...",agentName:"analytics"},e);let r=Yo(t.agentExecutionContext.messages),n=!!nl(t).latestItemId,o=await mo.fromTemplate(Gb).format({userMessage:r,hasSummaryContext:String(n)}),s=await wo({model:await el({modelTier:"fast"}),tools:[Ep],systemPrompt:o,responseFormat:qb,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),{intent:a,itemId:i,question:u}=s.structuredResponse,l=a==="clarify"||a==="summarize"&&!i||a==="followUp"&&!u;return{agentExecutionContext:{...t.agentExecutionContext},analyticsIntent:l?"clarify":a,analyticsItemId:i||null,analyticsQuestion:u||"",status:"success",outputMessage:l?'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".':""}},Gb=`
383
+ `;function no(t){let{portal:e,user:r}=t??{};if(!t||!e||!r)throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var Ep=D(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;no(n);let{result:o,error:s}=await zl(n.portal,r,{num:1});return s&&console.error("Error searching for portal item by title:",s),o?.results[0]?.id||null},{name:"resolvePortalItemIdByTitle",description:'Resolves an ArcGIS Portal item title to the best-match item id. Use this when a user references an item by title (including hash mentions like #title or #"title with spaces") instead of an explicit item id.',schema:d.object({itemTitle:d.string().describe("The portal item title to resolve to an item id.")})}),Gb=async(t,e)=>{await ze({text:"Analyzing intent...",agentName:"analytics"},e);let r=Yo(t.agentExecutionContext.messages),n=!!nl(t).latestItemId,o=await mo.fromTemplate(Hb).format({userMessage:r,hasSummaryContext:String(n)}),s=await wo({model:await el({modelTier:"fast"}),tools:[Ep],systemPrompt:o,responseFormat:Ub,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),{intent:a,itemId:i,question:u}=s.structuredResponse,l=a==="clarify"||a==="summarize"&&!i||a==="followUp"&&!u;return{agentExecutionContext:{...t.agentExecutionContext},analyticsIntent:l?"clarify":a,analyticsItemId:i||null,analyticsQuestion:u||"",status:"success",outputMessage:l?'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".':""}},Hb=`
384
384
  Classify the user analytics request.
385
385
 
386
386
  Rules:
@@ -410,7 +410,7 @@ hasSummaryContext:
410
410
 
411
411
  User message:
412
412
  {userMessage}
413
- `,Hb=async(t,e)=>{let r=t.analyticsItemId;if(!r)return{status:"success",outputMessage:'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".'};await ze({text:`Summarizing item ${r}...`,agentName:"analytics"},e);let n=e?.configurable?.context;no(n);let{portal:o,user:s}=n,{result:a,error:i}=await Dl(s,o,r);if(i||!a)return await ze({text:"Failed to get item context for summarization",agentName:"analytics"},e),{status:"success",outputMessage:"Unable to retrieve item context for summarization."};let{context:u}=a,l=await Er({promptText:Jb,schema:Ub,modelTier:"default",inputVariables:{context:JSON.stringify(u)}}),{followUpQuestions:c,summary:p}=l,m=nl(t),g={latestItemId:r,memory:{...m.memory,[r]:{summary:p,followUpQuestions:c,fullContext:u}}};return c.length&&await Xi({type:"suggested-prompts",data:{prompts:c}},e),{status:"success",outputMessage:p,sharedStatePatch:{portalItemAnalyticsSummaryMemory:{value:g}}}},Jb=`
413
+ `,Jb=async(t,e)=>{let r=t.analyticsItemId;if(!r)return{status:"success",outputMessage:'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".'};await ze({text:`Summarizing item ${r}...`,agentName:"analytics"},e);let n=e?.configurable?.context;no(n);let{portal:o,user:s}=n,{result:a,error:i}=await Dl(s,o,r);if(i||!a)return await ze({text:"Failed to get item context for summarization",agentName:"analytics"},e),{status:"success",outputMessage:"Unable to retrieve item context for summarization."};let{context:u}=a,l=await Er({promptText:Zb,schema:Bb,modelTier:"default",inputVariables:{context:JSON.stringify(u)}}),{followUpQuestions:c,summary:p}=l,m=nl(t),g={latestItemId:r,memory:{...m.memory,[r]:{summary:p,followUpQuestions:c,fullContext:u}}};return c.length&&await Xi({type:"suggested-prompts",data:{prompts:c}},e),{status:"success",outputMessage:p,sharedStatePatch:{portalItemAnalyticsSummaryMemory:{value:g}}}},Zb=`
414
414
  You are a item summary tool for ArcGIS. Your job is to summarize an item's info based on the provided context.
415
415
  Summary rules:
416
416
  - The summary should be concise markdown, make sure to format the output nicely so it's easy to read.
@@ -425,15 +425,15 @@ Do not include internal identifiers.
425
425
  If the user asks for a detailed summary, you may expand the response up to 300 words.
426
426
  Item context:
427
427
  {context}
428
- `,tl=(t,e)=>e??t,Op=N.Root({...ba(),analyticsIntent:N({reducer:tl,default:()=>"clarify"}),analyticsItemId:N({reducer:tl,default:()=>null}),analyticsQuestion:N({reducer:tl,default:()=>""})}),Zb=()=>new ye(Op).addNode("detectAnalyticsIntent",Vb).addNode("summarizePortalItem",Hb).addNode("answerAnalyticsFollowUp",Kb).addEdge(he,"detectAnalyticsIntent").addConditionalEdges("detectAnalyticsIntent",t=>t.analyticsIntent==="summarize"?"summarizePortalItem":t.analyticsIntent==="followUp"?"answerAnalyticsFollowUp":B).addEdge("summarizePortalItem",B).addEdge("answerAnalyticsFollowUp",B),Qb=String.raw`- **portal-item-analytics** - Portal item analytics assistant:
428
+ `,tl=(t,e)=>e??t,Op=N.Root({...ba(),analyticsIntent:N({reducer:tl,default:()=>"clarify"}),analyticsItemId:N({reducer:tl,default:()=>null}),analyticsQuestion:N({reducer:tl,default:()=>""})}),Qb=()=>new ye(Op).addNode("detectAnalyticsIntent",Gb).addNode("summarizePortalItem",Jb).addNode("answerAnalyticsFollowUp",Wb).addEdge(he,"detectAnalyticsIntent").addConditionalEdges("detectAnalyticsIntent",t=>t.analyticsIntent==="summarize"?"summarizePortalItem":t.analyticsIntent==="followUp"?"answerAnalyticsFollowUp":B).addEdge("summarizePortalItem",B).addEdge("answerAnalyticsFollowUp",B),Yb=String.raw`- **portal-item-analytics** - Portal item analytics assistant:
429
429
  - summarizes ArcGIS portal items from item context
430
430
  - suggests follow-up prompts grounded in the item
431
- `,Yb={id:"portal-item-analytics",name:"Portal Item Analytics",description:Qb,createGraph:Zb,workspace:Op},Xb=t=>t.map(e=>`"${e}"`).join(", "),ex=d.object({successMessage:d.string().default("")}),Ip="portal-group-creation",vp="approveAddMembers",tx=async(t,e)=>{if(t.intentParams.intent!=="addMembers")return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let r=t.agentExecutionContext.sharedState.createdGroupId?.value;if(!r)return{status:"success",outputMessage:"Create a group first, then add members using @mention usernames."};let n=t.intentParams.memberInfo.memberIdentifiers.map(p=>p.trim()).filter(Boolean);if(!n.length)return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let o=`The following member(s) will be added to the newly created group:
431
+ `,Xb={id:"portal-item-analytics",name:"Portal Item Analytics",description:Yb,createGraph:Qb,workspace:Op},ex=t=>t.map(e=>`"${e}"`).join(", "),tx=d.object({successMessage:d.string().default("")}),Ip="portal-group-creation",vp="approveAddMembers",rx=async(t,e)=>{if(t.intentParams.intent!=="addMembers")return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let r=t.agentExecutionContext.sharedState.createdGroupId?.value;if(!r)return{status:"success",outputMessage:"Create a group first, then add members using @mention usernames."};let n=t.intentParams.memberInfo.memberIdentifiers.map(p=>p.trim()).filter(Boolean);if(!n.length)return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let o=`The following member(s) will be added to the newly created group:
432
432
 
433
433
  ${n.map(p=>`- **@${p}**`).join(`
434
434
  `)}
435
435
 
436
- Do you want to continue?`,{hitlResponse:s}=e?.configurable??{};if(s?.agentId!==Ip||s.id!==vp){let p={agentId:Ip,id:vp,kind:"booleanChoice",message:o,metadata:{action:"addMembers",groupId:r,members:[...n]}};throw new es(p)}if(s.payload!==!0)return{status:"success",outputMessage:"Okay, I cancelled adding members to the group."};await ze({text:`Adding members ${Xb(n)}...`,agentName:"group-creation"},e);let a=e?.configurable?.context;no(a);let{result:i,error:u}=await Ul(a.portal,r,n);if(u||!i)return{status:"success",outputMessage:"I could not add members to that group. Please confirm group access and user accounts, then try again."};let{addedUsernames:l,notAddedUsers:c}=i;try{let p=(await Er({promptText:rx,schema:ex,modelTier:"fast",inputVariables:{addedMembers:l.join(", "),notAddedMembers:JSON.stringify(c.map(m=>({username:m.username,reason:m.error.message})))}})).successMessage;if(p)return{status:"success",outputMessage:p}}catch(p){console.error("Error generating add-members success message:",p)}return{}},rx=`
436
+ Do you want to continue?`,{hitlResponse:s}=e?.configurable??{};if(s?.agentId!==Ip||s.id!==vp){let p={agentId:Ip,id:vp,kind:"booleanChoice",message:o,metadata:{action:"addMembers",groupId:r,members:[...n]}};throw new es(p)}if(s.payload!==!0)return{status:"success",outputMessage:"Okay, I cancelled adding members to the group."};await ze({text:`Adding members ${ex(n)}...`,agentName:"group-creation"},e);let a=e?.configurable?.context;no(a);let{result:i,error:u}=await Ul(a.portal,r,n);if(u||!i)return{status:"success",outputMessage:"I could not add members to that group. Please confirm group access and user accounts, then try again."};let{addedUsernames:l,notAddedUsers:c}=i;try{let p=(await Er({promptText:nx,schema:tx,modelTier:"fast",inputVariables:{addedMembers:l.join(", "),notAddedMembers:JSON.stringify(c.map(m=>({username:m.username,reason:m.error.message})))}})).successMessage;if(p)return{status:"success",outputMessage:p}}catch(p){console.error("Error generating add-members success message:",p)}return{}},nx=`
437
437
  Write a concise, friendly success message for adding members to a group.
438
438
 
439
439
  Rules:
@@ -448,7 +448,7 @@ Added members:
448
448
 
449
449
  Not added members:
450
450
  {notAddedMembers}
451
- `,Tp="portal-group-creation",Sp="approveCreateGroup",nx=d.object({successMessage:d.string().default("")}),ox=d.object({failureMessage:d.string().default("")}),sx=async(t,e)=>{if(t.intentParams.intent!=="create")return{status:"success",outputMessage:"Tell me the group title you want to use."};let r=t.intentParams.title.trim();if(!r)return{status:"success",outputMessage:"What title would you like for the new group?"};let n=`A group with the title **${r}** will be created. Do you want to continue?`,{hitlResponse:o}=e?.configurable;if(o?.agentId!==Tp||o.id!==Sp){let l={agentId:Tp,id:Sp,kind:"booleanChoice",message:n,metadata:{action:"createGroup",title:r,access:"private"}};throw new es(l)}if(o.payload!==!0)return{status:"success",outputMessage:`Okay, I cancelled creating **${r}**.`};await ze({text:`Creating group "${r}"...`,agentName:"group-creation"},e);let s=e?.configurable?.context;no(s);let{result:a,error:i}=await ql(s.portal,{title:r,access:"private"});if(i||!a){let l=i?.message?.trim()||"No additional details were provided.";try{let c=(await Er({promptText:ix,schema:ox,modelTier:"fast",inputVariables:{groupTitle:r,failureReason:l}})).failureMessage.trim();if(c)return{status:"success",outputMessage:c}}catch(c){console.error("Error generating create-group failure message:",c)}return{status:"success",outputMessage:"I could not create that group. Please confirm your permissions and try again with the group title."}}let u=a.id;try{let l=(await Er({promptText:ax,schema:nx,modelTier:"fast",inputVariables:{groupTitle:r}})).successMessage.trim();if(l)return{status:"success",outputMessage:l,sharedStatePatch:{createdGroupId:{value:u}},createdGroupId:u}}catch(l){console.error("Error generating create-group success message:",l)}return{}},ax=`
451
+ `,Tp="portal-group-creation",Sp="approveCreateGroup",ox=d.object({successMessage:d.string().default("")}),sx=d.object({failureMessage:d.string().default("")}),ax=async(t,e)=>{if(t.intentParams.intent!=="create")return{status:"success",outputMessage:"Tell me the group title you want to use."};let r=t.intentParams.title.trim();if(!r)return{status:"success",outputMessage:"What title would you like for the new group?"};let n=`A group with the title **${r}** will be created. Do you want to continue?`,{hitlResponse:o}=e?.configurable;if(o?.agentId!==Tp||o.id!==Sp){let l={agentId:Tp,id:Sp,kind:"booleanChoice",message:n,metadata:{action:"createGroup",title:r,access:"private"}};throw new es(l)}if(o.payload!==!0)return{status:"success",outputMessage:`Okay, I cancelled creating **${r}**.`};await ze({text:`Creating group "${r}"...`,agentName:"group-creation"},e);let s=e?.configurable?.context;no(s);let{result:a,error:i}=await ql(s.portal,{title:r,access:"private"});if(i||!a){let l=i?.message?.trim()||"No additional details were provided.";try{let c=(await Er({promptText:lx,schema:sx,modelTier:"fast",inputVariables:{groupTitle:r,failureReason:l}})).failureMessage.trim();if(c)return{status:"success",outputMessage:c}}catch(c){console.error("Error generating create-group failure message:",c)}return{status:"success",outputMessage:"I could not create that group. Please confirm your permissions and try again with the group title."}}let u=a.id;try{let l=(await Er({promptText:ix,schema:ox,modelTier:"fast",inputVariables:{groupTitle:r}})).successMessage.trim();if(l)return{status:"success",outputMessage:l,sharedStatePatch:{createdGroupId:{value:u}},createdGroupId:u}}catch(l){console.error("Error generating create-group success message:",l)}return{}},ix=`
452
452
  Write a concise, friendly success message after creating a portal group.
453
453
 
454
454
  Rules:
@@ -459,7 +459,7 @@ Rules:
459
459
 
460
460
  Group title:
461
461
  {groupTitle}
462
- `,ix=`
462
+ `,lx=`
463
463
  Write a concise, friendly failure message after an attempt to create a portal group.
464
464
 
465
465
  Rules:
@@ -474,7 +474,7 @@ Group title:
474
474
 
475
475
  Failure reason:
476
476
  {failureReason}
477
- `,lx=d.object({intent:d.enum(["clarify","create","addMembers"]).default("clarify"),title:d.string().default(""),memberIdentifiers:d.array(d.string()).default([]),clarifyMessage:d.string().default("")}),ux=async(t,e)=>{await ze({text:"Thinking about groups...",agentName:"group-creation"},e);let r=Yo(t.agentExecutionContext.messages).trim(),n=await Er({promptText:cx,schema:lx,modelTier:"default",inputVariables:{userMessage:r}}),o=n.title.trim(),s=n.memberIdentifiers.filter(Boolean),a=n.clarifyMessage.trim(),i=n.intent==="create"&&!!o,u=n.intent==="addMembers"&&s.length>0;return{intentParams:i?{intent:"create",title:o}:u?{intent:"addMembers",memberInfo:{memberIdentifiers:s}}:{intent:"clarify"},status:"success",outputMessage:!i&&!u?a:""}},cx=`
477
+ `,ux=d.object({intent:d.enum(["clarify","create","addMembers"]).default("clarify"),title:d.string().default(""),memberIdentifiers:d.array(d.string()).default([]),clarifyMessage:d.string().default("")}),cx=async(t,e)=>{await ze({text:"Thinking about groups...",agentName:"group-creation"},e);let r=Yo(t.agentExecutionContext.messages).trim(),n=await Er({promptText:dx,schema:ux,modelTier:"default",inputVariables:{userMessage:r}}),o=n.title.trim(),s=n.memberIdentifiers.filter(Boolean),a=n.clarifyMessage.trim(),i=n.intent==="create"&&!!o,u=n.intent==="addMembers"&&s.length>0;return{intentParams:i?{intent:"create",title:o}:u?{intent:"addMembers",memberInfo:{memberIdentifiers:s}}:{intent:"clarify"},status:"success",outputMessage:!i&&!u?a:""}},dx=`
478
478
  You classify whether a user is asking to create a new ArcGIS Portal group or add members to an existing group.
479
479
 
480
480
  Rules:
@@ -500,10 +500,10 @@ Examples:
500
500
 
501
501
  User message:
502
502
  {userMessage}
503
- `,dx=d.discriminatedUnion("destinationType",[d.object({destinationType:d.literal("portal-content")}),d.object({destinationType:d.literal("portal-groups")}),d.object({destinationType:d.literal("portal-item"),itemId:d.string().trim().min(1)}),d.object({destinationType:d.literal("portal-group"),groupId:d.string().trim().min(1)})]);function px(t){let e=dx.safeParse(t);return e.success?e.data:void 0}var Mp="portal-navigation",Pp=async(t,e)=>{await Xi({type:Mp,data:{...t}},e)},mx=async(t,e)=>{let r=t.createdGroupId??t.agentExecutionContext.sharedState.createdGroupId?.value;return r?(await ze({text:"Preparing navigation...",agentName:"group-creation"},e),await Pp({destinationType:"portal-group",groupId:r},e),{}):{}},kp=(t,e)=>e??t,Rp=N.Root({...ba(),intentParams:N({reducer:kp,default:()=>({intent:"clarify"})}),createdGroupId:N({reducer:kp,default:()=>""})}),fx=()=>new ye(Rp).addNode("detectGroupCreationIntent",ux).addNode("createPortalGroup",sx).addNode("addMembersToPortalGroup",tx).addNode("suggestCreatedGroupNavigation",mx).addEdge(he,"detectGroupCreationIntent").addConditionalEdges("detectGroupCreationIntent",t=>{switch(t.intentParams.intent){case"create":return"createPortalGroup";case"addMembers":return"addMembersToPortalGroup";default:return B}}).addEdge("createPortalGroup","suggestCreatedGroupNavigation").addEdge("addMembersToPortalGroup","suggestCreatedGroupNavigation").addEdge("suggestCreatedGroupNavigation",B),hx=String.raw`- **portal-group-creation** - Portal group creation assistant:
503
+ `,px=d.discriminatedUnion("destinationType",[d.object({destinationType:d.literal("portal-content")}),d.object({destinationType:d.literal("portal-groups")}),d.object({destinationType:d.literal("portal-item"),itemId:d.string().trim().min(1)}),d.object({destinationType:d.literal("portal-group"),groupId:d.string().trim().min(1)})]);function mx(t){let e=px.safeParse(t);return e.success?e.data:void 0}var Mp="portal-navigation",Pp=async(t,e)=>{await Xi({type:Mp,data:{...t}},e)},fx=async(t,e)=>{let r=t.createdGroupId??t.agentExecutionContext.sharedState.createdGroupId?.value;return r?(await ze({text:"Preparing navigation...",agentName:"group-creation"},e),await Pp({destinationType:"portal-group",groupId:r},e),{}):{}},kp=(t,e)=>e??t,Rp=N.Root({...ba(),intentParams:N({reducer:kp,default:()=>({intent:"clarify"})}),createdGroupId:N({reducer:kp,default:()=>""})}),hx=()=>new ye(Rp).addNode("detectGroupCreationIntent",cx).addNode("createPortalGroup",ax).addNode("addMembersToPortalGroup",rx).addNode("suggestCreatedGroupNavigation",fx).addEdge(he,"detectGroupCreationIntent").addConditionalEdges("detectGroupCreationIntent",t=>{switch(t.intentParams.intent){case"create":return"createPortalGroup";case"addMembers":return"addMembersToPortalGroup";default:return B}}).addEdge("createPortalGroup","suggestCreatedGroupNavigation").addEdge("addMembersToPortalGroup","suggestCreatedGroupNavigation").addEdge("suggestCreatedGroupNavigation",B),gx=String.raw`- **portal-group-creation** - Portal group creation assistant:
504
504
  - creates a new ArcGIS Portal group for the signed-in user
505
505
  - adds users to the newly created group using @mention usernames
506
- `,gx={id:"portal-group-creation",name:"Portal Group Creation",description:hx,createGraph:fx,workspace:Rp},Np="portalDocAssistantMemory",yx=()=>({conversationId:""}),_x=t=>{let e=t?.[Np]?.value;if(!e||typeof e!="object")return yx();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},wx=t=>({[Np]:{value:t}});async function bx({portal:t,question:e,persona:r,previousConversationId:n,signal:o,skillId:s}){s??="doc_ai_assistant";let a=await xx({portal:t,skillId:s,message:e,options:{context:{kind:"DocAIAssistantRequest",filters:{persona:{persona:r}}},previousConversationId:n,signal:o}});return{reply:Ax(a,s),conversationId:a[0]?.conversationId??""}}async function xx({portal:t,skillId:e,message:r,options:n}){let o=`${t.helperServices.aiAssistantServices.url}/skills/${e}/chat`,s={"Content-Type":"application/json",token:Db.findCredential(t.url)?.token??""},a=await Ap(o,{method:"post",body:JSON.stringify({message:r,context:n.context,conversationId:n.previousConversationId}),headers:s,signal:n.signal});if(a.httpStatus!==200)throw new Error(`Doc assistant chat failed (${a.httpStatus})`,{cause:a.data});let i=a.data,u=[i],{conversationId:l,inquiryId:c}=i,p=async(m,g)=>{if(!g)return;await pl(1e3);let y=await Ap(o,{method:"post",body:JSON.stringify({conversationId:l,inquiryId:c,ackSequenceNumber:m}),headers:s,signal:n.signal});if(y.httpStatus!==200)throw new Error(`Doc assistant poll failed (${y.httpStatus})`,{cause:y.data});let A=y.data;u.push(A),await p(A.sequenceNumber,A.hasMore)};return i.hasMore&&await p(i.sequenceNumber,i.hasMore),u}function Ax(t,e){switch(e){case"doc_chat":return t.find(r=>r.message!=null)?.message??"";case"doc_ai_assistant":for(let r=t.length-1;r>=0;r-=1){let n=t[r];if(n.context?.kind==="DocAIAssistantContext"){let o=n.context.results?.[0]?.reply;if(o)return o}}return"";default:return ao(e)}}var Ix=async(t,e)=>{await ze({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let r=Yo(t.agentExecutionContext.messages).trim();if(!r)return{status:"success",outputMessage:"Please share your question and I can help with ArcGIS and Portal documentation."};let n=e?.configurable?.context;no(n);let o=_x(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await bx({portal:n.portal,question:r,previousConversationId:o.conversationId||void 0,skillId:"doc_ai_assistant",persona:"developers"});return{status:"success",outputMessage:s.trim()||"I could not retrieve a response from the documentation assistant.",sharedStatePatch:wx({conversationId:a||o.conversationId})}},vx=D(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;no(n);try{return(await Fl(n.portal,{query:`title:${r}`,num:1}))?.results[0]?.id||null}catch(o){return console.error("Error searching for portal group by title:",o),null}},{name:"resolvePortalGroupIdByTitle",description:"Resolves an ArcGIS Portal group title to the best-match group id. Use this when a user references a group by title instead of an explicit group id.",schema:d.object({groupTitle:d.string().describe("The portal group title to resolve to a group id.")})}),Cp=d.object({shouldSuggestNavigation:d.boolean().default(!1),destinationType:d.enum(["none","portal-content","portal-item","portal-groups","portal-group"]).default("none"),itemId:d.string().default(""),groupId:d.string().default("")}),Tx=async(t,e)=>{await ze({text:"Extracting navigation intent...",agentName:"doc-assistant"},e);let r=t.outputMessage.trim();if(!r)return{};let n=Yo(t.agentExecutionContext.messages).trim(),o=await mo.fromTemplate(kx).format({question:n,response:r}),s=await wo({model:await el({modelTier:"default"}),tools:[Ep,vx],systemPrompt:o,responseFormat:Cp,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),a=Cp.parse(s.structuredResponse??{});if(!a.shouldSuggestNavigation||a.destinationType==="none")return{};let i=Sx(a);return i?(await Pp(i,e),{}):{}};function Sx({destinationType:t,itemId:e,groupId:r}){switch(t){case"portal-content":return{destinationType:"portal-content"};case"portal-groups":return{destinationType:"portal-groups"};case"portal-item":return e?{destinationType:"portal-item",itemId:e}:null;case"portal-group":return r?{destinationType:"portal-group",groupId:r}:null;case"none":return null;default:return ao(t)}}var kx=`
506
+ `,yx={id:"portal-group-creation",name:"Portal Group Creation",description:gx,createGraph:hx,workspace:Rp},Np="portalDocAssistantMemory",_x=()=>({conversationId:""}),wx=t=>{let e=t?.[Np]?.value;if(!e||typeof e!="object")return _x();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},bx=t=>({[Np]:{value:t}});async function xx({portal:t,question:e,persona:r,previousConversationId:n,signal:o,skillId:s}){s??="doc_ai_assistant";let a=await Ax({portal:t,skillId:s,message:e,options:{context:{kind:"DocAIAssistantRequest",filters:{persona:{persona:r}}},previousConversationId:n,signal:o}});return{reply:Ix(a,s),conversationId:a[0]?.conversationId??""}}async function Ax({portal:t,skillId:e,message:r,options:n}){let o=`${t.helperServices.aiAssistantServices.url}/skills/${e}/chat`,s={"Content-Type":"application/json",token:Fb.findCredential(t.url)?.token??""},a=await Ap(o,{method:"post",body:JSON.stringify({message:r,context:n.context,conversationId:n.previousConversationId}),headers:s,signal:n.signal});if(a.httpStatus!==200)throw new Error(`Doc assistant chat failed (${a.httpStatus})`,{cause:a.data});let i=a.data,u=[i],{conversationId:l,inquiryId:c}=i,p=async(m,g)=>{if(!g)return;await pl(1e3);let y=await Ap(o,{method:"post",body:JSON.stringify({conversationId:l,inquiryId:c,ackSequenceNumber:m}),headers:s,signal:n.signal});if(y.httpStatus!==200)throw new Error(`Doc assistant poll failed (${y.httpStatus})`,{cause:y.data});let A=y.data;u.push(A),await p(A.sequenceNumber,A.hasMore)};return i.hasMore&&await p(i.sequenceNumber,i.hasMore),u}function Ix(t,e){switch(e){case"doc_chat":return t.find(r=>r.message!=null)?.message??"";case"doc_ai_assistant":for(let r=t.length-1;r>=0;r-=1){let n=t[r];if(n.context?.kind==="DocAIAssistantContext"){let o=n.context.results?.[0]?.reply;if(o)return o}}return"";default:return ao(e)}}var vx=async(t,e)=>{await ze({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let r=Yo(t.agentExecutionContext.messages).trim();if(!r)return{status:"success",outputMessage:"Please share your question and I can help with ArcGIS and Portal documentation."};let n=e?.configurable?.context;no(n);let o=wx(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await xx({portal:n.portal,question:r,previousConversationId:o.conversationId||void 0,skillId:"doc_ai_assistant",persona:"developers"});return{status:"success",outputMessage:s.trim()||"I could not retrieve a response from the documentation assistant.",sharedStatePatch:bx({conversationId:a||o.conversationId})}},Tx=D(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;no(n);try{return(await Fl(n.portal,{query:`title:${r}`,num:1}))?.results[0]?.id||null}catch(o){return console.error("Error searching for portal group by title:",o),null}},{name:"resolvePortalGroupIdByTitle",description:"Resolves an ArcGIS Portal group title to the best-match group id. Use this when a user references a group by title instead of an explicit group id.",schema:d.object({groupTitle:d.string().describe("The portal group title to resolve to a group id.")})}),Cp=d.object({shouldSuggestNavigation:d.boolean().default(!1),destinationType:d.enum(["none","portal-content","portal-item","portal-groups","portal-group"]).default("none"),itemId:d.string().default(""),groupId:d.string().default("")}),Sx=async(t,e)=>{await ze({text:"Extracting navigation intent...",agentName:"doc-assistant"},e);let r=t.outputMessage.trim();if(!r)return{};let n=Yo(t.agentExecutionContext.messages).trim(),o=await mo.fromTemplate(Cx).format({question:n,response:r}),s=await wo({model:await el({modelTier:"default"}),tools:[Ep,Tx],systemPrompt:o,responseFormat:Cp,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),a=Cp.parse(s.structuredResponse??{});if(!a.shouldSuggestNavigation||a.destinationType==="none")return{};let i=kx(a);return i?(await Pp(i,e),{}):{}};function kx({destinationType:t,itemId:e,groupId:r}){switch(t){case"portal-content":return{destinationType:"portal-content"};case"portal-groups":return{destinationType:"portal-groups"};case"portal-item":return e?{destinationType:"portal-item",itemId:e}:null;case"portal-group":return r?{destinationType:"portal-group",groupId:r}:null;case"none":return null;default:return ao(t)}}var Cx=`
507
507
  You decide whether the assistant response should include a navigation action to ArcGIS Portal.
508
508
 
509
509
  Given the user question and assistant response:
@@ -527,7 +527,7 @@ User question:
527
527
 
528
528
  Assistant response:
529
529
  {response}
530
- `,$p=N.Root({...ba()}),Cx=()=>new ye($p).addNode("answerDocQuestion",Ix).addNode("extractNavigationIntent",Tx).addEdge(he,"answerDocQuestion").addEdge("answerDocQuestion","extractNavigationIntent").addEdge("extractNavigationIntent",B),Ex=String.raw`- **portal-doc-assistant** - General ArcGIS documentation and Portal help assistant:
530
+ `,$p=N.Root({...ba()}),Ex=()=>new ye($p).addNode("answerDocQuestion",vx).addNode("extractNavigationIntent",Sx).addEdge(he,"answerDocQuestion").addEdge("answerDocQuestion","extractNavigationIntent").addEdge("extractNavigationIntent",B),Ox=String.raw`- **portal-doc-assistant** - General ArcGIS documentation and Portal help assistant:
531
531
  - answers general ArcGIS, Portal, Enterprise, and JavaScript SDK questions
532
532
  - acts as a fallback when specialized agents are not applicable
533
- `,Ox={id:"portal-doc-assistant",name:"Portal Doc Assistant",description:Ex,createGraph:Cx,workspace:$p},Mx=sl`:host{height:100%;border-width:1px;border-style:solid;border-color:var(--calcite-color-border-3);display:block;width:100%;--tw-shadow: 0 1px 6px -1px rgba(0, 0, 0, .16), 0 1px 2px -1px rgba(0, 0, 0, .08);--tw-shadow-colored: 0 1px 6px -1px var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.chat-entry{display:flex;flex-direction:column;gap:.75rem;width:100%}.chat-actions{display:flex;justify-content:flex-end;gap:.5rem}.header-actions{display:flex;gap:.5rem;padding-inline-start:.75rem}.navigation-block{display:flex;flex-direction:column;align-items:stretch;gap:.35rem;margin-top:.5rem}.navigation-button{width:100%;margin-block:.25rem}.navigation-block-description{font-size:.75rem;color:var(--calcite-color-text-3)}`,Px=(t,e)=>{let{destinationType:r}=t,n=`${e.url}/home`;switch(r){case"portal-content":return`${n}/content.html`;case"portal-groups":return`${n}/groups.html`;case"portal-item":return`${n}/item.html?id=${t.itemId}`;case"portal-group":return`${n}/group.html?id=${t.groupId}`;default:return ao(r)}},rl=class extends ul{constructor(){super(...arguments),this.t9n=dl({blocking:!0}),this.assistantEl=oo(),this.formEl=oo(),this.voiceInputEl=oo(),this.inputEl=oo(),this.navigationSlotElements=new Map,this.handleSlottableRequest=e=>{let r=e.detail,n=r.data?.block;if(!n)return;let o=this.getNavigationAction(n);o&&this.upsertNavigationSlotElement(r.slotName,o)},this.inputText="",this.showVoiceInput=!0,this.isListening=!1,this.isVoiceInputDisabled=!1,this.interrupt=null,this.autoDestroyDisabled=!1,this.defaultClosed=!1,this.arcgisPortalNavigationRequest=il()}static{this.properties={inputText:16,showVoiceInput:16,isListening:16,isVoiceInputDisabled:16,interrupt:16,autoDestroyDisabled:5,portal:0,user:0,config:0,defaultClosed:5}}static{this.styles=Mx}getNavigationAction(e){if(e?.type!==Mp)return;let r=px(e.data);if(!r)return;let n=Px(r,this.portal);if(n)return{href:n,targetDetail:r,label:this.getNavigationText(r.destinationType)}}upsertNavigationSlotElement(e,r){let n=this.assistantEl.value;if(!n)return;let o=this.navigationSlotElements.get(e);o||(o=document.createElement("div"),o.slot=e,this.navigationSlotElements.set(e,o),n.append(o)),al(Or`<div><calcite-button class="navigation-button" appearance=outline width=full .href=${r.href} icon-end=launch @click=${s=>{s.preventDefault(),this.arcgisPortalNavigationRequest.emit({href:r.href,targetDetail:r.targetDetail})}}>${r.label}</calcite-button>${r.description?Or`<div class="navigation-block-description">${r.description}</div>`:null}</div>`,o)}getNavigationText(e){let r=this.t9n.navigation;switch(e){case"portal-content":return r.openContent;case"portal-groups":return r.openGroups;case"portal-item":return r.openItem;case"portal-group":return r.openGroup;default:return ao(e)}}render(){let{t9n:e,inputText:r,portal:n,user:o,showVoiceInput:s,isListening:a,isVoiceInputDisabled:i}=this;return Or`<arcgis-assistant log-enabled keep-suggested-prompts .heading=${e.heading} .entryMessage=${e.entryMessage} @arcgisSlottableRequest=${this.handleSlottableRequest} @arcgisInterrupt=${({detail:u})=>{this.interrupt=u}} @arcgisInterruptCancel=${()=>{this.interrupt=null}} @arcgisInterruptSubmit=${()=>{this.interrupt=null}} @arcgisPromptSelect=${({detail:u})=>{this.inputText=u.prompt,requestAnimationFrame(()=>{this.inputEl.value?.focusTextArea()})}} ${so(this.assistantEl)}><div slot=header-actions-start class="header-actions"><calcite-icon icon=effects></calcite-icon></div><form slot=chat-entry class="chat-entry" @submit=${u=>{u.preventDefault();let l=r.trim();l&&(this.assistantEl.value?.submitMessage(l),this.inputText="")}} ${so(this.formEl)}><arcgis-portal-mentionable-text-area .portal=${n} .user=${o} rows=3 .popoverListLabel=${e.mentionEntities} .placeholder=${e.placeholder} .value=${r} @arcgisUserMentionableTextAreaKeyDown=${({detail:u})=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),this.formEl.value?.requestSubmit())}} @arcgisUserMentionableTextAreaChange=${({detail:u})=>{this.inputText=u??""}} ${so(this.inputEl)}></arcgis-portal-mentionable-text-area><div class="chat-actions"><arcgis-portal-voice-input @arcgisVoiceInputStart=${()=>{this.isListening=!0,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputStop=${()=>{this.isListening=!1,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputError=${u=>{u.detail.errorCode==="not-supported"&&(this.showVoiceInput=!1)}} @arcgisVoiceInputInterimTranscription=${u=>{this.inputText=u.detail.text}} ${so(this.voiceInputEl)}></arcgis-portal-voice-input>${s&&Or`<calcite-button icon-start=microphone .label=${e.voiceInput} round .disabled=${i} .appearance=${a?"solid":"outline-fill"} @click=${async()=>{this.isVoiceInputDisabled=!0;let u=this.voiceInputEl.value;a?await u?.stopListening():await u?.startListening()}}></calcite-button>`||""}<calcite-button type=submit icon-start=send round .disabled=${!r.trim()} .label=${e.send}>${e.send}</calcite-button></div></form><arcgis-assistant-agent .agent=${Yb} .context=${{portal:n,user:o}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${gx} .context=${{portal:n,user:o}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${Ox} .context=${{portal:n,user:o}}></arcgis-assistant-agent>${this.interrupt&&Or`<arcgis-portal-ai-assistant-interrupt slot=interrupt .type=${this.interrupt.type} .message=${this.interrupt.message} .options=${this.interrupt.options} @arcgisSubmit=${({detail:u})=>{this.assistantEl.value?.submitInterrupt(u)}} @arcgisCancel=${()=>{this.assistantEl.value?.cancelInterrupt()}}></arcgis-portal-ai-assistant-interrupt>`||""}</arcgis-assistant>`}};cl("arcgis-portal-ai-assistant",rl);return rl},"identity/IdentityManager","portal/Portal","portal/Portal","identity/IdentityManager","config","core/reactiveUtils","layers/FeatureLayer","request","layers/FeatureLayer","core/reactiveUtils","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","Graphic","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming","applications/KnowledgeStudio/generalSharedKgUtils","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","request",a)
533
+ `,Mx={id:"portal-doc-assistant",name:"Portal Doc Assistant",description:Ox,createGraph:Ex,workspace:$p},Px=sl`:host{height:100%;border-width:1px;border-style:solid;border-color:var(--calcite-color-border-3);display:block;width:100%;--tw-shadow: 0 1px 6px -1px rgba(0, 0, 0, .16), 0 1px 2px -1px rgba(0, 0, 0, .08);--tw-shadow-colored: 0 1px 6px -1px var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.chat-entry{display:flex;flex-direction:column;gap:.75rem;width:100%}.chat-actions{display:flex;justify-content:flex-end;gap:.5rem}.header-actions{display:flex;gap:.5rem;padding-inline-start:.75rem}.navigation-block{display:flex;flex-direction:column;align-items:stretch;gap:.35rem;margin-top:.5rem}.navigation-button{width:100%;margin-block:.25rem}.navigation-block-description{font-size:.75rem;color:var(--calcite-color-text-3)}`,Rx=(t,e)=>{let{destinationType:r}=t,n=`${e.url}/home`;switch(r){case"portal-content":return`${n}/content.html`;case"portal-groups":return`${n}/groups.html`;case"portal-item":return`${n}/item.html?id=${t.itemId}`;case"portal-group":return`${n}/group.html?id=${t.groupId}`;default:return ao(r)}},rl=class extends ul{constructor(){super(...arguments),this.t9n=dl({blocking:!0}),this.assistantEl=oo(),this.formEl=oo(),this.voiceInputEl=oo(),this.inputEl=oo(),this.navigationSlotElements=new Map,this.handleSlottableRequest=e=>{let r=e.detail,n=r.data?.block;if(!n)return;let o=this.getNavigationAction(n);o&&this.upsertNavigationSlotElement(r.slotName,o)},this.inputText="",this.showVoiceInput=!0,this.isListening=!1,this.isVoiceInputDisabled=!1,this.interrupt=null,this.autoDestroyDisabled=!1,this.defaultClosed=!1,this.arcgisPortalNavigationRequest=il()}static{this.properties={inputText:16,showVoiceInput:16,isListening:16,isVoiceInputDisabled:16,interrupt:16,autoDestroyDisabled:5,portal:0,user:0,config:0,defaultClosed:5}}static{this.styles=Px}getNavigationAction(e){if(e?.type!==Mp)return;let r=mx(e.data);if(!r)return;let n=Rx(r,this.portal);if(n)return{href:n,targetDetail:r,label:this.getNavigationText(r.destinationType)}}upsertNavigationSlotElement(e,r){let n=this.assistantEl.value;if(!n)return;let o=this.navigationSlotElements.get(e);o||(o=document.createElement("div"),o.slot=e,this.navigationSlotElements.set(e,o),n.append(o)),al(Or`<div><calcite-button class="navigation-button" appearance=outline width=full .href=${r.href} icon-end=launch @click=${s=>{s.preventDefault(),this.arcgisPortalNavigationRequest.emit({href:r.href,targetDetail:r.targetDetail})}}>${r.label}</calcite-button>${r.description?Or`<div class="navigation-block-description">${r.description}</div>`:null}</div>`,o)}getNavigationText(e){let r=this.t9n.navigation;switch(e){case"portal-content":return r.openContent;case"portal-groups":return r.openGroups;case"portal-item":return r.openItem;case"portal-group":return r.openGroup;default:return ao(e)}}render(){let{t9n:e,inputText:r,portal:n,user:o,showVoiceInput:s,isListening:a,isVoiceInputDisabled:i}=this;return Or`<arcgis-assistant log-enabled keep-suggested-prompts .heading=${e.heading} .entryMessage=${e.entryMessage} @arcgisSlottableRequest=${this.handleSlottableRequest} @arcgisInterrupt=${({detail:u})=>{this.interrupt=u}} @arcgisInterruptCancel=${()=>{this.interrupt=null}} @arcgisInterruptSubmit=${()=>{this.interrupt=null}} @arcgisPromptSelect=${({detail:u})=>{this.inputText=u.prompt,requestAnimationFrame(()=>{this.inputEl.value?.focusTextArea()})}} ${so(this.assistantEl)}><div slot=header-actions-start class="header-actions"><calcite-icon icon=effects></calcite-icon></div><form slot=chat-entry class="chat-entry" @submit=${u=>{u.preventDefault();let l=r.trim();l&&(this.assistantEl.value?.submitMessage(l),this.inputText="")}} ${so(this.formEl)}><arcgis-portal-mentionable-text-area .portal=${n} .user=${o} rows=3 .popoverListLabel=${e.mentionEntities} .placeholder=${e.placeholder} .value=${r} @arcgisUserMentionableTextAreaKeyDown=${({detail:u})=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),this.formEl.value?.requestSubmit())}} @arcgisUserMentionableTextAreaChange=${({detail:u})=>{this.inputText=u??""}} ${so(this.inputEl)}></arcgis-portal-mentionable-text-area><div class="chat-actions"><arcgis-portal-voice-input @arcgisVoiceInputStart=${()=>{this.isListening=!0,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputStop=${()=>{this.isListening=!1,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputError=${u=>{u.detail.errorCode==="not-supported"&&(this.showVoiceInput=!1)}} @arcgisVoiceInputInterimTranscription=${u=>{this.inputText=u.detail.text}} ${so(this.voiceInputEl)}></arcgis-portal-voice-input>${s&&Or`<calcite-button icon-start=microphone .label=${e.voiceInput} round .disabled=${i} .appearance=${a?"solid":"outline-fill"} @click=${async()=>{this.isVoiceInputDisabled=!0;let u=this.voiceInputEl.value;a?await u?.stopListening():await u?.startListening()}}></calcite-button>`||""}<calcite-button type=submit icon-start=send round .disabled=${!r.trim()} .label=${e.send}>${e.send}</calcite-button></div></form><arcgis-assistant-agent .agent=${Xb} .context=${{portal:n,user:o}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${yx} .context=${{portal:n,user:o}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${Mx} .context=${{portal:n,user:o}}></arcgis-assistant-agent>${this.interrupt&&Or`<arcgis-portal-ai-assistant-interrupt slot=interrupt .type=${this.interrupt.type} .message=${this.interrupt.message} .options=${this.interrupt.options} @arcgisSubmit=${({detail:u})=>{this.assistantEl.value?.submitInterrupt(u)}} @arcgisCancel=${()=>{this.assistantEl.value?.cancelInterrupt()}}></arcgis-portal-ai-assistant-interrupt>`||""}</arcgis-assistant>`}};cl("arcgis-portal-ai-assistant",rl);return rl},"identity/IdentityManager","portal/Portal","portal/Portal","request","identity/IdentityManager","config","core/reactiveUtils","layers/FeatureLayer","request","layers/FeatureLayer","core/reactiveUtils","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","Graphic","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming","applications/KnowledgeStudio/generalSharedKgUtils","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","request",a)