@hugex/ai 3.1.4 → 3.1.5

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 +1 @@
1
- import{h as a,i as b}from"./chunk-DEW7U7V7.js";import"./chunk-V35SRZAO.js";import"./chunk-ZYIULB2P.js";import"./chunk-6AZ7RATD.js";import"./chunk-XXB57DMN.js";import"./chunk-3K4IMMLP.js";import"./chunk-6JUKM6LT.js";import"./chunk-QEZQZG6Z.js";import"./chunk-V6JSMX5A.js";import"./chunk-YLDLDEUP.js";import"./chunk-U56YWPSI.js";import"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";export{b as FlowExecutionStoppedError,a as startEngine};
1
+ import{h as a,i as b}from"./chunk-DZQ3WL3Y.js";import"./chunk-V35SRZAO.js";import"./chunk-ZYIULB2P.js";import"./chunk-6AZ7RATD.js";import"./chunk-XXB57DMN.js";import"./chunk-3K4IMMLP.js";import"./chunk-6JUKM6LT.js";import"./chunk-QEZQZG6Z.js";import"./chunk-V6JSMX5A.js";import"./chunk-YLDLDEUP.js";import"./chunk-U56YWPSI.js";import"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";export{b as FlowExecutionStoppedError,a as startEngine};
@@ -1,4 +1,4 @@
1
- import{a as Wt}from"./chunk-V35SRZAO.js";import{a as K,b as G,c as Ht,d as tt}from"./chunk-ZYIULB2P.js";import{a as to}from"./chunk-6AZ7RATD.js";import{a as jt,b as Ut,d as Vt,g as Lt,i as st}from"./chunk-XXB57DMN.js";import{a as oo,b as eo}from"./chunk-3K4IMMLP.js";import{A as Xt,B as qt,D as Kt,H as Bt,K as zt,L as Gt,M as Yt,T as Zt,V as Qt,W as Et,X as St,Y as vt,a as B,b as It,k as Ot,n as kt,o as Dt,q as Mt,x as Jt}from"./chunk-6JUKM6LT.js";import{B as Pt,c as S,d as $t,h as bt,k as Z,r as Ct,s as P,v as Q,w as W}from"./chunk-QEZQZG6Z.js";import{a as At,b as _t,d as Ft}from"./chunk-YLDLDEUP.js";import{a as v}from"./chunk-YHXUBVN2.js";import{a as E}from"./chunk-3TXHFKDN.js";async function io(e,o){return e.length?!o||!o.HX_ORA_URL||!o.HX_API_KEY?(console.error("extractDocuments: missing HX_ORA_URL or HX_API_KEY"),e.map(t=>({name:t.name,text:""}))):await Promise.all(e.map(async t=>{try{let s=await fetch(`${o.HX_ORA_URL}/internal/files/extract`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:o.HX_API_KEY},body:JSON.stringify(t)});if(!s.ok)return console.error(`extractDocuments: ${t.name} failed ${s.status}`),{name:t.name,text:""};let u=await s.json();return{name:t.name,text:u.text||""}}catch(s){return console.error(`extractDocuments: ${t.name} threw`,s),{name:t.name,text:""}}})):[]}function No(e,o,i){var t,s,u,p;return Z(((s=(t=i.flowData)==null?void 0:t.state)==null?void 0:s.nodes)??[],((p=(u=i.flowData)==null?void 0:u.state)==null?void 0:p.edges)??[],o.id).some(n=>n.ref===e&&(n.type==="image"||n.type==="file"))}function Ro(e,o){var p,n,f,d,c,g,a;let i=Array.isArray((p=e.data)==null?void 0:p.outputMapping)?e.data.outputMapping:[];if(i.length===0)return null;let t=((f=(n=o.flowData)==null?void 0:n.state)==null?void 0:f.nodes)||[],s={},u=new Set;for(let w of i){let r=(d=w.key)==null?void 0:d.trim(),y=(c=w.from)==null?void 0:c.trim();if(!r||!y)throw new Error(`Answer node ${e.id} has an incomplete variable mapping`);if(u.has(r))throw new Error(`Answer node ${e.id} has duplicate output key "${r}"`);if(No(y,e,o))throw new Error(`Answer node ${e.id} cannot persist binary source "${y}"`);let l=W(y,{context:o.context||{},results:o.results||{},nodes:t,edges:((a=(g=o.flowData)==null?void 0:g.state)==null?void 0:a.edges)??[],currentNodeId:e.id}),m=l.value;if(l.missing||m===void 0||m===null){if(w.default===void 0)throw new P(l.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Answer node ${e.id} could not resolve output "${y}"`);m=w.default}s[r]=m,u.add(r)}try{JSON.stringify(s)}catch{throw new Error(`Answer node ${e.id} produced a value that is not JSON serializable`)}return s}async function nt(e,o,i,t,s,u,p){var f,d,c;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n;try{n=Ro(o,i)}catch(g){throw t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(g)}}),g}n&&e.outputCollector&&e.outputCollector.add(o.id,n);try{let g=await((f=e.getMessages)==null?void 0:f.call(e))??[],a=((d=g[g.length-1])==null?void 0:d.type)==="text"?g[g.length-1].content:"NO-TEXT";p==null||p({type:"answer_node",payload:{userMessage:(c=i==null?void 0:i.context)==null?void 0:c.user_input,answer:a}})}catch(g){console.error("answerNodeRunner: failed to emit answer telemetry:",g),t==null||t({type:"debug",content:"Warning: failed to emit answer telemetry"})}s==null||s(o.id,{type:"answerNode",message:"Answer response for: "+o.data.response,saved:!0,persistenceRequested:!!n&&!!e.outputCollector,persisted:!1,...e.runId?{runId:e.runId}:{}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}function J(e,o,i,t,s){var n,f,d,c,g;let u=(s==null?void 0:s.callerTag)??"llmNodeRunner",p=(s==null?void 0:s.serializeNonStrings)??!1;return Pt(e,o,{context:i.context??{},results:i.results??{},nodes:((f=(n=i.flowData)==null?void 0:n.state)==null?void 0:f.nodes)??[],edges:((c=(d=i.flowData)==null?void 0:d.state)==null?void 0:c.edges)??[],currentNodeId:o.id,secrets:(g=s==null?void 0:s.sessionEnv)==null?void 0:g.secrets},{callerTag:u,serializeNonStrings:p,onError:a=>{t==null||t({type:`error:${u}`,content:a})}})}var at="[redacted]",so=8*1024;function xo(e){if(e==null)return{value:e,truncated:!1};let o=typeof e=="string"?e:JSON.stringify(e),i=new TextEncoder().encode(o);if(i.byteLength<=so){if(typeof e=="string")return{value:e,truncated:!1};try{return{value:JSON.parse(o),truncated:!1}}catch{return{value:o,truncated:!1}}}let t=i.slice(0,so);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function To(e,o){return Q(e,o)}var dt=(e,o,i,t,s)=>J(e,o,i,s,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function ct(e,o,i,t,s,u,p){var d,c,g,a,w,r;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=null,f=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(i.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(i.results||{}));let y=((d=o.data)==null?void 0:d.url)||"",l=dt(y,o,i,e,t);if(console.log("[apiNodeRunner] resolved url:",K(y)?G(l):l),!l){t==null||t({type:"error:apiNodeRunner",content:"Missing url"}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:"Missing url"}}),s==null||s(o.id,n);return}let m=(((c=o.data)==null?void 0:c.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",m);let N=((g=o.data)==null?void 0:g.headers)||{},R={},h={};for(let U in N)if(Object.prototype.hasOwnProperty.call(N,U)){let j=String(N[U]??"");h[U]=K(j),R[U]=dt(j,o,i,e,t)}let T,k=!1;if(m!=="GET"&&m!=="HEAD"&&((a=o.data)==null?void 0:a.body)!==void 0){let U=typeof o.data.body=="string"?o.data.body:JSON.stringify(o.data.body);k=K(U),T=dt(U,o,i,e,t),!R["Content-Type"]&&!R["content-type"]&&(R["Content-Type"]="application/json")}let _={};for(let U in R)_[U]=h[U]?at:R[U];console.log("[apiNodeRunner] headers:",JSON.stringify(_)),console.log("[apiNodeRunner] body:",k?at:T),t==null||t({type:"info:apiNodeRunner:request",content:{nodeId:o.id,method:m,url:K(y)?G(l):l,headers:_,body:k?at:T}});let b=Number((w=o.data)==null?void 0:w.timeoutMs),C=new AbortController,F=Number.isFinite(b)&&b>0?setTimeout(()=>C.abort(),b):null,x;try{console.log("[apiNodeRunner] fetching..."),x=await fetch(l,{method:m,headers:R,body:T,signal:C.signal}),console.log("[apiNodeRunner] fetch returned status:",x.status)}finally{F&&clearTimeout(F)}let D=x.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",D);let M=await Ct(x);console.log("[apiNodeRunner] payload preview:",typeof M=="string"?M.slice(0,200):JSON.stringify(M).slice(0,200)),n={ok:x.ok,status:x.status,data:M};let V=Date.now()-f;p==null||p({type:"api_call",payload:{nodeId:o.id,url:l,method:m,status:x.status,latencyMs:V}});let{value:I,truncated:q}=xo(M);t==null||t({type:"info:apiNodeRunner:response",content:{nodeId:o.id,ok:x.ok,status:x.status,latencyMs:V,data:I,truncated:q,outVars:To(o,n)}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}catch(y){console.error("Error processing ApiNode:",y),t==null||t({type:"error:apiNodeRunner",content:`API node execution failed: ${y}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(y)}})}finally{console.log("[apiNodeRunner] final result:",(r=JSON.stringify(n))==null?void 0:r.slice(0,300)),s==null||s(o.id,n)}}var Ao="[redacted]",no=8*1024;function lt(e,o){if(typeof e=="string")return K(e)?typeof o=="string"&&/^https?:\/\//i.test(o)?G(o):Ao:o;if(e&&typeof e=="object"&&!Array.isArray(e)){let i={},t=o&&typeof o=="object"&&!Array.isArray(o)?o:{};for(let[s,u]of Object.entries(e))i[s]=lt(u,t[s]);return i}if(Array.isArray(e)){let i=Array.isArray(o)?o:[];return e.map((t,s)=>lt(t,i[s]))}return o}function _o(e){if(e==null)return{value:e,truncated:!1};let o=typeof e=="string"?e:JSON.stringify(e),i=new TextEncoder().encode(o);if(i.byteLength<=no){if(typeof e=="string")return{value:e,truncated:!1};try{return{value:JSON.parse(o),truncated:!1}}catch{return{value:o,truncated:!1}}}let t=i.slice(0,no);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function Fo(e,o){return Q(e,o)}var $o=(e,o,i,t,s)=>J(e,o,i,s,{callerTag:"toolNodeRunner",serializeNonStrings:!0,sessionEnv:t});function ot(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Io(e){let o=ot(e);if(Array.isArray(o.enum)&&o.enum.length>0)return o.enum.every(s=>typeof s=="string"||typeof s=="number")?"enum":"unsupported";switch(Array.isArray(o.type)?o.type.find(t=>typeof t=="string"&&t!=="null"):o.type){case"string":return"string";case"number":return"number";case"integer":return"integer";case"boolean":return"boolean";case"object":return"object";case"array":return"array";default:return"unsupported"}}function Oo(e,o){var p,n;let i={},t={},s=((p=e.data)==null?void 0:p.inputSchema)??o;if(s&&typeof s=="object"&&!Array.isArray(s)){t=ot(ot(s).properties);for(let[f,d]of Object.entries(t))i[f]=Io(d);return{types:i,properties:t}}let u=(n=e.data)==null?void 0:n.argTypes;if(u&&typeof u=="object"&&!Array.isArray(u))for(let[f,d]of Object.entries(u))typeof d=="string"&&(i[f]=d);return{types:i,properties:t}}function ko(e,o,i){if(e.trim()!==""){if(e==="null"&&o&&o!=="string"&&o!=="enum")return null;switch(o){case"string":return e;case"enum":{let t=ot(i).enum;if(Array.isArray(t)){let s=t.find(u=>String(u)===e);if(s!==void 0)return s}return e}case"number":{let t=Number(e);return Number.isFinite(t)?t:e}case"integer":{let t=Number.parseInt(e,10);return Number.isFinite(t)?t:e}case"boolean":return e==="true"?!0:e==="false"?!1:e;case"object":case"array":case"unsupported":try{return JSON.parse(e)}catch{return e}default:return e}}}function Do(e){return e===void 0||typeof e=="string"&&e.trim()===""}function ut(e,o,i,t,s,u,p){if(typeof e=="string"){let n=e.includes("{{")?$o(e,o,i,t,s):e;return ko(n,u,p)}if(e&&typeof e=="object"&&!Array.isArray(e)){let n={};for(let[f,d]of Object.entries(e))n[f]=ut(d,o,i,t,s);return n}return Array.isArray(e)?e.map(n=>ut(n,o,i,t,s)):e}function Mo(e,o,i,t,s,u){let p={};for(let[n,f]of Object.entries(e)){let d=ut(f,o,i,t,s,u.types[n],u.properties[n]);Do(d)||(p[n]=d)}return p}async function bo(e){if(e.toolDefs)return e.toolDefs;if(!e.env)return e.toolDefs={},e.toolDefs;let o=await v(e.env),i={};for(let t of o)t!=null&&t.id&&(i[t.id]=t);return e.toolDefs=i,i}function Co(e){var o,i,t;return((o=e.data)==null?void 0:o.source)==="catalog"?"catalog":((i=e.data)==null?void 0:i.source)==="composio"?"composio":(((t=e.data)==null?void 0:t.source)==="http","http")}function Po(e,o,i){let t=st(e.execution);if(t.authMode==="manual"){let s=jt(t,e.id);if(!s)throw new Error(`Composio tool '${e.name}' is missing connection scope`);return Ut(s)}return Lt(o,i,{allowChatIdFallback:!0})}async function pt(e,o,i,t,s,u,p){var c,g,a,w,r,y;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n={ok:!1,data:null,error:null},f=Date.now(),d=Co(o);try{if(d==="catalog")throw new Error("This Tool node still uses a curated catalog connector. Reconfigure it to a tenant HTTP or connector tool.");let l=(c=o.data)!=null&&c.args&&typeof o.data.args=="object"&&!Array.isArray(o.data.args)?o.data.args:{},m=typeof((g=o.data)==null?void 0:g.toolId)=="string"?o.data.toolId.trim():"";if(!m)throw new Error("Tool nodes require toolId");let R=(await bo(e))[m];if(!R)throw new Error(`Tool ${m} not found`);let h="";if(d==="composio"){if(R.kind!=="composio")throw new Error(`Tool ${m} is not a connector tool`);if(h=typeof((a=o.data)==null?void 0:a.toolSlug)=="string"?o.data.toolSlug.trim():"",!h)throw new Error("Connector tool nodes require toolSlug");let F=st(R.execution);if(!Vt(F.tools).includes(h))throw new Error(`Tool slug ${h} is not enabled on connector ${m}`)}else if(R.kind!=="http")throw new Error(`Tool ${m} is not an HTTP tool`);let T=Oo(o,d==="http"?R.inputSchema:void 0),k=Mo(l,o,i,e,t,T);if(t==null||t({type:"info:toolNodeRunner:request",content:{nodeId:o.id,source:d,toolSlug:(w=o.data)==null?void 0:w.toolSlug,toolId:(r=o.data)==null?void 0:r.toolId,args:lt(l,k)}}),d==="composio"){let F=typeof((y=o.data)==null?void 0:y.toolVersion)=="string"?o.data.toolVersion.trim():"",x=await Wt(e,{toolSlug:h,connectionScope:Po(R,e,i),toolVersion:F||null,arguments:k});n={ok:x.ok,data:x.ok?x.data:null,error:x.ok?null:x.error??"Tool execution failed"}}else{let F=tt(R,e,i,t);if(!F.execute)throw new Error(`Tool ${m} is missing an execute handler`);let x=await F.execute(k,{}),D=x&&typeof x=="object"&&"error"in x&&x.error?String(x.error):null;n={ok:!D,data:x,error:D}}let _=Date.now()-f;p==null||p({type:"tool_call",payload:{nodeId:o.id,url:d==="composio"?`composio:${h}`:`tool:${m}`,method:"EXECUTE",status:n.ok?200:502,latencyMs:_}});let{value:b,truncated:C}=_o(n.data);t==null||t({type:"info:toolNodeRunner:response",content:{nodeId:o.id,ok:n.ok,latencyMs:_,data:b,truncated:C,error:n.error,outVars:Fo(o,n)}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:n.ok?"success":"error",error:n.error??void 0}})}catch(l){let m=l instanceof Error?l.message:String(l);n={ok:!1,data:null,error:m},t==null||t({type:"error:toolNodeRunner",content:`Tool node execution failed: ${m}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:m}})}finally{s==null||s(o.id,n)}}var jo=1440*60*1e3,ao=8*1024;function co(e){if(e==null)return{value:e,truncated:!1};let o=new TextEncoder().encode(JSON.stringify(e));return o.byteLength<=ao?{value:e,truncated:!1}:{value:new TextDecoder().decode(o.slice(0,ao)),truncated:!0}}async function ft(e,o,i,t,s,u,p){var g,a,w;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n={ok:!1,data:null,error:null},f=Date.now(),d="crawl:unknown",c=r=>{let y=JSON.stringify(r);for(let l of Object.values(e.secrets??{}))l&&(y=y.split(JSON.stringify(l).slice(1,-1)).join("[redacted]"),y=y.split(encodeURIComponent(l)).join("[redacted]"));return JSON.parse(y)};try{if(!Jt("crawlNode",(g=i.flowData)==null?void 0:g.tenant))throw new Error("Crawl node no disponible para este tenant");let r=e.env;if(!(r!=null&&r.CF_ACCOUNT_ID)||!(r!=null&&r.CF_BROWSER_RUN_TOKEN))throw new Error("Crawl no configurado: faltan CF_ACCOUNT_ID / CF_BROWSER_RUN_TOKEN");let y=J(o.data.url,o,i,t,{callerTag:"crawlNodeRunner",serializeNonStrings:!0,sessionEnv:e}),l=Xt(o.data,y),m=K(o.data.url);d=`crawl:${c(new URL(y).host)}`;let N=`crawl:pending:${await qt(l)}`,R=(a=e.ctx)==null?void 0:a.storage,h=await(R==null?void 0:R.get(N)),T=h&&typeof h.jobId=="string"&&h.jobId&&Number.isFinite(h.createdAt)&&Date.now()-h.createdAt>=0&&Date.now()-h.createdAt<jo;h&&!T&&await(R==null?void 0:R.delete(N)),t==null||t({type:"info:crawlNodeRunner:request",content:{nodeId:o.id,url:m?c(G(y)):y,resumeJobId:T?h.jobId:void 0}}),{result:n}=await Kt({accountId:r.CF_ACCOUNT_ID,apiToken:r.CF_BROWSER_RUN_TOKEN},o.data,{url:y,...T?{resumeJobId:h.jobId}:{}}),n.error==="timeout"&&((w=n.data)!=null&&w.jobId)?await(R==null?void 0:R.put(N,{jobId:n.data.jobId,createdAt:T?h.createdAt:Date.now()})):n.data&&n.data.status!=="running"&&await(R==null?void 0:R.delete(N))}catch(r){n={ok:!1,data:null,error:r instanceof Error?r.message:String(r)},t==null||t({type:"error:crawlNodeRunner",content:c(`Crawl node execution failed: ${n.error}`)})}finally{let r=Date.now()-f;p==null||p({type:"tool_call",payload:{nodeId:o.id,url:d,method:"EXECUTE",status:n.ok?200:502,latencyMs:r}});let y=co(c(n.data));t==null||t({type:"info:crawlNodeRunner:response",content:{nodeId:o.id,ok:n.ok,latencyMs:r,data:y.value,truncated:y.truncated,error:c(n.error),outVars:co(c(Q(o,n))).value}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:n.ok?"success":"error",error:c(n.error)??void 0}}),s==null||s(o.id,n)}}function lo(){let e={};return{add(o,i){e[o]=i},hasOutputs(){return Object.keys(e).length>0},answerNodeIds(){return Object.keys(e)},snapshotData(){let o=Object.entries(e);return o.length===1?o[0][1]:Object.fromEntries(o)}}}function Uo(e){return!!(e!=null&&e.HX_ORA_URL)&&!!(e!=null&&e.HX_API_KEY)}async function Ve(e,o){if(!Uo(e))throw new Error("Structured outputs require HX_ORA_URL and HX_API_KEY");let i=await fetch(`${e.HX_ORA_URL}/internal/outputs/${encodeURIComponent(o.flowId)}/${encodeURIComponent(o.sessionId)}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:e.HX_API_KEY},body:JSON.stringify({runId:o.runId,createdAt:o.createdAt,data:o.data,answerNodeIds:o.answerNodeIds})});if(!i.ok){let t=await i.text().catch(()=>"");throw new Error(`Structured output persistence failed with ${i.status}${t?`: ${t}`:""}`)}}var uo=3,po=10,Vo=new Set(["agent:start","agent:complete","agent:telemetry"]);function Lo(e){let o=e.executedNodes||[];return o.length===0?"(none)":o.map(i=>i.label?`${i.id} (${i.label})`:i.id).join(" \u2192 ")}function Wo(e){let o=e.executedNodes||[];return o[o.length-1]}function X(e,o,i){throw e==null||e({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:i.message}}),i}function Ho(e,o){var u,p,n,f,d,c,g;let i=Array.isArray((u=e.data)==null?void 0:u.inputs)?e.data.inputs:[],t=((n=(p=o.flowData)==null?void 0:p.state)==null?void 0:n.nodes)||[],s={};for(let a of i){let w=(f=a.key)==null?void 0:f.trim();if(!w)continue;let r=(d=a.from)==null?void 0:d.trim();if(!r){if(a.default===void 0)continue;s[w]=a.default;continue}let y=W(r,{context:o.context||{},results:o.results||{},nodes:t,edges:((g=(c=o.flowData)==null?void 0:c.state)==null?void 0:g.edges)??[],currentNodeId:e.id}),l=y.value;if(y.missing||l===void 0||l===null){if(a.default===void 0)throw new P(y.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Worker node ${e.id} could not resolve input "${r}"`);l=a.default}s[w]=l}return s}async function mt(e,o,i,t,s,u,p){var C,F,x,D,M,V;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=typeof((C=o.data)==null?void 0:C.flowId)=="string"?o.data.flowId.trim():"";n||X(t,o,new Error(`Worker node ${o.id} is missing flowId`));let f=(F=i.flowData)==null?void 0:F.flowId,d=e.workerStack??(f?[f]:[]);d.includes(n)&&X(t,o,new Error(`Worker node ${o.id} cannot call ${n}: cycle detected (${[...d,n].join(" \u2192 ")})`)),d.length>=uo&&X(t,o,new Error(`Worker node ${o.id} exceeded max nesting depth (${uo})`));let c=e.workerCalls??{count:0};e.workerCalls=c,c.count>=po&&X(t,o,new Error(`Worker node ${o.id} exceeded max worker calls per run (${po})`)),c.count+=1;let g;try{g=Ho(o,i)}catch(I){X(t,o,I instanceof Error?I:new Error(String(I)));return}let a=e.env;a||X(t,o,new Error(`Worker node ${o.id} is missing runtime env`));let w,r;try{let I=await At(n,a);r=(x=I==null?void 0:I.metadata)==null?void 0:x.tenant,w=await _t(n,a)}catch(I){X(t,o,new Error(`Worker node ${o.id} could not load worker ${n}: ${I instanceof Error?I.message:String(I)}`))}let y=(D=i.flowData)==null?void 0:D.tenant;(!r||r!==y)&&X(t,o,new Error(`Worker ${n} belongs to a different tenant`));let l=lo(),m={flowData:{...w,tenant:r,flowId:n,chatId:((M=i.flowData)==null?void 0:M.chatId)||""},executedNodes:[],context:{},results:{}},N={env:a,ctx:e.ctx,secrets:e.secrets,userAuth:e.userAuth,user:e.user,toolDefs:e.toolDefs,composioSessions:e.composioSessions,skillRefCache:e.skillRefCache,publicOrigin:e.publicOrigin,getOraModel:e.getOraModel,runId:e.runId,shouldStop:e.shouldStop,workerCalls:c,conn:void 0,getMessages:async()=>[],setMessages:async()=>{},agentMemory:"",outputCollector:l,workerStack:[...d,n]},R,h={onChangeState:()=>{},onServerEvent:I=>{var q;Vo.has(I.type)||t==null||t({type:"worker:node",content:{workerNodeId:o.id,childNodeId:(q=I.content)==null?void 0:q.nodeId,event:I}})},onTelemetry:I=>p==null?void 0:p(I),onError:I=>{R=I},shouldStop:e.shouldStop},{startEngine:T,FlowExecutionStoppedError:k}=await import("./FlowEngine-H3QNWZVB.js"),_=await T(N,m,h)({text:"",inputs:g});if((_.status==="stopped"||await((V=e.shouldStop)==null?void 0:V.call(e)))&&X(t,o,new k),_.status!=="completed"){let I=Wo(m),q=Lo(m),U=_.error||R||"unknown error",j=I?` at node ${I.label?`${I.id} (${I.label})`:I.id}`:"";X(t,o,new Error(`Worker ${n} failed${j}: ${U}. Path: ${q}`))}l.hasOutputs()||X(t,o,new Error(`El worker ${n} complet\xF3 sin output estructurado. Agreg\xE1 un mapeo de salida en su nodo Answer.`));let b=(m.executedNodes||[]).map(I=>I.id);s==null||s(o.id,{ok:!0,data:l.snapshotData(),error:null,executed:b}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}import{generateObject as Zo}from"ai";import{z as fo}from"zod";import{openai as Jo}from"@ai-sdk/openai";import{extractReasoningMiddleware as Xo,wrapLanguageModel as qo}from"ai";import{createWorkersAI as Ko}from"workers-ai-provider";import{xai as Bo}from"@ai-sdk/xai";import{anthropic as zo}from"@ai-sdk/anthropic";import{createOpenRouter as Go}from"@openrouter/ai-sdk-provider";var gt={};function yt(e){if(e!=null){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}}function Yo(e){return{...e,defaultParams:yt(e.defaultParams)??e.defaultParams,capabilities:yt(e.capabilities)??e.capabilities,price:yt(e.price)??e.price}}async function et(e,o,i){var c,g;if(!(o!=null&&o.getOraModel))throw new Error("resolveModelById requires a sessionEnv with getOraModel capable of fetching models dynamically.");let t=await o.getOraModel(e);if(!t)return;let s=Yo(t),u=((c=s.capabilities)==null?void 0:c.params)??Bt(s),{effectiveParams:p,adjustments:n}=Gt(s.defaultParams,i,u),f;if(gt[s.provider])f=await gt[s.provider](s,o,i);else if(s.provider==="openai")f=Jo(s.providerModel);else if(s.provider==="xai")f=Bo(s.providerModel);else if(s.provider==="anthropic")f=zo(s.providerModel);else if(s.provider==="openrouter")f=Go()(s.providerModel);else if(s.provider==="workersai"||s.provider==="cloudflare"){if(!((g=o==null?void 0:o.env)!=null&&g.AI))throw new Error("Workers AI provider requires sessionEnv.env.AI binding");f=Ko({binding:o.env.AI})(s.providerModel)}else f={provider:s.provider,providerModel:s.providerModel};let d=Zt(s);return d.kind==="tag"&&f&&typeof f=="object"&&"specificationVersion"in f&&(f=qo({model:f,middleware:Xo({tagName:d.tagName??"think",startWithReasoning:d.startWithReasoning??!1})})),{provider:s.provider,modelHandle:f,entry:s,effectiveParams:p,paramAdjustments:n.length>0?n:void 0,reasoning:d}}function Ee(e,o){gt[e]=o}async function wt(e,o,i,t,s,u,p){var r,y,l,m,N,R,h;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=String(((r=o==null?void 0:o.data)==null?void 0:r.input_variable)||"user_input").trim(),f;try{let T=W(n,{context:i.context??{},results:i.results??{},nodes:((l=(y=i.flowData)==null?void 0:y.state)==null?void 0:l.nodes)??[],edges:((N=(m=i.flowData)==null?void 0:m.state)==null?void 0:N.edges)??[],currentNodeId:o.id});if(T.missing)throw new Error(`Classifier input "${n}" did not produce a value`);f=T.value}catch(T){throw t==null||t({type:"error:classifier",content:String(T)}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(T)}}),T}let d=Array.isArray((R=o==null?void 0:o.data)==null?void 0:R.items)?o.data.items:[];if(d.length===0){t==null||t({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let c=String((h=d[d.length-1])==null?void 0:h.id);if(!f||String(f).trim().length===0){t==null||t({type:"warning:classifier",content:"No input for classification \u2014 falling back to last item."}),s==null||s(o.id,{classification:c}),i.context=i.context||{},i.context.classified_id=c,u==null||u(i);return}let a=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
1
+ import{a as Wt}from"./chunk-V35SRZAO.js";import{a as K,b as G,c as Ht,d as tt}from"./chunk-ZYIULB2P.js";import{a as to}from"./chunk-6AZ7RATD.js";import{a as jt,b as Ut,d as Vt,g as Lt,i as st}from"./chunk-XXB57DMN.js";import{a as oo,b as eo}from"./chunk-3K4IMMLP.js";import{A as Xt,B as qt,D as Kt,H as Bt,K as zt,L as Gt,M as Yt,T as Zt,V as Qt,W as Et,X as St,Y as vt,a as B,b as It,k as Ot,n as kt,o as Dt,q as Mt,x as Jt}from"./chunk-6JUKM6LT.js";import{B as Pt,c as S,d as $t,h as bt,k as Z,r as Ct,s as P,v as Q,w as W}from"./chunk-QEZQZG6Z.js";import{a as At,b as _t,d as Ft}from"./chunk-YLDLDEUP.js";import{a as v}from"./chunk-YHXUBVN2.js";import{a as E}from"./chunk-3TXHFKDN.js";async function io(e,o){return e.length?!o||!o.HX_ORA_URL||!o.HX_API_KEY?(console.error("extractDocuments: missing HX_ORA_URL or HX_API_KEY"),e.map(t=>({name:t.name,text:""}))):await Promise.all(e.map(async t=>{try{let s=await fetch(`${o.HX_ORA_URL}/internal/files/extract`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:o.HX_API_KEY},body:JSON.stringify(t)});if(!s.ok)return console.error(`extractDocuments: ${t.name} failed ${s.status}`),{name:t.name,text:""};let u=await s.json();return{name:t.name,text:u.text||""}}catch(s){return console.error(`extractDocuments: ${t.name} threw`,s),{name:t.name,text:""}}})):[]}function No(e,o,i){var t,s,u,p;return Z(((s=(t=i.flowData)==null?void 0:t.state)==null?void 0:s.nodes)??[],((p=(u=i.flowData)==null?void 0:u.state)==null?void 0:p.edges)??[],o.id).some(n=>n.ref===e&&(n.type==="image"||n.type==="file"))}function Ro(e,o){var p,n,f,d,c,g,a;let i=Array.isArray((p=e.data)==null?void 0:p.outputMapping)?e.data.outputMapping:[];if(i.length===0)return null;let t=((f=(n=o.flowData)==null?void 0:n.state)==null?void 0:f.nodes)||[],s={},u=new Set;for(let w of i){let r=(d=w.key)==null?void 0:d.trim(),y=(c=w.from)==null?void 0:c.trim();if(!r||!y)throw new Error(`Answer node ${e.id} has an incomplete variable mapping`);if(u.has(r))throw new Error(`Answer node ${e.id} has duplicate output key "${r}"`);if(No(y,e,o))throw new Error(`Answer node ${e.id} cannot persist binary source "${y}"`);let l=W(y,{context:o.context||{},results:o.results||{},nodes:t,edges:((a=(g=o.flowData)==null?void 0:g.state)==null?void 0:a.edges)??[],currentNodeId:e.id}),m=l.value;if(l.missing||m===void 0||m===null){if(w.default===void 0)throw new P(l.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Answer node ${e.id} could not resolve output "${y}"`);m=w.default}s[r]=m,u.add(r)}try{JSON.stringify(s)}catch{throw new Error(`Answer node ${e.id} produced a value that is not JSON serializable`)}return s}async function nt(e,o,i,t,s,u,p){var f,d,c;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n;try{n=Ro(o,i)}catch(g){throw t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(g)}}),g}n&&e.outputCollector&&e.outputCollector.add(o.id,n);try{let g=await((f=e.getMessages)==null?void 0:f.call(e))??[],a=((d=g[g.length-1])==null?void 0:d.type)==="text"?g[g.length-1].content:"NO-TEXT";p==null||p({type:"answer_node",payload:{userMessage:(c=i==null?void 0:i.context)==null?void 0:c.user_input,answer:a}})}catch(g){console.error("answerNodeRunner: failed to emit answer telemetry:",g),t==null||t({type:"debug",content:"Warning: failed to emit answer telemetry"})}s==null||s(o.id,{type:"answerNode",message:"Answer response for: "+o.data.response,saved:!0,persistenceRequested:!!n&&!!e.outputCollector,persisted:!1,...e.runId?{runId:e.runId}:{}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}function J(e,o,i,t,s){var n,f,d,c,g;let u=(s==null?void 0:s.callerTag)??"llmNodeRunner",p=(s==null?void 0:s.serializeNonStrings)??!1;return Pt(e,o,{context:i.context??{},results:i.results??{},nodes:((f=(n=i.flowData)==null?void 0:n.state)==null?void 0:f.nodes)??[],edges:((c=(d=i.flowData)==null?void 0:d.state)==null?void 0:c.edges)??[],currentNodeId:o.id,secrets:(g=s==null?void 0:s.sessionEnv)==null?void 0:g.secrets},{callerTag:u,serializeNonStrings:p,onError:a=>{t==null||t({type:`error:${u}`,content:a})}})}var at="[redacted]",so=8*1024;function xo(e){if(e==null)return{value:e,truncated:!1};let o=typeof e=="string"?e:JSON.stringify(e),i=new TextEncoder().encode(o);if(i.byteLength<=so){if(typeof e=="string")return{value:e,truncated:!1};try{return{value:JSON.parse(o),truncated:!1}}catch{return{value:o,truncated:!1}}}let t=i.slice(0,so);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function To(e,o){return Q(e,o)}var dt=(e,o,i,t,s)=>J(e,o,i,s,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function ct(e,o,i,t,s,u,p){var d,c,g,a,w,r;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=null,f=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(i.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(i.results||{}));let y=((d=o.data)==null?void 0:d.url)||"",l=dt(y,o,i,e,t);if(console.log("[apiNodeRunner] resolved url:",K(y)?G(l):l),!l){t==null||t({type:"error:apiNodeRunner",content:"Missing url"}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:"Missing url"}}),s==null||s(o.id,n);return}let m=(((c=o.data)==null?void 0:c.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",m);let N=((g=o.data)==null?void 0:g.headers)||{},R={},h={};for(let U in N)if(Object.prototype.hasOwnProperty.call(N,U)){let j=String(N[U]??"");h[U]=K(j),R[U]=dt(j,o,i,e,t)}let T,k=!1;if(m!=="GET"&&m!=="HEAD"&&((a=o.data)==null?void 0:a.body)!==void 0){let U=typeof o.data.body=="string"?o.data.body:JSON.stringify(o.data.body);k=K(U),T=dt(U,o,i,e,t),!R["Content-Type"]&&!R["content-type"]&&(R["Content-Type"]="application/json")}let _={};for(let U in R)_[U]=h[U]?at:R[U];console.log("[apiNodeRunner] headers:",JSON.stringify(_)),console.log("[apiNodeRunner] body:",k?at:T),t==null||t({type:"info:apiNodeRunner:request",content:{nodeId:o.id,method:m,url:K(y)?G(l):l,headers:_,body:k?at:T}});let b=Number((w=o.data)==null?void 0:w.timeoutMs),C=new AbortController,F=Number.isFinite(b)&&b>0?setTimeout(()=>C.abort(),b):null,x;try{console.log("[apiNodeRunner] fetching..."),x=await fetch(l,{method:m,headers:R,body:T,signal:C.signal}),console.log("[apiNodeRunner] fetch returned status:",x.status)}finally{F&&clearTimeout(F)}let D=x.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",D);let M=await Ct(x);console.log("[apiNodeRunner] payload preview:",typeof M=="string"?M.slice(0,200):JSON.stringify(M).slice(0,200)),n={ok:x.ok,status:x.status,data:M};let V=Date.now()-f;p==null||p({type:"api_call",payload:{nodeId:o.id,url:l,method:m,status:x.status,latencyMs:V}});let{value:I,truncated:q}=xo(M);t==null||t({type:"info:apiNodeRunner:response",content:{nodeId:o.id,ok:x.ok,status:x.status,latencyMs:V,data:I,truncated:q,outVars:To(o,n)}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}catch(y){console.error("Error processing ApiNode:",y),t==null||t({type:"error:apiNodeRunner",content:`API node execution failed: ${y}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(y)}})}finally{console.log("[apiNodeRunner] final result:",(r=JSON.stringify(n))==null?void 0:r.slice(0,300)),s==null||s(o.id,n)}}var Ao="[redacted]",no=8*1024;function lt(e,o){if(typeof e=="string")return K(e)?typeof o=="string"&&/^https?:\/\//i.test(o)?G(o):Ao:o;if(e&&typeof e=="object"&&!Array.isArray(e)){let i={},t=o&&typeof o=="object"&&!Array.isArray(o)?o:{};for(let[s,u]of Object.entries(e))i[s]=lt(u,t[s]);return i}if(Array.isArray(e)){let i=Array.isArray(o)?o:[];return e.map((t,s)=>lt(t,i[s]))}return o}function _o(e){if(e==null)return{value:e,truncated:!1};let o=typeof e=="string"?e:JSON.stringify(e),i=new TextEncoder().encode(o);if(i.byteLength<=no){if(typeof e=="string")return{value:e,truncated:!1};try{return{value:JSON.parse(o),truncated:!1}}catch{return{value:o,truncated:!1}}}let t=i.slice(0,no);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function Fo(e,o){return Q(e,o)}var $o=(e,o,i,t,s)=>J(e,o,i,s,{callerTag:"toolNodeRunner",serializeNonStrings:!0,sessionEnv:t});function ot(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Io(e){let o=ot(e);if(Array.isArray(o.enum)&&o.enum.length>0)return o.enum.every(s=>typeof s=="string"||typeof s=="number")?"enum":"unsupported";switch(Array.isArray(o.type)?o.type.find(t=>typeof t=="string"&&t!=="null"):o.type){case"string":return"string";case"number":return"number";case"integer":return"integer";case"boolean":return"boolean";case"object":return"object";case"array":return"array";default:return"unsupported"}}function Oo(e,o){var p,n;let i={},t={},s=((p=e.data)==null?void 0:p.inputSchema)??o;if(s&&typeof s=="object"&&!Array.isArray(s)){t=ot(ot(s).properties);for(let[f,d]of Object.entries(t))i[f]=Io(d);return{types:i,properties:t}}let u=(n=e.data)==null?void 0:n.argTypes;if(u&&typeof u=="object"&&!Array.isArray(u))for(let[f,d]of Object.entries(u))typeof d=="string"&&(i[f]=d);return{types:i,properties:t}}function ko(e,o,i){if(e.trim()!==""){if(e==="null"&&o&&o!=="string"&&o!=="enum")return null;switch(o){case"string":return e;case"enum":{let t=ot(i).enum;if(Array.isArray(t)){let s=t.find(u=>String(u)===e);if(s!==void 0)return s}return e}case"number":{let t=Number(e);return Number.isFinite(t)?t:e}case"integer":{let t=Number.parseInt(e,10);return Number.isFinite(t)?t:e}case"boolean":return e==="true"?!0:e==="false"?!1:e;case"object":case"array":case"unsupported":try{return JSON.parse(e)}catch{return e}default:return e}}}function Do(e){return e===void 0||typeof e=="string"&&e.trim()===""}function ut(e,o,i,t,s,u,p){if(typeof e=="string"){let n=e.includes("{{")?$o(e,o,i,t,s):e;return ko(n,u,p)}if(e&&typeof e=="object"&&!Array.isArray(e)){let n={};for(let[f,d]of Object.entries(e))n[f]=ut(d,o,i,t,s);return n}return Array.isArray(e)?e.map(n=>ut(n,o,i,t,s)):e}function Mo(e,o,i,t,s,u){let p={};for(let[n,f]of Object.entries(e)){let d=ut(f,o,i,t,s,u.types[n],u.properties[n]);Do(d)||(p[n]=d)}return p}async function bo(e){if(e.toolDefs)return e.toolDefs;if(!e.env)return e.toolDefs={},e.toolDefs;let o=await v(e.env),i={};for(let t of o)t!=null&&t.id&&(i[t.id]=t);return e.toolDefs=i,i}function Co(e){var o,i,t;return((o=e.data)==null?void 0:o.source)==="catalog"?"catalog":((i=e.data)==null?void 0:i.source)==="composio"?"composio":(((t=e.data)==null?void 0:t.source)==="http","http")}function Po(e,o,i){let t=st(e.execution);if(t.authMode==="manual"){let s=jt(t,e.id);if(!s)throw new Error(`Composio tool '${e.name}' is missing connection scope`);return Ut(s)}return Lt(o,i,{allowChatIdFallback:!0})}async function pt(e,o,i,t,s,u,p){var c,g,a,w,r,y;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n={ok:!1,data:null,error:null},f=Date.now(),d=Co(o);try{if(d==="catalog")throw new Error("This Tool node still uses a curated catalog connector. Reconfigure it to a tenant HTTP or connector tool.");let l=(c=o.data)!=null&&c.args&&typeof o.data.args=="object"&&!Array.isArray(o.data.args)?o.data.args:{},m=typeof((g=o.data)==null?void 0:g.toolId)=="string"?o.data.toolId.trim():"";if(!m)throw new Error("Tool nodes require toolId");let R=(await bo(e))[m];if(!R)throw new Error(`Tool ${m} not found`);let h="";if(d==="composio"){if(R.kind!=="composio")throw new Error(`Tool ${m} is not a connector tool`);if(h=typeof((a=o.data)==null?void 0:a.toolSlug)=="string"?o.data.toolSlug.trim():"",!h)throw new Error("Connector tool nodes require toolSlug");let F=st(R.execution);if(!Vt(F.tools).includes(h))throw new Error(`Tool slug ${h} is not enabled on connector ${m}`)}else if(R.kind!=="http")throw new Error(`Tool ${m} is not an HTTP tool`);let T=Oo(o,d==="http"?R.inputSchema:void 0),k=Mo(l,o,i,e,t,T);if(t==null||t({type:"info:toolNodeRunner:request",content:{nodeId:o.id,source:d,toolSlug:(w=o.data)==null?void 0:w.toolSlug,toolId:(r=o.data)==null?void 0:r.toolId,args:lt(l,k)}}),d==="composio"){let F=typeof((y=o.data)==null?void 0:y.toolVersion)=="string"?o.data.toolVersion.trim():"",x=await Wt(e,{toolSlug:h,connectionScope:Po(R,e,i),toolVersion:F||null,arguments:k});n={ok:x.ok,data:x.ok?x.data:null,error:x.ok?null:x.error??"Tool execution failed"}}else{let F=tt(R,e,i,t);if(!F.execute)throw new Error(`Tool ${m} is missing an execute handler`);let x=await F.execute(k,{}),D=x&&typeof x=="object"&&"error"in x&&x.error?String(x.error):null;n={ok:!D,data:x,error:D}}let _=Date.now()-f;p==null||p({type:"tool_call",payload:{nodeId:o.id,url:d==="composio"?`composio:${h}`:`tool:${m}`,method:"EXECUTE",status:n.ok?200:502,latencyMs:_}});let{value:b,truncated:C}=_o(n.data);t==null||t({type:"info:toolNodeRunner:response",content:{nodeId:o.id,ok:n.ok,latencyMs:_,data:b,truncated:C,error:n.error,outVars:Fo(o,n)}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:n.ok?"success":"error",error:n.error??void 0}})}catch(l){let m=l instanceof Error?l.message:String(l);n={ok:!1,data:null,error:m},t==null||t({type:"error:toolNodeRunner",content:`Tool node execution failed: ${m}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:m}})}finally{s==null||s(o.id,n)}}var jo=1440*60*1e3,ao=8*1024;function co(e){if(e==null)return{value:e,truncated:!1};let o=new TextEncoder().encode(JSON.stringify(e));return o.byteLength<=ao?{value:e,truncated:!1}:{value:new TextDecoder().decode(o.slice(0,ao)),truncated:!0}}async function ft(e,o,i,t,s,u,p){var g,a,w;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n={ok:!1,data:null,error:null},f=Date.now(),d="crawl:unknown",c=r=>{let y=JSON.stringify(r);for(let l of Object.values(e.secrets??{}))l&&(y=y.split(JSON.stringify(l).slice(1,-1)).join("[redacted]"),y=y.split(encodeURIComponent(l)).join("[redacted]"));return JSON.parse(y)};try{if(!Jt("crawlNode",(g=i.flowData)==null?void 0:g.tenant))throw new Error("Crawl node no disponible para este tenant");let r=e.env;if(!(r!=null&&r.CF_ACCOUNT_ID)||!(r!=null&&r.CF_BROWSER_RUN_TOKEN))throw new Error("Crawl no configurado: faltan CF_ACCOUNT_ID / CF_BROWSER_RUN_TOKEN");let y=J(o.data.url,o,i,t,{callerTag:"crawlNodeRunner",serializeNonStrings:!0,sessionEnv:e}),l=Xt(o.data,y),m=K(o.data.url);d=`crawl:${c(new URL(y).host)}`;let N=`crawl:pending:${await qt(l)}`,R=(a=e.ctx)==null?void 0:a.storage,h=await(R==null?void 0:R.get(N)),T=h&&typeof h.jobId=="string"&&h.jobId&&Number.isFinite(h.createdAt)&&Date.now()-h.createdAt>=0&&Date.now()-h.createdAt<jo;h&&!T&&await(R==null?void 0:R.delete(N)),t==null||t({type:"info:crawlNodeRunner:request",content:{nodeId:o.id,url:m?c(G(y)):y,resumeJobId:T?h.jobId:void 0}}),{result:n}=await Kt({accountId:r.CF_ACCOUNT_ID,apiToken:r.CF_BROWSER_RUN_TOKEN},o.data,{url:y,...T?{resumeJobId:h.jobId}:{}}),n.error==="timeout"&&((w=n.data)!=null&&w.jobId)?await(R==null?void 0:R.put(N,{jobId:n.data.jobId,createdAt:T?h.createdAt:Date.now()})):n.data&&n.data.status!=="running"&&await(R==null?void 0:R.delete(N))}catch(r){n={ok:!1,data:null,error:r instanceof Error?r.message:String(r)},t==null||t({type:"error:crawlNodeRunner",content:c(`Crawl node execution failed: ${n.error}`)})}finally{let r=Date.now()-f;p==null||p({type:"tool_call",payload:{nodeId:o.id,url:d,method:"EXECUTE",status:n.ok?200:502,latencyMs:r}});let y=co(c(n.data));t==null||t({type:"info:crawlNodeRunner:response",content:{nodeId:o.id,ok:n.ok,latencyMs:r,data:y.value,truncated:y.truncated,error:c(n.error),outVars:co(c(Q(o,n))).value}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:n.ok?"success":"error",error:c(n.error)??void 0}}),s==null||s(o.id,n)}}function lo(){let e={};return{add(o,i){e[o]=i},hasOutputs(){return Object.keys(e).length>0},answerNodeIds(){return Object.keys(e)},snapshotData(){let o=Object.entries(e);return o.length===1?o[0][1]:Object.fromEntries(o)}}}function Uo(e){return!!(e!=null&&e.HX_ORA_URL)&&!!(e!=null&&e.HX_API_KEY)}async function Ve(e,o){if(!Uo(e))throw new Error("Structured outputs require HX_ORA_URL and HX_API_KEY");let i=await fetch(`${e.HX_ORA_URL}/internal/outputs/${encodeURIComponent(o.flowId)}/${encodeURIComponent(o.sessionId)}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:e.HX_API_KEY},body:JSON.stringify({runId:o.runId,createdAt:o.createdAt,data:o.data,answerNodeIds:o.answerNodeIds})});if(!i.ok){let t=await i.text().catch(()=>"");throw new Error(`Structured output persistence failed with ${i.status}${t?`: ${t}`:""}`)}}var uo=3,po=10,Vo=new Set(["agent:start","agent:complete","agent:telemetry"]);function Lo(e){let o=e.executedNodes||[];return o.length===0?"(none)":o.map(i=>i.label?`${i.id} (${i.label})`:i.id).join(" \u2192 ")}function Wo(e){let o=e.executedNodes||[];return o[o.length-1]}function X(e,o,i){throw e==null||e({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:i.message}}),i}function Ho(e,o){var u,p,n,f,d,c,g;let i=Array.isArray((u=e.data)==null?void 0:u.inputs)?e.data.inputs:[],t=((n=(p=o.flowData)==null?void 0:p.state)==null?void 0:n.nodes)||[],s={};for(let a of i){let w=(f=a.key)==null?void 0:f.trim();if(!w)continue;let r=(d=a.from)==null?void 0:d.trim();if(!r){if(a.default===void 0)continue;s[w]=a.default;continue}let y=W(r,{context:o.context||{},results:o.results||{},nodes:t,edges:((g=(c=o.flowData)==null?void 0:c.state)==null?void 0:g.edges)??[],currentNodeId:e.id}),l=y.value;if(y.missing||l===void 0||l===null){if(a.default===void 0)throw new P(y.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Worker node ${e.id} could not resolve input "${r}"`);l=a.default}s[w]=l}return s}async function mt(e,o,i,t,s,u,p){var C,F,x,D,M,V;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=typeof((C=o.data)==null?void 0:C.flowId)=="string"?o.data.flowId.trim():"";n||X(t,o,new Error(`Worker node ${o.id} is missing flowId`));let f=(F=i.flowData)==null?void 0:F.flowId,d=e.workerStack??(f?[f]:[]);d.includes(n)&&X(t,o,new Error(`Worker node ${o.id} cannot call ${n}: cycle detected (${[...d,n].join(" \u2192 ")})`)),d.length>=uo&&X(t,o,new Error(`Worker node ${o.id} exceeded max nesting depth (${uo})`));let c=e.workerCalls??{count:0};e.workerCalls=c,c.count>=po&&X(t,o,new Error(`Worker node ${o.id} exceeded max worker calls per run (${po})`)),c.count+=1;let g;try{g=Ho(o,i)}catch(I){X(t,o,I instanceof Error?I:new Error(String(I)));return}let a=e.env;a||X(t,o,new Error(`Worker node ${o.id} is missing runtime env`));let w,r;try{let I=await At(n,a);r=(x=I==null?void 0:I.metadata)==null?void 0:x.tenant,w=await _t(n,a)}catch(I){X(t,o,new Error(`Worker node ${o.id} could not load worker ${n}: ${I instanceof Error?I.message:String(I)}`))}let y=(D=i.flowData)==null?void 0:D.tenant;(!r||r!==y)&&X(t,o,new Error(`Worker ${n} belongs to a different tenant`));let l=lo(),m={flowData:{...w,tenant:r,flowId:n,chatId:((M=i.flowData)==null?void 0:M.chatId)||""},executedNodes:[],context:{},results:{}},N={env:a,ctx:e.ctx,secrets:e.secrets,userAuth:e.userAuth,user:e.user,toolDefs:e.toolDefs,composioSessions:e.composioSessions,skillRefCache:e.skillRefCache,publicOrigin:e.publicOrigin,getOraModel:e.getOraModel,runId:e.runId,shouldStop:e.shouldStop,workerCalls:c,conn:void 0,getMessages:async()=>[],setMessages:async()=>{},agentMemory:"",outputCollector:l,workerStack:[...d,n]},R,h={onChangeState:()=>{},onServerEvent:I=>{var q;Vo.has(I.type)||t==null||t({type:"worker:node",content:{workerNodeId:o.id,childNodeId:(q=I.content)==null?void 0:q.nodeId,event:I}})},onTelemetry:I=>p==null?void 0:p(I),onError:I=>{R=I},shouldStop:e.shouldStop},{startEngine:T,FlowExecutionStoppedError:k}=await import("./FlowEngine-WCL63TST.js"),_=await T(N,m,h)({text:"",inputs:g});if((_.status==="stopped"||await((V=e.shouldStop)==null?void 0:V.call(e)))&&X(t,o,new k),_.status!=="completed"){let I=Wo(m),q=Lo(m),U=_.error||R||"unknown error",j=I?` at node ${I.label?`${I.id} (${I.label})`:I.id}`:"";X(t,o,new Error(`Worker ${n} failed${j}: ${U}. Path: ${q}`))}l.hasOutputs()||X(t,o,new Error(`El worker ${n} complet\xF3 sin output estructurado. Agreg\xE1 un mapeo de salida en su nodo Answer.`));let b=(m.executedNodes||[]).map(I=>I.id);s==null||s(o.id,{ok:!0,data:l.snapshotData(),error:null,executed:b}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}import{generateObject as Zo}from"ai";import{z as fo}from"zod";import{openai as Jo}from"@ai-sdk/openai";import{extractReasoningMiddleware as Xo,wrapLanguageModel as qo}from"ai";import{createWorkersAI as Ko}from"workers-ai-provider";import{xai as Bo}from"@ai-sdk/xai";import{anthropic as zo}from"@ai-sdk/anthropic";import{createOpenRouter as Go}from"@openrouter/ai-sdk-provider";var gt={};function yt(e){if(e!=null){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}}function Yo(e){return{...e,defaultParams:yt(e.defaultParams)??e.defaultParams,capabilities:yt(e.capabilities)??e.capabilities,price:yt(e.price)??e.price}}async function et(e,o,i){var c,g;if(!(o!=null&&o.getOraModel))throw new Error("resolveModelById requires a sessionEnv with getOraModel capable of fetching models dynamically.");let t=await o.getOraModel(e);if(!t)return;let s=Yo(t),u=((c=s.capabilities)==null?void 0:c.params)??Bt(s),{effectiveParams:p,adjustments:n}=Gt(s.defaultParams,i,u),f;if(gt[s.provider])f=await gt[s.provider](s,o,i);else if(s.provider==="openai")f=Jo(s.providerModel);else if(s.provider==="xai")f=Bo(s.providerModel);else if(s.provider==="anthropic")f=zo(s.providerModel);else if(s.provider==="openrouter")f=Go()(s.providerModel);else if(s.provider==="workersai"||s.provider==="cloudflare"){if(!((g=o==null?void 0:o.env)!=null&&g.AI))throw new Error("Workers AI provider requires sessionEnv.env.AI binding");f=Ko({binding:o.env.AI})(s.providerModel)}else f={provider:s.provider,providerModel:s.providerModel};let d=Zt(s);return d.kind==="tag"&&f&&typeof f=="object"&&"specificationVersion"in f&&(f=qo({model:f,middleware:Xo({tagName:d.tagName??"think",startWithReasoning:d.startWithReasoning??!1})})),{provider:s.provider,modelHandle:f,entry:s,effectiveParams:p,paramAdjustments:n.length>0?n:void 0,reasoning:d}}function Ee(e,o){gt[e]=o}async function wt(e,o,i,t,s,u,p){var r,y,l,m,N,R,h;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=String(((r=o==null?void 0:o.data)==null?void 0:r.input_variable)||"user_input").trim(),f;try{let T=W(n,{context:i.context??{},results:i.results??{},nodes:((l=(y=i.flowData)==null?void 0:y.state)==null?void 0:l.nodes)??[],edges:((N=(m=i.flowData)==null?void 0:m.state)==null?void 0:N.edges)??[],currentNodeId:o.id});if(T.missing)throw new Error(`Classifier input "${n}" did not produce a value`);f=T.value}catch(T){throw t==null||t({type:"error:classifier",content:String(T)}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(T)}}),T}let d=Array.isArray((R=o==null?void 0:o.data)==null?void 0:R.items)?o.data.items:[];if(d.length===0){t==null||t({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let c=String((h=d[d.length-1])==null?void 0:h.id);if(!f||String(f).trim().length===0){t==null||t({type:"warning:classifier",content:"No input for classification \u2014 falling back to last item."}),s==null||s(o.id,{classification:c}),i.context=i.context||{},i.context.classified_id=c,u==null||u(i);return}let a=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
2
2
  If the message is ambiguous or none clearly matches, choose the LAST category in the list.
3
3
 
4
4
  Categories:
@@ -11,7 +11,7 @@ ${d.map(T=>{let k=T.keywords??T["keywords/topics"]??"",_=Array.isArray(k)?k.join
11
11
 
12
12
  Select the best matching category id.`;try{let T=Date.now(),k=d.map(V=>String(V.id)),_="gpt_4_1_mini",b=await et(_,e);if(!b)throw new Error(`Model '${_}' not found in registry`);let{modelHandle:C,effectiveParams:F}=b,x=await Zo({model:C,messages:[{role:"system",content:a},{role:"user",content:w}],schema:fo.object({classification:fo.enum(k).describe("The id of the best matching category")}),temperature:F.temperature??0}),D=Date.now()-T,M=x.object.classification;p==null||p({type:"class_telemetry",payload:{nodeId:o.id,totalLatency:D,model:x.response.modelId,usage:x.usage,options:k}}),p==null||p({type:"class_result",payload:{result:x}}),s==null||s(o.id,{classification:M}),i.context=i.context||{},i.context.classified_id=M,u==null||u(i),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}catch(T){throw t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(T)}}),T}}import{stepCountIs as vo,streamText as te}from"ai";import{nanoid as oe}from"nanoid";import"zod";function mo(e,o){var n,f,d,c,g;let i=((n=e.data)==null?void 0:n.attachments)??[];if(!Array.isArray(i))throw new P("INVALID_EXPRESSION",`Node ${e.id} attachments must be an array`);let t=((d=(f=o.flowData)==null?void 0:f.state)==null?void 0:d.nodes)??[],s=((g=(c=o.flowData)==null?void 0:c.state)==null?void 0:g.edges)??[],u=Z(t,s,e.id),p="";for(let a of i){if(typeof a!="string")throw new P("INVALID_EXPRESSION",`Node ${e.id} has an invalid attachment reference`);let w=u.find(y=>y.ref===a);if(!w)throw new P("OUT_OF_SCOPE",`Attachment "${a}" is not in this node's connection scope`);if(w.type!=="file"&&w.type!=="image")throw new P("UNKNOWN_OUTPUT",`Attachment "${a}" is not an image or file output`);if(w.type!=="file")continue;let r=W(a,{context:o.context??{},results:o.results??{},nodes:t,edges:s,currentNodeId:e.id});if(r.missing)throw new P(r.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${a}" did not produce a value`);if(typeof r.value!="string")throw new P("PATH_NOT_FOUND",`Attachment "${a}" must resolve to file text`);r.value.trim()&&(p+=(p?`
13
13
 
14
- `:"")+r.value)}return p}function Qo(e,o){var s,u,p,n,f;let i=((s=e.data)==null?void 0:s.attachments)??[];if(!Array.isArray(i))throw new P("INVALID_EXPRESSION",`Node ${e.id} attachments must be an array`);let t=Z(((p=(u=o.flowData)==null?void 0:u.state)==null?void 0:p.nodes)??[],((f=(n=o.flowData)==null?void 0:n.state)==null?void 0:f.edges)??[],e.id);return i.map(d=>{if(typeof d!="string")throw new P("INVALID_EXPRESSION",`Node ${e.id} has an invalid attachment reference`);let c=t.find(g=>g.ref===d);if(!c)throw new P("OUT_OF_SCOPE",`Attachment "${d}" is not in this node's connection scope`);if(c.type!=="image"&&c.type!=="file")throw new P("UNKNOWN_OUTPUT",`Attachment "${d}" is not a binary output`);return c.type==="image"?d:null}).filter(d=>d!==null)}function yo(e,o){var s,u,p,n;let i=[],t={context:o.context??{},results:o.results??{},nodes:((u=(s=o.flowData)==null?void 0:s.state)==null?void 0:u.nodes)??[],edges:((n=(p=o.flowData)==null?void 0:p.state)==null?void 0:n.edges)??[],currentNodeId:e.id};for(let f of Qo(e,o)){let d=W(f,t);if(d.missing)throw new P(d.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${f}" did not produce a value`);if(!Array.isArray(d.value))throw new P("PATH_NOT_FOUND",`Attachment "${f}" must resolve to an image array`);i.push(...d.value)}return i}var z=(e,o,i)=>{e.send(o+"::"+i)};var Eo=E({"../tools/composioDirectTool.ts":()=>import("./composioDirectTool-XOKIM5FJ.js"),"../tools/composioTool.ts":()=>import("./composioTool-C4KZMI4Q.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-RT5CTG4O.js"),"../tools/skillTool.ts":()=>import("./skillTool-JEAL3G33.js"),"../tools/tempTool.ts":()=>import("./tempTool-2RXAF56M.js"),"../tools/twitter.ts":()=>import("./twitter-OMDEG7T2.js"),"../tools/vectorize.ts":()=>import("./vectorize-CDB26DMD.js")});var So=E({});async function ee(e,o,i,t){var g;let s=Array.isArray((g=i==null?void 0:i.data)==null?void 0:g.tools)?i.data.tools:[];if(s.length===0)return{};let u={},p=a=>{var R,h;let w=typeof(a==null?void 0:a.description)=="string"?a.description:"",r=a==null?void 0:a.inputSchema,y;try{let T=(r==null?void 0:r.shape)??(typeof((R=r==null?void 0:r._def)==null?void 0:R.shape)=="function"?r._def.shape():(h=r==null?void 0:r._def)==null?void 0:h.shape);T&&typeof T=="object"&&(y=T)}catch{}let l=y?Object.keys(y):[],m=w?`description="${w.length>120?w.slice(0,120)+"\u2026":w}"`:"description=(none)",N=l.length?`inputSchema={${l.join(", ")}}`:"inputSchema=(none)";return`${m} ${N}`},n=(()=>{let a=[],w=[],r=[],y=[];for(let m=0;m<s.length;m++){let N=s[m];!N||typeof N!="object"||typeof N.id!="string"?y.push(m):N.kind==="builtin"?a.push(N.id):N.kind==="skill"?r.push(N.id):N.kind==="http"||N.kind==="mcp"||N.kind==="composio"?w.push(N.id):y.push(m)}let l=[];return a.length&&l.push(`builtin[${a.join(", ")}]`),w.length&&l.push(`custom[${w.join(", ")}]`),r.length&&l.push(`skill[${r.join(", ")}]`),y.length&&l.push(`invalid@[${y.join(", ")}]`),l.join(" ")||"(none)"})();console.log(`[tools] node ${i.id} requested (${s.length}): ${n}`);let f=!1,d=async()=>{if(f&&e.toolDefs)return e.toolDefs;if(!e.env)return e.toolDefs=e.toolDefs||{},f=!0,e.toolDefs;try{let a=await v(e.env),w={};for(let r of a)r&&r.id&&(w[r.id]=r);e.toolDefs=w}catch(a){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(a)}`}),e.toolDefs=e.toolDefs||{}}return f=!0,e.toolDefs},c=[];for(let a=0;a<s.length;a++){let w=s[a];if(!w||typeof w!="object"||typeof w.id!="string"||w.kind!=="builtin"&&w.kind!=="http"&&w.kind!=="mcp"&&w.kind!=="composio"&&w.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${a}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let r=w;if(r.kind!=="builtin"){let l=(await d())[r.id];if(!l){console.error(`[tools] \u2717 custom '${r.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${r.id}' not found for this tenant`});continue}if(r.kind==="composio"){try{let N=await to(l,e,o,t),R=Object.keys(N);for(let[h,T]of Object.entries(N))u[h]=T;console.log(`[tools] \u2713 composio '${r.id}' \u2192 ${R.length} tool(s)`)}catch(N){console.error(`[tools] \u2717 composio '${r.id}': ${String(N)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${r.id}': ${String(N)}`})}continue}if(r.kind==="skill"){if(l.kind!=="skill"){console.error(`[tools] \u2717 skill '${r.id}': row is of kind '${l.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${r.id}' is not a skill`});continue}let N=l.name;if(u[N]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${N}' \u2014 builtin/other already registered, skipping skill '${r.id}'`});continue}try{u[N]=oo(l,e,o,t),c.push(l);let R=typeof l.execution=="string"?JSON.parse(l.execution):l.execution||{},h=Array.isArray(R.references)?R.references.map(T=>T==null?void 0:T.name):[];console.log(`[tools] \u2713 skill '${r.id}' \u2192 '${N}' (refs: ${h.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:N,refCount:h.length,refs:h}})}catch(R){console.error(`[tools] \u2717 skill '${r.id}': ${String(R)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${r.id}': ${String(R)}`})}continue}let m=l.name;if(u[m]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${m}' \u2014 builtin already registered, skipping custom tool '${r.id}'`});continue}try{let N=tt(l,e,o,t);u[m]=N,console.log(`[tools] \u2713 custom '${r.id}' \u2192 '${m}'`),console.log(`[tools] ${p(u[m])}`)}catch(N){console.error(`[tools] \u2717 custom '${r.id}': ${String(N)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${r.id}': ${String(N)}`})}continue}if(!vt[r.id]){console.error(`[tools] \u2717 builtin '${r.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${r.id}' not found in registry`});continue}try{let y;try{y=await Eo(`../tools/${r.id}.ts`)}catch{y=await So(`../tools/${r.id}.js`)}let l;if(y[r.id])l=y[r.id];else if(y.default)l=y.default;else if(y.create)l=y.create;else{let _=Object.values(y);_.length>0&&(l=_[0])}if(!l){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${r.id}'`});continue}let m,N,R={};if(r.params&&typeof r.params=="object"){if(typeof r.params.description=="string"?m=r.params.description:r.params.description!==void 0&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${r.id}' \u2014 must be a string`})),r.params.inputSchema!==void 0){let _=r.params.inputSchema;typeof _=="object"&&(typeof _.safeParse=="function"||_._def)?N=_:typeof _=="object"&&_!==null&&_.type==="object"&&_.properties?(N=Ht(_),N||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${r.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${r.id}' \u2014 must be a Zod schema or JSON Schema object`})}r.params.defaults!==void 0?typeof r.params.defaults=="object"&&r.params.defaults!==null&&!Array.isArray(r.params.defaults)?R=r.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${r.id}' \u2014 must be an object`}),R={}):r.params.source!==void 0||r.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${r.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),R={}):R={}}let h=l(e,o,R,t);m&&h&&typeof h=="object"&&(h.description=m),N&&h&&typeof h=="object"&&(h.inputSchema=N),u[r.id]=h;let T=[];m&&T.push("description"),N&&T.push("inputSchema"),Object.keys(R).length&&T.push(`defaults(${Object.keys(R).join(",")})`);let k=T.length?` [overrides: ${T.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${r.id}'${k}`),console.log(`[tools] ${p(h)}`)}catch(y){console.error(`[tools] \u2717 builtin '${r.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${r.id}': ${String(y)}`});continue}}if(c.length>0)if(u.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{u.readSkillRef=eo(e,c,o,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${c.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:c.map(a=>a.name)}})}catch(a){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(a)}`)}return u}async function ht(e,o,i,t,s,u,p){var _,b,C,F;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=!1;try{let x=(_=i.flowData)==null?void 0:_.state;if(x&&x.edges&&x.nodes){let D=x.edges.filter(M=>M.source===o.id);if(D.length>0){let M=x.nodes.find(V=>V.id===D[0].target);M&&M.type==="answerNode"&&(n=!0)}}}catch(x){console.error("Error determining next node for streaming:",x)}let f=J(o.data.template,o,i,t,{sessionEnv:e});(!f||!f.trim())&&(f="Answer straight forward to the user, dont offer any other option to continue");let d=f,c=J(o.data.user_template||"",o,i,t,{sessionEnv:e}),g=x=>x&&Object.fromEntries(Object.keys(x).map(D=>[D,"[redacted]"])),a=e!=null&&e.secrets||e!=null&&e.userAuth?{...e,secrets:g(e.secrets),userAuth:g(e.userAuth)}:e,w=J(o.data.template,o,i,void 0,{sessionEnv:a})||d,r=J(o.data.user_template||"",o,i,void 0,{sessionEnv:a});t==null||t({type:`info:llmNodeRunner:${o.id}`,content:w}),t==null||t({type:`info:llmNodeRunner:${o.id}`,content:r});let y=(b=o==null?void 0:o.data)==null?void 0:b.window_size,l=Number(y);(!Number.isInteger(l)||l<=0)&&(l=5);let m=yo(o,i),N=mo(o,i);t==null||t({type:"info:llmNodeRunner:attachments",content:{nodeId:o.id,refs:Array.isArray((C=o.data)==null?void 0:C.attachments)?o.data.attachments:[],images:m.length,documents:N?1:0}});let h=(await((F=e.getMessages)==null?void 0:F.call(e))??[]).slice(-l),T=h.filter(x=>x&&typeof x.role=="string"&&typeof x.content=="string");T.length!==h.length&&console.warn(`Filtered ${h.length-T.length} invalid messages from history`);let k=se(T,c,m,N);await ie(f,k,e.conn,t,o,n,s,i,u,e,p)}async function ie(e,o,i,t,s,u,p,n,f,d,c){var a;let g=Date.now();if(!((a=d.env)!=null&&a.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(w,r)=>{var D,M,V,I,q,U;let y,l={},m,N="none",R=!1,h,T=!1,k=!1,_=0,b=0,C=(D=s==null?void 0:s.data)==null?void 0:D.sendReasoning,F=C!==!1;try{let j=(M=s==null?void 0:s.data)==null?void 0:M.model,Y=Array.isArray(j)?j[0]:j||"gpt_5_nano",A=zt(s==null?void 0:s.data),O=await et(Y,d,A);if(!O)throw new Error(`Model '${Y}' not found in registry`);y=O.modelHandle,l=O.effectiveParams||{},N=O.reasoning.kind;let $=Et(O.reasoning,(V=s==null?void 0:s.data)==null?void 0:V.reasoningEffort);R=F&&Qt(O.reasoning);let H=typeof((I=s==null?void 0:s.data)==null?void 0:I.reasoningMaxTokens)=="number"?s.data.reasoningMaxTokens:void 0;m=St(O.provider,{effort:$,exposeReasoning:R,maxTokens:H}),$&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:$})),console.log(`[reasoning] ${JSON.stringify({model:Y,provider:O.provider,capability:O.reasoning,requestedEffort:((q=s==null?void 0:s.data)==null?void 0:q.reasoningEffort)??null,resolvedEffort:$??null,sendReasoning:F,exposeReasoning:R,providerOptions:m??null},null,2)}`);for(let L of O.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:L});t==null||t({type:"info:llmNodeRunner:model",content:Y}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(U=s==null?void 0:s.data)!=null&&U.generationPreset?{preset:s.data.generationPreset}:{},...l,...N!=="none"?{reasoning:N,configuredSendReasoning:C,sendReasoning:F,exposeReasoning:R,...$?{effort:$}:{}}:{}}})}catch(j){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(j)}`}),j}let x=await ee(d,n,s,t);console.log(`[tools] node ${s.id} loaded ${Object.keys(x).length}: ${Object.keys(x).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:s.id,tools:Object.keys(x)}});try{let j=te({model:y,system:e,messages:o,stopWhen:(()=>{var L;let O=!!x.readSkillRef?10:5,$=Number(((L=s.data)==null?void 0:L.max_steps)??O),H=Number.isFinite($)?Math.max(1,Math.min(30,$)):O;return vo(H)})(),...Yt(l),...m?{providerOptions:m}:{},tools:x,onFinish:async A=>{var xt,Tt;let O=A.text||"",$=A.reasoningText??((xt=A.reasoning)==null?void 0:xt.text)??"";if(console.log(`[reasoning] done: deltas=${_} chars=${b} result.reasoningText=${$.length} finishReason=${A.finishReason??"n/a"} reasoningTokens=${((Tt=A.usage)==null?void 0:Tt.reasoningTokens)??"n/a"}`),F&&R&&!T&&$&&i){T=!0;try{z(i,B.SERVER_REASONING_STREAM,$)}catch(ho){console.warn("Failed to send finished reasoning over connection",ho)}}let H={id:oe(),role:"assistant",type:"text",content:O,ts:Date.now()};u&&(d.setMessages?await d.setMessages(H):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),i&&F&&T&&!k&&(k=!0,z(i,B.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),u&&i&&z(i,B.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),p==null||p((s==null?void 0:s.id)||"llm_result",O),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(A)});let L=Date.now()-g,wo=h?h-g:void 0;c==null||c({type:"llm_telemetry",payload:{nodeId:s.id,totalLatency:L,timeToFirstToken:wo,model:A.response.modelId,usage:A.usage}}),c==null||c({type:"llm_result",payload:{result:A}})},onStepFinish:async A=>{let O=($,H=200)=>{let L=typeof $=="string"?$:JSON.stringify($);return L?L.length>H?`${L.slice(0,H)}\u2026(+${L.length-H})`:L:""};if(A.toolCalls&&A.toolCalls.length>0){for(let $ of A.toolCalls)console.log(`[tools] \u2192 ${$.toolName}(${O($.args??$.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${s.id}`,content:JSON.stringify(A.toolCalls)})}if(A.toolResults&&A.toolResults.length>0){for(let $ of A.toolResults)console.log(`[tools] \u2190 ${$.toolName} \u2192 ${O($.result??$.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${s.id}`,content:JSON.stringify(A.toolResults)})}},experimental_onToolCallStart:A=>{var O;t==null||t({type:"tool:execution",content:{nodeId:s.id,toolName:(O=A==null?void 0:A.toolCall)==null?void 0:O.toolName,status:"start"}})},experimental_onToolCallFinish:A=>{var O,$;t==null||t({type:"tool:execution",content:{nodeId:s.id,toolName:(O=A==null?void 0:A.toolCall)==null?void 0:O.toolName,status:(($=A==null?void 0:A.toolOutput)==null?void 0:$.type)==="tool-error"?"error":"success"}})},onError:A=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),r(A)},onChunk:A=>{if(A.chunk.type==="reasoning-delta"){let $=A.chunk.text??A.chunk.delta??"";if($&&(T=!0,_+=1,b+=$.length,_===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),F&&i&&$)try{z(i,B.SERVER_REASONING_STREAM,$)}catch(H){console.warn("Failed to send reasoning chunk over connection",H)}return}if(A.chunk.type==="text-delta"){if(h||(h=Date.now()),i&&F&&T&&!k){k=!0;try{z(i,B.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch($){console.warn("Failed to send reasoning complete over connection",$)}}return}c==null||c({type:A.chunk.type,payload:{nodeId:s.id,chunk:A.chunk}});let O=`llm_chunk:${A.chunk.type}`;t==null||t({type:O,content:{...A}})}}),Y=async()=>{let A="";for await(let O of j.fullStream)if(O.type==="text-delta"){if(A+=O.text,u&&i)try{z(i,B.SERVER_TEXT_STREAM,O.text)}catch($){console.warn("Failed to send chunk over connection",$)}}else if(O.type==="finish-step"&&O.finishReason==="tool-calls"){if(u&&i&&A.trim())try{z(i,B.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch($){console.warn("Failed to flush text segment over connection",$)}A=""}};await Promise.all([j,Y()]),w(),t==null||t({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"success"}})}catch(j){t==null||t({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"error",error:String(j)}}),r(j)}})}function se(e,o,i,t){let s=!!(i&&i.length>0),u=!!t,p=s||u,f=e.length>0&&e[e.length-1].role==="user"?e[e.length-1]:void 0,d=c=>{let g=[],a="";if(u&&(a+=`[Attached files]
14
+ `:"")+r.value)}return p}function Qo(e,o){var s,u,p,n,f;let i=((s=e.data)==null?void 0:s.attachments)??[];if(!Array.isArray(i))throw new P("INVALID_EXPRESSION",`Node ${e.id} attachments must be an array`);let t=Z(((p=(u=o.flowData)==null?void 0:u.state)==null?void 0:p.nodes)??[],((f=(n=o.flowData)==null?void 0:n.state)==null?void 0:f.edges)??[],e.id);return i.map(d=>{if(typeof d!="string")throw new P("INVALID_EXPRESSION",`Node ${e.id} has an invalid attachment reference`);let c=t.find(g=>g.ref===d);if(!c)throw new P("OUT_OF_SCOPE",`Attachment "${d}" is not in this node's connection scope`);if(c.type!=="image"&&c.type!=="file")throw new P("UNKNOWN_OUTPUT",`Attachment "${d}" is not a binary output`);return c.type==="image"?d:null}).filter(d=>d!==null)}function yo(e,o){var s,u,p,n;let i=[],t={context:o.context??{},results:o.results??{},nodes:((u=(s=o.flowData)==null?void 0:s.state)==null?void 0:u.nodes)??[],edges:((n=(p=o.flowData)==null?void 0:p.state)==null?void 0:n.edges)??[],currentNodeId:e.id};for(let f of Qo(e,o)){let d=W(f,t);if(d.missing)throw new P(d.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${f}" did not produce a value`);if(!Array.isArray(d.value))throw new P("PATH_NOT_FOUND",`Attachment "${f}" must resolve to an image array`);i.push(...d.value)}return i}var z=(e,o,i)=>{e.send(o+"::"+i)};var Eo=E({"../tools/composioDirectTool.d.ts":()=>import("./composioDirectTool.d-YTSP3KYC.js"),"../tools/composioDirectTool.ts":()=>import("./composioDirectTool-XOKIM5FJ.js"),"../tools/composioTool.d.ts":()=>import("./composioTool.d-JTYAYXZ3.js"),"../tools/composioTool.ts":()=>import("./composioTool-C4KZMI4Q.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.d.ts":()=>import("./httpTool.d-USBSKQA6.js"),"../tools/httpTool.ts":()=>import("./httpTool-RT5CTG4O.js"),"../tools/skillTool.d.ts":()=>import("./skillTool.d-DIKTOKS5.js"),"../tools/skillTool.ts":()=>import("./skillTool-JEAL3G33.js"),"../tools/tempTool.ts":()=>import("./tempTool-2RXAF56M.js"),"../tools/twitter.ts":()=>import("./twitter-OMDEG7T2.js"),"../tools/vectorize.ts":()=>import("./vectorize-CDB26DMD.js")});var So=E({});async function ee(e,o,i,t){var g;let s=Array.isArray((g=i==null?void 0:i.data)==null?void 0:g.tools)?i.data.tools:[];if(s.length===0)return{};let u={},p=a=>{var R,h;let w=typeof(a==null?void 0:a.description)=="string"?a.description:"",r=a==null?void 0:a.inputSchema,y;try{let T=(r==null?void 0:r.shape)??(typeof((R=r==null?void 0:r._def)==null?void 0:R.shape)=="function"?r._def.shape():(h=r==null?void 0:r._def)==null?void 0:h.shape);T&&typeof T=="object"&&(y=T)}catch{}let l=y?Object.keys(y):[],m=w?`description="${w.length>120?w.slice(0,120)+"\u2026":w}"`:"description=(none)",N=l.length?`inputSchema={${l.join(", ")}}`:"inputSchema=(none)";return`${m} ${N}`},n=(()=>{let a=[],w=[],r=[],y=[];for(let m=0;m<s.length;m++){let N=s[m];!N||typeof N!="object"||typeof N.id!="string"?y.push(m):N.kind==="builtin"?a.push(N.id):N.kind==="skill"?r.push(N.id):N.kind==="http"||N.kind==="mcp"||N.kind==="composio"?w.push(N.id):y.push(m)}let l=[];return a.length&&l.push(`builtin[${a.join(", ")}]`),w.length&&l.push(`custom[${w.join(", ")}]`),r.length&&l.push(`skill[${r.join(", ")}]`),y.length&&l.push(`invalid@[${y.join(", ")}]`),l.join(" ")||"(none)"})();console.log(`[tools] node ${i.id} requested (${s.length}): ${n}`);let f=!1,d=async()=>{if(f&&e.toolDefs)return e.toolDefs;if(!e.env)return e.toolDefs=e.toolDefs||{},f=!0,e.toolDefs;try{let a=await v(e.env),w={};for(let r of a)r&&r.id&&(w[r.id]=r);e.toolDefs=w}catch(a){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(a)}`}),e.toolDefs=e.toolDefs||{}}return f=!0,e.toolDefs},c=[];for(let a=0;a<s.length;a++){let w=s[a];if(!w||typeof w!="object"||typeof w.id!="string"||w.kind!=="builtin"&&w.kind!=="http"&&w.kind!=="mcp"&&w.kind!=="composio"&&w.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${a}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let r=w;if(r.kind!=="builtin"){let l=(await d())[r.id];if(!l){console.error(`[tools] \u2717 custom '${r.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${r.id}' not found for this tenant`});continue}if(r.kind==="composio"){try{let N=await to(l,e,o,t),R=Object.keys(N);for(let[h,T]of Object.entries(N))u[h]=T;console.log(`[tools] \u2713 composio '${r.id}' \u2192 ${R.length} tool(s)`)}catch(N){console.error(`[tools] \u2717 composio '${r.id}': ${String(N)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${r.id}': ${String(N)}`})}continue}if(r.kind==="skill"){if(l.kind!=="skill"){console.error(`[tools] \u2717 skill '${r.id}': row is of kind '${l.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${r.id}' is not a skill`});continue}let N=l.name;if(u[N]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${N}' \u2014 builtin/other already registered, skipping skill '${r.id}'`});continue}try{u[N]=oo(l,e,o,t),c.push(l);let R=typeof l.execution=="string"?JSON.parse(l.execution):l.execution||{},h=Array.isArray(R.references)?R.references.map(T=>T==null?void 0:T.name):[];console.log(`[tools] \u2713 skill '${r.id}' \u2192 '${N}' (refs: ${h.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:N,refCount:h.length,refs:h}})}catch(R){console.error(`[tools] \u2717 skill '${r.id}': ${String(R)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${r.id}': ${String(R)}`})}continue}let m=l.name;if(u[m]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${m}' \u2014 builtin already registered, skipping custom tool '${r.id}'`});continue}try{let N=tt(l,e,o,t);u[m]=N,console.log(`[tools] \u2713 custom '${r.id}' \u2192 '${m}'`),console.log(`[tools] ${p(u[m])}`)}catch(N){console.error(`[tools] \u2717 custom '${r.id}': ${String(N)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${r.id}': ${String(N)}`})}continue}if(!vt[r.id]){console.error(`[tools] \u2717 builtin '${r.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${r.id}' not found in registry`});continue}try{let y;try{y=await Eo(`../tools/${r.id}.ts`)}catch{y=await So(`../tools/${r.id}.js`)}let l;if(y[r.id])l=y[r.id];else if(y.default)l=y.default;else if(y.create)l=y.create;else{let _=Object.values(y);_.length>0&&(l=_[0])}if(!l){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${r.id}'`});continue}let m,N,R={};if(r.params&&typeof r.params=="object"){if(typeof r.params.description=="string"?m=r.params.description:r.params.description!==void 0&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${r.id}' \u2014 must be a string`})),r.params.inputSchema!==void 0){let _=r.params.inputSchema;typeof _=="object"&&(typeof _.safeParse=="function"||_._def)?N=_:typeof _=="object"&&_!==null&&_.type==="object"&&_.properties?(N=Ht(_),N||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${r.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${r.id}' \u2014 must be a Zod schema or JSON Schema object`})}r.params.defaults!==void 0?typeof r.params.defaults=="object"&&r.params.defaults!==null&&!Array.isArray(r.params.defaults)?R=r.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${r.id}' \u2014 must be an object`}),R={}):r.params.source!==void 0||r.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${r.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),R={}):R={}}let h=l(e,o,R,t);m&&h&&typeof h=="object"&&(h.description=m),N&&h&&typeof h=="object"&&(h.inputSchema=N),u[r.id]=h;let T=[];m&&T.push("description"),N&&T.push("inputSchema"),Object.keys(R).length&&T.push(`defaults(${Object.keys(R).join(",")})`);let k=T.length?` [overrides: ${T.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${r.id}'${k}`),console.log(`[tools] ${p(h)}`)}catch(y){console.error(`[tools] \u2717 builtin '${r.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${r.id}': ${String(y)}`});continue}}if(c.length>0)if(u.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{u.readSkillRef=eo(e,c,o,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${c.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:c.map(a=>a.name)}})}catch(a){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(a)}`)}return u}async function ht(e,o,i,t,s,u,p){var _,b,C,F;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=!1;try{let x=(_=i.flowData)==null?void 0:_.state;if(x&&x.edges&&x.nodes){let D=x.edges.filter(M=>M.source===o.id);if(D.length>0){let M=x.nodes.find(V=>V.id===D[0].target);M&&M.type==="answerNode"&&(n=!0)}}}catch(x){console.error("Error determining next node for streaming:",x)}let f=J(o.data.template,o,i,t,{sessionEnv:e});(!f||!f.trim())&&(f="Answer straight forward to the user, dont offer any other option to continue");let d=f,c=J(o.data.user_template||"",o,i,t,{sessionEnv:e}),g=x=>x&&Object.fromEntries(Object.keys(x).map(D=>[D,"[redacted]"])),a=e!=null&&e.secrets||e!=null&&e.userAuth?{...e,secrets:g(e.secrets),userAuth:g(e.userAuth)}:e,w=J(o.data.template,o,i,void 0,{sessionEnv:a})||d,r=J(o.data.user_template||"",o,i,void 0,{sessionEnv:a});t==null||t({type:`info:llmNodeRunner:${o.id}`,content:w}),t==null||t({type:`info:llmNodeRunner:${o.id}`,content:r});let y=(b=o==null?void 0:o.data)==null?void 0:b.window_size,l=Number(y);(!Number.isInteger(l)||l<=0)&&(l=5);let m=yo(o,i),N=mo(o,i);t==null||t({type:"info:llmNodeRunner:attachments",content:{nodeId:o.id,refs:Array.isArray((C=o.data)==null?void 0:C.attachments)?o.data.attachments:[],images:m.length,documents:N?1:0}});let h=(await((F=e.getMessages)==null?void 0:F.call(e))??[]).slice(-l),T=h.filter(x=>x&&typeof x.role=="string"&&typeof x.content=="string");T.length!==h.length&&console.warn(`Filtered ${h.length-T.length} invalid messages from history`);let k=se(T,c,m,N);await ie(f,k,e.conn,t,o,n,s,i,u,e,p)}async function ie(e,o,i,t,s,u,p,n,f,d,c){var a;let g=Date.now();if(!((a=d.env)!=null&&a.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(w,r)=>{var D,M,V,I,q,U;let y,l={},m,N="none",R=!1,h,T=!1,k=!1,_=0,b=0,C=(D=s==null?void 0:s.data)==null?void 0:D.sendReasoning,F=C!==!1;try{let j=(M=s==null?void 0:s.data)==null?void 0:M.model,Y=Array.isArray(j)?j[0]:j||"gpt_5_nano",A=zt(s==null?void 0:s.data),O=await et(Y,d,A);if(!O)throw new Error(`Model '${Y}' not found in registry`);y=O.modelHandle,l=O.effectiveParams||{},N=O.reasoning.kind;let $=Et(O.reasoning,(V=s==null?void 0:s.data)==null?void 0:V.reasoningEffort);R=F&&Qt(O.reasoning);let H=typeof((I=s==null?void 0:s.data)==null?void 0:I.reasoningMaxTokens)=="number"?s.data.reasoningMaxTokens:void 0;m=St(O.provider,{effort:$,exposeReasoning:R,maxTokens:H}),$&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:$})),console.log(`[reasoning] ${JSON.stringify({model:Y,provider:O.provider,capability:O.reasoning,requestedEffort:((q=s==null?void 0:s.data)==null?void 0:q.reasoningEffort)??null,resolvedEffort:$??null,sendReasoning:F,exposeReasoning:R,providerOptions:m??null},null,2)}`);for(let L of O.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:L});t==null||t({type:"info:llmNodeRunner:model",content:Y}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(U=s==null?void 0:s.data)!=null&&U.generationPreset?{preset:s.data.generationPreset}:{},...l,...N!=="none"?{reasoning:N,configuredSendReasoning:C,sendReasoning:F,exposeReasoning:R,...$?{effort:$}:{}}:{}}})}catch(j){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(j)}`}),j}let x=await ee(d,n,s,t);console.log(`[tools] node ${s.id} loaded ${Object.keys(x).length}: ${Object.keys(x).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:s.id,tools:Object.keys(x)}});try{let j=te({model:y,system:e,messages:o,stopWhen:(()=>{var L;let O=!!x.readSkillRef?10:5,$=Number(((L=s.data)==null?void 0:L.max_steps)??O),H=Number.isFinite($)?Math.max(1,Math.min(30,$)):O;return vo(H)})(),...Yt(l),...m?{providerOptions:m}:{},tools:x,onFinish:async A=>{var xt,Tt;let O=A.text||"",$=A.reasoningText??((xt=A.reasoning)==null?void 0:xt.text)??"";if(console.log(`[reasoning] done: deltas=${_} chars=${b} result.reasoningText=${$.length} finishReason=${A.finishReason??"n/a"} reasoningTokens=${((Tt=A.usage)==null?void 0:Tt.reasoningTokens)??"n/a"}`),F&&R&&!T&&$&&i){T=!0;try{z(i,B.SERVER_REASONING_STREAM,$)}catch(ho){console.warn("Failed to send finished reasoning over connection",ho)}}let H={id:oe(),role:"assistant",type:"text",content:O,ts:Date.now()};u&&(d.setMessages?await d.setMessages(H):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),i&&F&&T&&!k&&(k=!0,z(i,B.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),u&&i&&z(i,B.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),p==null||p((s==null?void 0:s.id)||"llm_result",O),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(A)});let L=Date.now()-g,wo=h?h-g:void 0;c==null||c({type:"llm_telemetry",payload:{nodeId:s.id,totalLatency:L,timeToFirstToken:wo,model:A.response.modelId,usage:A.usage}}),c==null||c({type:"llm_result",payload:{result:A}})},onStepFinish:async A=>{let O=($,H=200)=>{let L=typeof $=="string"?$:JSON.stringify($);return L?L.length>H?`${L.slice(0,H)}\u2026(+${L.length-H})`:L:""};if(A.toolCalls&&A.toolCalls.length>0){for(let $ of A.toolCalls)console.log(`[tools] \u2192 ${$.toolName}(${O($.args??$.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${s.id}`,content:JSON.stringify(A.toolCalls)})}if(A.toolResults&&A.toolResults.length>0){for(let $ of A.toolResults)console.log(`[tools] \u2190 ${$.toolName} \u2192 ${O($.result??$.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${s.id}`,content:JSON.stringify(A.toolResults)})}},experimental_onToolCallStart:A=>{var O;t==null||t({type:"tool:execution",content:{nodeId:s.id,toolName:(O=A==null?void 0:A.toolCall)==null?void 0:O.toolName,status:"start"}})},experimental_onToolCallFinish:A=>{var O,$;t==null||t({type:"tool:execution",content:{nodeId:s.id,toolName:(O=A==null?void 0:A.toolCall)==null?void 0:O.toolName,status:(($=A==null?void 0:A.toolOutput)==null?void 0:$.type)==="tool-error"?"error":"success"}})},onError:A=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),r(A)},onChunk:A=>{if(A.chunk.type==="reasoning-delta"){let $=A.chunk.text??A.chunk.delta??"";if($&&(T=!0,_+=1,b+=$.length,_===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),F&&i&&$)try{z(i,B.SERVER_REASONING_STREAM,$)}catch(H){console.warn("Failed to send reasoning chunk over connection",H)}return}if(A.chunk.type==="text-delta"){if(h||(h=Date.now()),i&&F&&T&&!k){k=!0;try{z(i,B.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch($){console.warn("Failed to send reasoning complete over connection",$)}}return}c==null||c({type:A.chunk.type,payload:{nodeId:s.id,chunk:A.chunk}});let O=`llm_chunk:${A.chunk.type}`;t==null||t({type:O,content:{...A}})}}),Y=async()=>{let A="";for await(let O of j.fullStream)if(O.type==="text-delta"){if(A+=O.text,u&&i)try{z(i,B.SERVER_TEXT_STREAM,O.text)}catch($){console.warn("Failed to send chunk over connection",$)}}else if(O.type==="finish-step"&&O.finishReason==="tool-calls"){if(u&&i&&A.trim())try{z(i,B.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch($){console.warn("Failed to flush text segment over connection",$)}A=""}};await Promise.all([j,Y()]),w(),t==null||t({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"success"}})}catch(j){t==null||t({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"error",error:String(j)}}),r(j)}})}function se(e,o,i,t){let s=!!(i&&i.length>0),u=!!t,p=s||u,f=e.length>0&&e[e.length-1].role==="user"?e[e.length-1]:void 0,d=c=>{let g=[],a="";if(u&&(a+=`[Attached files]
15
15
  ${t}
16
16
  [End of attached files]
17
17
 
File without changes
File without changes
@@ -0,0 +1 @@
1
+ import"./chunk-3TXHFKDN.js";import"ai";var n=customHttpTool;export{n as default};
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import{a as A,b as Mn,c as Ce,d as Pe,e as ir,f as $e,g as cr,h as Fe,i as ur}from"./chunk-DEW7U7V7.js";import"./chunk-V35SRZAO.js";import{c as Nn}from"./chunk-ZYIULB2P.js";import"./chunk-6AZ7RATD.js";import"./chunk-XXB57DMN.js";import"./chunk-3K4IMMLP.js";import{a as dr,b as mr}from"./chunk-RFWFJGER.js";import{A as Hn,B as Kn,C as jn,D as Xn,E as qn,F as Vn,G as Gn,H as Jn,I as zn,J as Wn,K as Yn,L as Bn,M as Me,N as Qn,O as Zn,P as er,Q as tr,R as nr,S as rr,T as sr,U as or,V as ar,W as Ne,X as De,Y as lr,a as T,b as Ee,c as rn,d as N,e as Ie,f as sn,g as on,h as an,i as cn,j as ln,k as xe,l as j,m as un,n as Te,o as ke,p as Ae,q as Ue,r as _e,s as Oe,t as W,u as be,v as ve,w as Dn,x as $n,y as Fn,z as Ln}from"./chunk-6JUKM6LT.js";import{A as Cn,B as Pn,a as K,b as tn,c as Re,d as nn,e as Se,f as dn,g as mn,h as pn,i as gn,j as fn,k as yn,l as hn,m as wn,n as Rn,o as Sn,p as En,q as In,r as xn,s as Tn,t as kn,u as An,v as Un,w as _n,x as On,y as bn,z as vn}from"./chunk-QEZQZG6Z.js";import{a as Jt}from"./chunk-RYHQGPX5.js";import{a as zt}from"./chunk-R6EKV3WR.js";import{a as Bt}from"./chunk-6HY7QUMP.js";import{a as Wt,b as Yt}from"./chunk-V6JSMX5A.js";import{a as en}from"./chunk-Q7QHJJGR.js";import{a as O,b as P,c as Qt,d as Zt}from"./chunk-YLDLDEUP.js";import{a as we}from"./chunk-U56YWPSI.js";import"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";import{Agent as Ct}from"agents";import{nanoid as Pt}from"nanoid";async function ut(t){t.sql`CREATE TABLE IF NOT EXISTS messages (id TEXT PRIMARY KEY, role TEXT NOT NULL, type TEXT NOT NULL, content TEXT NOT NULL, ts INTEGER NOT NULL)`}async function Le(t,e){t.sql`INSERT INTO messages (id, role, type, content, ts) VALUES (${e.id}, ${e.role}, ${e.type}, ${e.content}, ${e.ts})`}async function b(t){return t.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function X(t){t.sql`DELETE FROM messages`}async function He(t){await ut(t)}function Y(t){return{"Content-Type":"application/json",Authorization:t.HX_API_KEY}}function q(t){return!!(t!=null&&t.HX_ORA_URL)&&!!(t!=null&&t.HX_API_KEY)}var dt="anonymous:";function Ke(t,e){return(t==null?void 0:t.trim())||`${dt}${e}`}async function B(t,e){if(!q(t))return null;let r=await fetch(`${t.HX_ORA_URL}/internal/runs`,{method:"POST",headers:Y(t),body:JSON.stringify(e)});return r.ok?await r.json():(console.error("[oraTriggers] createRun failed",r.status,await r.text().catch(()=>"")),null)}async function D(t,e){if(!q(t))return{claimed:!0};let r=await fetch(`${t.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/claim`,{method:"POST",headers:Y(t)});if(!r.ok){let n=await r.text().catch(()=>"");throw new Error(`claimRun ${e} failed with ${r.status}: ${n}`)}return await r.json()}async function V(t,e,r,n=3){if(!q(t))return!0;for(let s=1;s<=n;s++){try{let o=await fetch(`${t.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/complete`,{method:"POST",headers:Y(t),body:JSON.stringify(r)});if(o.ok||o.status===409)return!0;if(o.status===404)return console.error(`[oraTriggers] completeRun ${e} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${e} attempt ${s} failed with ${o.status}`)}catch(o){console.warn(`[oraTriggers] completeRun ${e} attempt ${s} threw`,o)}s<n&&await new Promise(o=>setTimeout(o,250*s))}return console.error(`[oraTriggers] completeRun ${e} exhausted ${n} attempts; hx-ora will time the run out`),!1}async function je(t,e){if(!q(t))return Promise.resolve();try{return await B(t,e)}catch(r){return console.error("[oraTriggers] recordRun failed",r),null}}var Q=Object.freeze({}),mt="__SYSTEM_";function Z(t){return t.startsWith(mt)}function pt(t){let e={};for(let[r,n]of Object.entries(t))Z(r)||(e[r]=n);return Object.freeze(e)}function G(t){return(typeof t=="string"?t.trim():"")||"default"}async function Xe(t,e,r){if(!e)return Q;let n=G(r);if(t.HX_ORA_URL&&t.HX_API_KEY)try{let o=new URL(`${t.HX_ORA_URL.replace(/\/$/,"")}/internal/secrets`);o.searchParams.set("org",n);let a=await fetch(o,{headers:{Authorization:t.HX_API_KEY}});if(a.ok){let i=await a.json();if(i.secrets)return pt(i.secrets)}else console.warn(`[secrets] API failed with status ${a.status}, falling back to KV`)}catch(o){console.error("[secrets] API request failed, falling back to KV",o)}let s=t.ORA_SECRETS;if(!s)return Q;try{let o={};return await gt(s,`${e}:${n}:`,o),n==="default"&&await ft(s,e,o),Object.freeze(o)}catch(o){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,org:n,err:o}),Q}}async function gt(t,e,r){let n=await t.list({prefix:e,limit:1e3});n.list_complete===!1&&console.warn(`[secrets] prefix=${e} exceeded list page; truncating to first 1000 keys`);let s=n.keys.filter(a=>{let i=a.name.slice(e.length);return i.length>0&&!i.includes(":")&&!Z(i)}),o=await Promise.all(s.map(async a=>{let i=await t.get(a.name);return i!==null?[a.name.slice(e.length),i]:null}));for(let a of o){if(!a)continue;let[i,c]=a;i&&(r[i]=c)}}async function ft(t,e,r){let n=`${e}:`,s=await t.list({prefix:n,limit:1e3});s.list_complete===!1&&console.warn(`[secrets] tenant=${e} legacy secrets exceeded list page; truncating to first 1000 keys`);let o=s.keys.filter(i=>{let c=i.name.slice(n.length);return c.length>0&&!c.includes(":")&&!Z(c)}),a=await Promise.all(o.map(async i=>{let c=i.name.slice(n.length);if(c in r)return null;let d=await t.get(i.name);return d!==null?[c,d]:null}));for(let i of a){if(!i)continue;let[c,d]=i;c&&(r[c]=d)}}function J(t){var s;let e=((s=t==null?void 0:t.flowData)==null?void 0:s.state)??(t==null?void 0:t.flowData),n=((e==null?void 0:e.nodes)??[]).find(o=>o.type==="startNode");return n==null?void 0:n.data}import{nanoid as _t}from"nanoid";import{streamText as yt}from"ai";var ht={short:`Up to ${j("short")} markdown lines (one fact or bullet per line). Keep constraints, working agreements, and the outline of anything already settled.`,medium:`Up to ${j("medium")} markdown lines. Group bullets by whatever this session is about (actors, constraints, decisions, current plan/state, open work). Under-remembering is worse than a few extra lines.`,long:`Up to ${j("long")} markdown lines. Same as medium, with one-line context on a decision or plan block when later turns will need it.`},wt=12,Rt=400,qe=700;function St(t,e=wt){let r=t.filter(s=>s.role==="user"||s.role==="assistant").slice(-e),n=[];for(let s of r){let o=typeof s.content=="string"?s.content:JSON.stringify(s.content??""),a=s.role==="assistant"?qe:Rt,i=o.trim().replace(/\s+/g," ").slice(0,a);i&&n.push(`${s.role==="user"?"U":"A"}: ${i}`)}return n.join(`
2
- `)}function Et(t){let e=t??{},r=e.promptTokens??e.inputTokens??0,n=e.completionTokens??e.outputTokens??0,s=e.totalTokens??r+n;return{promptTokens:r,completionTokens:n,totalTokens:s}}function It(t){var e;for(let r=t.length-1;r>=0;r--)if(((e=t[r])==null?void 0:e.role)==="assistant"&&typeof t[r].content=="string")return t[r].content;return""}function xt(t){var s,o;let e=((s=t.flowData)==null?void 0:s.state)??t.flowData,r=(e==null?void 0:e.nodes)??[],n=[];for(let a of r){if(a.type!=="answerNode")continue;let i=(o=t.results)==null?void 0:o[a.id];i!=null&&n.push(typeof i=="string"?i:JSON.stringify(i))}return n.join(`
3
- `)}function Tt(t){var n;let e=["You maintain a KEYPOINT memory for one agent session so later turns can continue without re-asking.",`Hard limit: ${t.maxTokens} tokens.`,ht[t.length],"The session domain is unknown: personal, operational, technical, or mixed. Do not assume a personal-coaching frame.","Store facts that will still matter: who/what is in play, constraints and invariants, preferences, decisions, current state of the work, and the outline of anything the user accepted or asked to keep.","When something was confirmed (a plan, a process, a design, a sequence), keep a compact outline \u2014 enough to resume the next part \u2014 not the assistant\u2019s full wording.","Keep earlier facts unless the user superseded them. Merge, update, dedupe. Do not collapse memory to a single identity line plus one decision.","Never copy the conversation. Never write User:/Assistant:/U:/A: lines. Drop greetings, filler, and unanswered assistant questions.","If this turn added nothing durable, return the current memory unchanged.","If memory is empty and nothing durable happened, return exactly: (none)","Use the same language as the user. Return only the bullet list \u2014 no preamble."].join(" "),r=["Current keypoint memory:",'"""',t.previous.trim()||"(empty)",'"""',"","Recent session (for extraction only; do not transcribe):",'"""',((n=t.recentTurns)==null?void 0:n.trim())||"(none)",'"""',"","This turn:",`User said: ${t.userText.trim()||"(empty)"}`,t.assistantText.trim()?`Latest assistant reply (extract accepted plan/facts only): ${t.assistantText.trim().slice(0,qe)}`:"",t.answers.trim()?`Answer outputs:
1
+ import{a as k,b as Mn,c as Ce,d as Pe,e as ir,f as $e,g as cr,h as Fe,i as ur}from"./chunk-DZQ3WL3Y.js";import"./chunk-V35SRZAO.js";import{c as Nn}from"./chunk-ZYIULB2P.js";import"./chunk-6AZ7RATD.js";import"./chunk-XXB57DMN.js";import"./chunk-3K4IMMLP.js";import{a as dr,b as pr}from"./chunk-RFWFJGER.js";import{A as Hn,B as jn,C as Kn,D as Xn,E as qn,F as Vn,G as zn,H as Gn,I as Jn,J as Wn,K as Yn,L as Bn,M as Me,N as Qn,O as Zn,P as er,Q as tr,R as nr,S as rr,T as sr,U as or,V as ar,W as Ne,X as De,Y as lr,a as E,b as Ee,c as rn,d as P,e as Ie,f as sn,g as on,h as an,i as cn,j as ln,k as Te,l as L,m as un,n as xe,o as ke,p as Ue,q as Ae,r as _e,s as be,t as W,u as Oe,v as ve,w as Dn,x as $n,y as Fn,z as Ln}from"./chunk-6JUKM6LT.js";import{A as Cn,B as Pn,a as F,b as tn,c as Re,d as nn,e as Se,f as dn,g as pn,h as mn,i as fn,j as gn,k as yn,l as hn,m as wn,n as Rn,o as Sn,p as En,q as In,r as Tn,s as xn,t as kn,u as Un,v as An,w as _n,x as bn,y as On,z as vn}from"./chunk-QEZQZG6Z.js";import{a as Gt}from"./chunk-RYHQGPX5.js";import{a as Jt}from"./chunk-R6EKV3WR.js";import{a as Bt}from"./chunk-6HY7QUMP.js";import{a as Wt,b as Yt}from"./chunk-V6JSMX5A.js";import{a as en}from"./chunk-Q7QHJJGR.js";import{a as b,b as C,c as Qt,d as Zt}from"./chunk-YLDLDEUP.js";import{a as we}from"./chunk-U56YWPSI.js";import"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";import{Agent as Be}from"agents";import{nanoid as Pt}from"nanoid";async function dt(t){t.sql`CREATE TABLE IF NOT EXISTS messages (id TEXT PRIMARY KEY, role TEXT NOT NULL, type TEXT NOT NULL, content TEXT NOT NULL, ts INTEGER NOT NULL)`}async function Le(t,e){t.sql`INSERT INTO messages (id, role, type, content, ts) VALUES (${e.id}, ${e.role}, ${e.type}, ${e.content}, ${e.ts})`}async function O(t){return t.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function H(t){t.sql`DELETE FROM messages`}async function He(t){await dt(t)}function Y(t){return{"Content-Type":"application/json",Authorization:t.HX_API_KEY}}function j(t){return!!(t!=null&&t.HX_ORA_URL)&&!!(t!=null&&t.HX_API_KEY)}var pt="anonymous:";function je(t,e){return(t==null?void 0:t.trim())||`${pt}${e}`}async function B(t,e){if(!j(t))return null;let r=await fetch(`${t.HX_ORA_URL}/internal/runs`,{method:"POST",headers:Y(t),body:JSON.stringify(e)});return r.ok?await r.json():(console.error("[oraTriggers] createRun failed",r.status,await r.text().catch(()=>"")),null)}async function M(t,e){if(!j(t))return{claimed:!0};let r=await fetch(`${t.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/claim`,{method:"POST",headers:Y(t)});if(!r.ok){let n=await r.text().catch(()=>"");throw new Error(`claimRun ${e} failed with ${r.status}: ${n}`)}return await r.json()}async function K(t,e,r,n=3){if(!j(t))return!0;for(let s=1;s<=n;s++){try{let a=await fetch(`${t.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/complete`,{method:"POST",headers:Y(t),body:JSON.stringify(r)});if(a.ok||a.status===409)return!0;if(a.status===404)return console.error(`[oraTriggers] completeRun ${e} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${e} attempt ${s} failed with ${a.status}`)}catch(a){console.warn(`[oraTriggers] completeRun ${e} attempt ${s} threw`,a)}s<n&&await new Promise(a=>setTimeout(a,250*s))}return console.error(`[oraTriggers] completeRun ${e} exhausted ${n} attempts; hx-ora will time the run out`),!1}async function Ke(t,e){if(!j(t))return Promise.resolve();try{return await B(t,e)}catch(r){return console.error("[oraTriggers] recordRun failed",r),null}}var Q=Object.freeze({}),mt="__SYSTEM_";function Z(t){return t.startsWith(mt)}function ft(t){let e={};for(let[r,n]of Object.entries(t))Z(r)||(e[r]=n);return Object.freeze(e)}function X(t){return(typeof t=="string"?t.trim():"")||"default"}async function Xe(t,e,r){if(!e)return Q;let n=X(r);if(t.HX_ORA_URL&&t.HX_API_KEY)try{let a=new URL(`${t.HX_ORA_URL.replace(/\/$/,"")}/internal/secrets`);a.searchParams.set("org",n);let o=await fetch(a,{headers:{Authorization:t.HX_API_KEY}});if(o.ok){let i=await o.json();if(i.secrets)return ft(i.secrets)}else console.warn(`[secrets] API failed with status ${o.status}, falling back to KV`)}catch(a){console.error("[secrets] API request failed, falling back to KV",a)}let s=t.ORA_SECRETS;if(!s)return Q;try{let a={};return await gt(s,`${e}:${n}:`,a),n==="default"&&await yt(s,e,a),Object.freeze(a)}catch(a){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,org:n,err:a}),Q}}async function gt(t,e,r){let n=await t.list({prefix:e,limit:1e3});n.list_complete===!1&&console.warn(`[secrets] prefix=${e} exceeded list page; truncating to first 1000 keys`);let s=n.keys.filter(o=>{let i=o.name.slice(e.length);return i.length>0&&!i.includes(":")&&!Z(i)}),a=await Promise.all(s.map(async o=>{let i=await t.get(o.name);return i!==null?[o.name.slice(e.length),i]:null}));for(let o of a){if(!o)continue;let[i,c]=o;i&&(r[i]=c)}}async function yt(t,e,r){let n=`${e}:`,s=await t.list({prefix:n,limit:1e3});s.list_complete===!1&&console.warn(`[secrets] tenant=${e} legacy secrets exceeded list page; truncating to first 1000 keys`);let a=s.keys.filter(i=>{let c=i.name.slice(n.length);return c.length>0&&!c.includes(":")&&!Z(c)}),o=await Promise.all(a.map(async i=>{let c=i.name.slice(n.length);if(c in r)return null;let l=await t.get(i.name);return l!==null?[c,l]:null}));for(let i of o){if(!i)continue;let[c,l]=i;c&&(r[c]=l)}}function q(t){var s;let e=((s=t==null?void 0:t.flowData)==null?void 0:s.state)??(t==null?void 0:t.flowData),n=((e==null?void 0:e.nodes)??[]).find(a=>a.type==="startNode");return n==null?void 0:n.data}import{nanoid as bt}from"nanoid";import{streamText as ht}from"ai";var wt={short:`Up to ${L("short")} markdown lines (one fact or bullet per line). Keep constraints, working agreements, and the outline of anything already settled.`,medium:`Up to ${L("medium")} markdown lines. Group bullets by whatever this session is about (actors, constraints, decisions, current plan/state, open work). Under-remembering is worse than a few extra lines.`,long:`Up to ${L("long")} markdown lines. Same as medium, with one-line context on a decision or plan block when later turns will need it.`},Rt=12,St=400,qe=700;function Et(t,e=Rt){let r=t.filter(s=>s.role==="user"||s.role==="assistant").slice(-e),n=[];for(let s of r){let a=typeof s.content=="string"?s.content:JSON.stringify(s.content??""),o=s.role==="assistant"?qe:St,i=a.trim().replace(/\s+/g," ").slice(0,o);i&&n.push(`${s.role==="user"?"U":"A"}: ${i}`)}return n.join(`
2
+ `)}function It(t){let e=t??{},r=e.promptTokens??e.inputTokens??0,n=e.completionTokens??e.outputTokens??0,s=e.totalTokens??r+n;return{promptTokens:r,completionTokens:n,totalTokens:s}}function Tt(t){var e;for(let r=t.length-1;r>=0;r--)if(((e=t[r])==null?void 0:e.role)==="assistant"&&typeof t[r].content=="string")return t[r].content;return""}function xt(t){var s,a;let e=((s=t.flowData)==null?void 0:s.state)??t.flowData,r=(e==null?void 0:e.nodes)??[],n=[];for(let o of r){if(o.type!=="answerNode")continue;let i=(a=t.results)==null?void 0:a[o.id];i!=null&&n.push(typeof i=="string"?i:JSON.stringify(i))}return n.join(`
3
+ `)}function kt(t){var n;let e=["You maintain a KEYPOINT memory for one agent session so later turns can continue without re-asking.",`Hard limit: ${t.maxTokens} tokens.`,wt[t.length],"The session domain is unknown: personal, operational, technical, or mixed. Do not assume a personal-coaching frame.","Store facts that will still matter: who/what is in play, constraints and invariants, preferences, decisions, current state of the work, and the outline of anything the user accepted or asked to keep.","When something was confirmed (a plan, a process, a design, a sequence), keep a compact outline \u2014 enough to resume the next part \u2014 not the assistant\u2019s full wording.","Keep earlier facts unless the user superseded them. Merge, update, dedupe. Do not collapse memory to a single identity line plus one decision.","Never copy the conversation. Never write User:/Assistant:/U:/A: lines. Drop greetings, filler, and unanswered assistant questions.","If this turn added nothing durable, return the current memory unchanged.","If memory is empty and nothing durable happened, return exactly: (none)","Use the same language as the user. Return only the bullet list \u2014 no preamble."].join(" "),r=["Current keypoint memory:",'"""',t.previous.trim()||"(empty)",'"""',"","Recent session (for extraction only; do not transcribe):",'"""',((n=t.recentTurns)==null?void 0:n.trim())||"(none)",'"""',"","This turn:",`User said: ${t.userText.trim()||"(empty)"}`,t.assistantText.trim()?`Latest assistant reply (extract accepted plan/facts only): ${t.assistantText.trim().slice(0,qe)}`:"",t.answers.trim()?`Answer outputs:
4
4
  ${t.answers.trim()}`:""].filter(Boolean).join(`
5
- `);return{system:e,user:r}}function kt(t){return ve(t.previous,be(t.userText),t.maxTokens)}async function At(t){let e="",r;for await(let n of t.fullStream)n.type==="text-delta"&&(e+=n.text??n.delta??""),n.type==="error"&&(r=n.error instanceof Error?n.error.message:String(n.error??"stream error"));return{text:e.trim(),error:r}}async function Ut(t){if(t.fullStream&&typeof t.fullStream[Symbol.asyncIterator]=="function")return At({fullStream:t.fullStream});try{return{text:((typeof t.text=="string"?t.text:await t.text)||"").trim()}}catch(e){return{text:"",error:e instanceof Error?e.message:String(e)}}}async function Ve(t){var d;let e=J(t.engineState);if(!e)return{status:"skipped",reason:"start_node_missing"};if(!ke(e))return{status:"skipped",reason:"memory_disabled"};let r=Ue(e),n=xe(r),s=Ae(e),o=W(t.previousContent||""),a=It(t.messages),i=xt(t.engineState),c=m=>{let h=kt({previous:o,userText:t.userText,maxTokens:n});return{status:"written",content:h,truncated:!1,modelId:s,fallback:!0,error:h?void 0:m}};try{let m=await $e(s,t.sessionEnv,{maxOutputTokens:n});if(!m)throw new Error(`Memory model '${s}' not found in registry`);let h=_e(r,(d=m.reasoning)==null?void 0:d.kind),{system:R,user:u}=Tt({previous:o,userText:t.userText,assistantText:a,answers:i,length:r,maxTokens:n,recentTurns:St(t.messages)}),p=Ne(m.reasoning),g=De(m.provider,{effort:p,exposeReasoning:!1,maxTokens:h}),f=yt({model:m.modelHandle,system:R,messages:[{role:"user",content:u}],...Me({...m.effectiveParams??{},maxOutputTokens:h}),...g?{providerOptions:g}:{}}),y=await Ut(f),E=Et(await f.usage),x=W(y.text);if(Oe(x)&&(x=""),!x)return{...c(y.error||"Memory model returned empty text"),usage:E};let I=Te(x,n);return{status:"written",content:I.content,truncated:I.truncated,usage:E,modelId:s}}catch(m){let h=m instanceof Error?m.message:"Memory update failed";return console.error("Memory update failed:",m),c(h)}}async function Ge(t,e){var n,s;let r=(n=e==null?void 0:e.flowData)==null?void 0:n.flowId;if(!(t!=null&&t.HX_CORE_URL)||!r)return{engineState:e,refreshed:!1};try{let o=await P(r,t),a={...e,flowData:{...o,tenant:e.flowData.tenant,flowId:r,chatId:e.flowData.chatId}},i=o==null?void 0:o.stateVersion,c=typeof i=="number"&&i!==((s=e.flowData)==null?void 0:s.stateVersion);return{engineState:a,refreshed:c}}catch(o){return console.error(`[flowRefresh] fetch failed for flow ${r}:`,o),{engineState:e,refreshed:!1}}}function Je(t,e){return!t||!t.HX_ORA_URL||!t.HX_API_KEY?Promise.resolve():fetch(`${t.HX_ORA_URL}/internal/sessions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t.HX_API_KEY},body:JSON.stringify(e)}).catch(r=>{console.error("[sessionIndex] failed to index session",r)})}var ze=async(t,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),`${JSON.stringify(t)}`};async function $(t,e){var o,a;let r=t.id||t.name||"",[n,s]=String(r).split("::");if(!n||!s)return null;try{let c=(o=(await O(n,e)).metadata)==null?void 0:o.tenant,d=await P(n,e),m=(a=t.state)==null?void 0:a.user,h={flowData:{...d,tenant:c,flowId:n,chatId:s},executedNodes:[],context:m?{user:m}:{}};return t.setState({...t.state,engineState:h}),h}catch(i){return console.error("Failed to initialize engine state:",i),null}}async function Ot(t,e,r){var n;if(e&&t.HX_CORE_URL&&t.HX_API_KEY)try{let s=await O(e,t),o=(n=s==null?void 0:s.metadata)==null?void 0:n.org;if(typeof o=="string"&&o.trim())return G(o)}catch(s){console.warn(`[secrets] could not read org for flow ${e}`,s)}return G(r)}async function F(t){var H,ne,re,se,oe,ae,ie,ce,le,ue,de,me;let{agent:e,env:r,ctx:n,payload:s,connection:o}=t,a=Date.now(),i=[],c=t.runId?Ce():void 0,d=async()=>await b(e),m=async l=>{await Le(e,l)},h=async l=>{if(e.state.modelsCache&&e.state.modelsCache[l])return e.state.modelsCache[l];try{let{fetchOraModel:w}=await import("./oraApi-YIJGMXX7.js"),k=await w(l,r);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[l]:k}}),k}catch(w){throw console.error(`Error fetching model ${l}:`,w),w}},R={id:_t(),role:"user",type:"text",content:s.text,images:s.images,ts:Date.now()};await m(R);let u={onChangeState:l=>{e.setState({...e.state,engineState:l})},onServerEvent:async l=>{var w;await((w=t.onServerEvent)==null?void 0:w.call(t,l)),i.push(l)},onTelemetry:async l=>{var _,pe,ge,fe,ye,he;let w=t.user??e.state.user,k=typeof(w==null?void 0:w.org)=="string"&&w.org.trim()?w.org.trim():"default";await ze({...l,userId:t.resolveUserId(),tenant:((pe=(_=e.state.engineState)==null?void 0:_.flowData)==null?void 0:pe.tenant)||"",org:k,flowId:((fe=(ge=e.state.engineState)==null?void 0:ge.flowData)==null?void 0:fe.flowId)||"",sessionId:((he=(ye=e.state.engineState)==null?void 0:ye.flowData)==null?void 0:he.chatId)||""},r)},onError:l=>{var w;(w=t.onError)==null||w.call(t,l),e.setState({...e.state,error:l})},shouldStop:t.shouldStop},p=e.state.engineState?{...e.state.engineState}:null;if(p){let{engineState:l,refreshed:w}=await Ge(r,p);p=l,w&&e.setState({...e.state,engineState:p,modelsCache:{}})}else if(p=await $(e,r),!p){let l="Failed to initialize agent";return u.onError(l),{status:"failed",error:l}}let g=t.user??e.state.user??void 0,f=(H=p.flowData)==null?void 0:H.tenant,y=await Ot(r,(ne=p.flowData)==null?void 0:ne.flowId,g==null?void 0:g.org),E=f?await Xe(r,f,y):{};(re=t.onSecretsLoaded)==null||re.call(t,E),g&&!((se=p.context)!=null&&se.user)&&(p.context={...p.context||{},user:g});let x={env:r,ctx:n,conn:o,getMessages:d,setMessages:m,getOraModel:h,secrets:E,userAuth:t.userAuth,user:g,composioSessions:t.composioSessions,publicOrigin:t.publicOrigin,skillRefCache:t.skillRefCache,runId:t.runId,outputCollector:c,agentMemory:typeof((oe=e.state.memory)==null?void 0:oe.content)=="string"?e.state.memory.content:"",shouldStop:t.shouldStop,workerStack:(ae=p.flowData)!=null&&ae.flowId?[p.flowData.flowId]:[],workerCalls:{count:0}},I=await Fe(x,p,u)(s),S=e.state.engineState??p;if(I.status==="completed")try{let l=await Ve({sessionEnv:x,engineState:S,previousContent:typeof((ie=e.state.memory)==null?void 0:ie.content)=="string"?e.state.memory.content:"",userText:s.text||"",messages:await d()});if(l.status==="skipped")await u.onServerEvent({type:"agent:memory",content:{skipped:!0,reason:l.reason},timestamp:Date.now()});else if(!l.content.trim())await u.onServerEvent({type:"agent:memory",content:{updated:!1,empty:!0,error:l.error,fallback:l.fallback},timestamp:Date.now()});else{let w={promptTokens:((ce=S.tokenUsage)==null?void 0:ce.promptTokens)??0,completionTokens:((le=S.tokenUsage)==null?void 0:le.completionTokens)??0,totalTokens:((ue=S.tokenUsage)==null?void 0:ue.totalTokens)??0};l.usage&&(w.promptTokens+=l.usage.promptTokens,w.completionTokens+=l.usage.completionTokens,w.totalTokens+=l.usage.totalTokens),S={...S,tokenUsage:w},e.setState({...e.state,engineState:S,memory:{content:l.content,updatedTs:Date.now(),...l.error?{lastError:l.error}:{},...l.fallback?{fallback:!0}:{}}}),await u.onTelemetry({type:"memory_update",payload:{model:l.modelId,truncated:l.truncated,usage:l.usage,fallback:l.fallback,error:l.error}}),await u.onServerEvent({type:"agent:memory",content:{updated:!0,truncated:l.truncated,fallback:l.fallback,error:l.error},timestamp:Date.now()})}}catch(l){let w=l instanceof Error?l.message:"Memory update failed";console.error("Memory update failed:",l),await u.onServerEvent({type:"agent:memory",content:{error:w},timestamp:Date.now()})}if(I.status==="completed"&&t.runId&&(c!=null&&c.hasOutputs())){let{flowId:l,chatId:w}=S.flowData??{};if(!l||!w)I={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await Pe(r,{flowId:l,sessionId:w,runId:t.runId,createdAt:new Date(a).toISOString(),data:c.snapshotData(),answerNodeIds:c.answerNodeIds()});let k={...S.results||{}};for(let _ of c.answerNodeIds())k[_]={...k[_]||{},persisted:!0,runId:t.runId};S={...S,results:k},e.setState({...e.state,engineState:S})}catch(k){let _=k instanceof Error?k.message:"Structured output persistence failed";u.onError(_),await u.onServerEvent({type:"error:answer-output",content:{runId:t.runId,error:_},timestamp:Date.now()}),I={status:"failed",error:_}}}let{tenant:v,flowId:M,chatId:L}=S.flowData??{},te=(de=S.flowData)==null?void 0:de.org;return v&&M&&L&&n.waitUntil(Je(r,{id:`${M}::${L}`,tenant:v,org:te,flowId:M,sessionId:L,userId:t.resolveUserId(),title:(me=s.text)==null?void 0:me.slice(0,120),turnTs:a,events:i})),e.setState({...e.state,lastUpdated:new Date}),{status:I.status,error:I.error,engineState:S}}import{nanoid as bt}from"nanoid";function vt(t){let e=t.headers.get("X-User-Payload");if(!e)return null;try{let r=JSON.parse(e),n=typeof(r==null?void 0:r.email)=="string"?N(r.email):null;return n?{...r,email:n}:null}catch{return null}}async function We(t,e,r,n){var s;try{let o=await e.json(),a=o.message;if(!a||typeof a!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let i=typeof o.userId=="string"?N(o.userId):null,c=vt(e),d=c==null?void 0:c.email;c?t.setState({...t.state,user:c,injectedUserId:d}):i&&!((s=t.state.user)!=null&&s.email)&&t.setState({...t.state,injectedUserId:i});let m=()=>d??i??t.state.injectedUserId??void 0;t.skillRefCache||(t.skillRefCache=new Map);let h=o.inputs&&typeof o.inputs=="object"?o.inputs:void 0;if(!t.state.engineState&&!await $(t,r))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let R=`run-${bt(12)}`;await t.registerManualRun(R,a,m()),await D(r,R).catch(f=>{console.warn(`[AgentHTTP] could not mark manual run ${R} as running`,f)});let u;try{u=await F({agent:t,env:r,ctx:n,payload:{text:a,inputs:h},skillRefCache:t.skillRefCache,user:c??void 0,resolveUserId:m,runId:R,shouldStop:()=>t.isRunStopRequested(R)}),n.waitUntil(t.completeManualRun(R,u.status==="completed"?"succeeded":u.status==="stopped"?"skipped":"failed",u.error))}finally{await t.clearRunStopRequest(R)}if(u.status==="failed")return new Response(JSON.stringify({error:u.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});if(u.status==="stopped")return new Response(JSON.stringify({error:u.error||"Stopped by user"}),{status:409,headers:{"content-type":"application/json"}});let g=(await b(t)).reverse().find(f=>f.role==="assistant");return new Response(JSON.stringify({answer:(g==null?void 0:g.content)||""}),{headers:{"content-type":"application/json"}})}catch(o){return new Response(JSON.stringify({error:o.message}),{status:500,headers:{"content-type":"application/json"}})}}async function Ye(t){try{return await X(t),t.skillRefCache&&t.skillRefCache.clear(),t.setState({...t.state,error:"",engineState:void 0,modelsCache:{},lastUpdated:new Date}),new Response(JSON.stringify({success:!0,messages:[]}),{headers:{"content-type":"application/json"}})}catch(e){return new Response(JSON.stringify({error:e.message}),{status:500,headers:{"content-type":"application/json"}})}}var Be="trigger:nonce:",Mt=900*1e3,ee="run:stop:",Qe=class extends Ct{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{},memory:void 0};resolveSessionUserId(){var e;return((e=this.state.user)==null?void 0:e.email)??this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async inspectPersistedSession(e){return e==="state"?{state:this.state}:e==="memory"?{memory:this.state.memory??null}:{messages:await b(this)}}async requestRunStop(e){return e!=null&&e.trim()?(await this.ctx.storage.put(`${ee}${e}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(e){return!!await this.ctx.storage.get(`${ee}${e}`)}async clearRunStopRequest(e){await this.ctx.storage.delete(`${ee}${e}`)}async onRequest(e){let r=new URL(e.url);if(r.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(r.pathname.endsWith("/history")){let n=await b(this);return new Response(JSON.stringify(n),{headers:{"content-type":"application/json"}})}return e.method==="POST"&&r.pathname.endsWith("/message")?We(this,e,this.env,this.ctx):e.method==="DELETE"&&r.pathname.endsWith("/clear")?Ye(this):new Response("Ready to assist.")}async onConnect(e,r){var R,u,p,g,f;let[n,s]=e.server.split("::"),a=(R=(await O(n,this.env)).metadata)==null?void 0:R.tenant;this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let i=null;if(r.request){try{this.publicOrigin=new URL(r.request.url).origin}catch{}let y=r.request.headers.get("X-User-Payload");if(y)try{i=JSON.parse(y)}catch(E){console.warn("Failed to parse X-User-Payload",E)}}let c=await P(n,this.env);this.setState({...this.state,user:i||null,sessionId:s,engineState:{flowData:{...c,tenant:a,flowId:n,chatId:s},executedNodes:[],context:i?{user:i}:{}}}),i||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let d=await b(this);A(e,T.SERVER_HISTORY,JSON.stringify({messages:d}));let h=(((u=c==null?void 0:c.state)==null?void 0:u.nodes)??(c==null?void 0:c.nodes)??[]).find(y=>y.type==="startNode");if(h){let y={allow_images:((p=h.data)==null?void 0:p.allow_images)??!1,allow_documents:((g=h.data)==null?void 0:g.allow_documents)??!1,greeting:(f=h.data)==null?void 0:f.greeting};A(e,T.SERVER_CONFIG,JSON.stringify(y))}}async onMessage(e,r){if(typeof r!="string")return;let n=r.indexOf(":");if(n===-1)return;let s=r.substring(0,n),o=r.substring(n+1);if(!s||!o)return;let i={[T.USER_MESSAGE]:c=>this.onUserMessage(e,c),[T.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[T.USER_AUTH]:c=>this.onUserAuth(e,c),[T.USER_IDENTITY]:c=>this.onUserIdentity(e,c)}[s];i&&await i(o)}async onUserMessage(e,r){let n=Ee(r),s=`run-${Pt(12)}`;await this.registerManualRun(s,n.text),await D(this.env,s).catch(o=>{console.warn(`[AgentDO] could not mark manual run ${s} as running`,o)});try{let o=await F({agent:this,env:this.env,ctx:this.ctx,payload:n,connection:e,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:this.state.user,resolveUserId:()=>this.resolveSessionUserId(),runId:s,shouldStop:()=>this.isRunStopRequested(s),onServerEvent:a=>{A(e,T.SERVER_EVENT,JSON.stringify(a))},onError:a=>{A(e,T.SERVER_ERROR,a)},onSecretsLoaded:a=>{this.secrets=a}});this.ctx.waitUntil(this.completeManualRun(s,o.status==="completed"?"succeeded":o.status==="stopped"?"skipped":"failed",o.error))}finally{await this.clearRunStopRequest(s)}}registerManualRun(e,r,n){var c;let{tenant:s,flowId:o,chatId:a}=((c=this.state.engineState)==null?void 0:c.flowData)??{};if(!s||!o||!a)return Promise.resolve();let i=Ke(n||this.resolveSessionUserId(),a);return je(this.env,{id:e,tenant:s,flowId:o,userId:i,sessionId:a,label:r==null?void 0:r.slice(0,120)})}completeManualRun(e,r,n){return V(this.env,e,{status:r,error:n})}async enqueueTrigger(e){var s;if(!(e!=null&&e.runId)||!(e!=null&&e.flowId))return{queued:!1};if(e.nonce&&!await this.claimTriggerNonce(e.nonce))return console.warn(`[AgentDO] rejected replayed trigger nonce ${e.nonce}`),{queued:!1,duplicate:!0};let r=e.runAsUserId;return r&&!((s=this.state.user)!=null&&s.email)&&this.state.injectedUserId!==r&&this.setState({...this.state,injectedUserId:r}),{queued:!0,taskId:await this.queue("processTrigger",e)}}async claimTriggerNonce(e){let r=`${Be}${e}`;if(await this.ctx.storage.get(r))return!1;let n=Date.now();await this.ctx.storage.put(r,n);let o=[...(await this.ctx.storage.list({prefix:Be})).entries()].filter(([,a])=>n-a>Mt).map(([a])=>a);return o.length>0&&await this.ctx.storage.delete(o),!0}async processTrigger(e){if(!(await D(this.env,e.runId)).claimed){console.warn(`[AgentDO] activation ${e.activationId} skipped \u2014 run ${e.runId} already claimed`);return}try{this.state.engineState||await $(this,this.env);let n=Re(J(this.state.engineState)),s=Se(n,e.inputs||{},e.label),o=await F({agent:this,env:this.env,ctx:this.ctx,payload:{text:s,inputs:e.inputs||{}},composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>e.runAsUserId||this.resolveSessionUserId(),runId:e.runId,shouldStop:()=>this.isRunStopRequested(e.runId),onSecretsLoaded:a=>{this.secrets=a}});await V(this.env,e.runId,{status:o.status==="completed"?"succeeded":o.status==="stopped"?"skipped":"failed",error:o.error})}catch(n){let s=n instanceof Error?n.message:"Trigger execution failed";throw await V(this.env,e.runId,{status:"failed",error:s}),n}finally{await this.clearRunStopRequest(e.runId)}}async onUserIdentity(e,r){let n=N(r);if(!n){A(e,T.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:n}),A(e,T.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,r){let n=Ie(r);if(!n){A(e,T.SERVER_ERROR,"Invalid auth payload");return}let s=n.value.trim();s===""?delete this.userAuth[n.name]:this.userAuth[n.name]=n.value,A(e,T.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:n.name,set:s!==""}}))}async onClearHistory(e){await X(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear(),this.setState({...this.state,error:"",engineState:this.state.engineState,memory:this.state.memory,modelsCache:{},lastUpdated:new Date}),e&&A(e,T.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await He(this);let e=await b(this);`${JSON.stringify(e)}`}async onClose(e,r,n,s){console.log(`Session closed: ${this.state.sessionId} ${r} - ${n}`)}async onError(e){console.error("AgentDO encountered an error:",e)}};function ds(t){let e=t.state;if(!e)return null;let r=["startNode","answerNode"];for(let n of r)if(!e.nodes.some(o=>o.type===n))return!1;return e.nodes.find(n=>n.type==="startNode")}import{importSPKI as Nt,jwtVerify as Dt}from"jose";function Ze(t){let e={};if(!t)return e;let r=t.split(";");for(let n of r){let s=n.indexOf("=");if(s>-1){let o=n.slice(0,s).trim(),a=n.slice(s+1).trim();o&&(e[o]=decodeURIComponent(a))}}return e}function $t(t){return(typeof t.email=="string"?t.email.trim():"")||null}async function C(t,e,r){let n=Ze(t.headers.get("cookie")),s=new URL(t.url),o=n.access_token||s.searchParams.get("access_token"),a=await Ft(e,o);if(a.ok){let i=a.payload,c=$t(i);return c?{id:i.sub,email:c,name:i.name,first_name:i.given_name,last_name:i.family_name,tenant:i.tenant,org:typeof i.org=="string"?i.org:null,roles:i["ora-roles"],db_name:i.db_name||null,user_id:i.user_id||null}:null}return null}async function Ft(t,e){if(!e||typeof e!="string")return{ok:!1,payload:null,protectedHeader:null};if(!t.KC_RS256_PK)throw new Error("PK is not defined");let r=`-----BEGIN PUBLIC KEY-----
5
+ `);return{system:e,user:r}}function Ut(t){return ve(t.previous,Oe(t.userText),t.maxTokens)}async function At(t){let e="",r;for await(let n of t.fullStream)n.type==="text-delta"&&(e+=n.text??n.delta??""),n.type==="error"&&(r=n.error instanceof Error?n.error.message:String(n.error??"stream error"));return{text:e.trim(),error:r}}async function _t(t){if(t.fullStream&&typeof t.fullStream[Symbol.asyncIterator]=="function")return At({fullStream:t.fullStream});try{return{text:((typeof t.text=="string"?t.text:await t.text)||"").trim()}}catch(e){return{text:"",error:e instanceof Error?e.message:String(e)}}}async function Ve(t){var l;let e=q(t.engineState);if(!e)return{status:"skipped",reason:"start_node_missing"};if(!ke(e))return{status:"skipped",reason:"memory_disabled"};let r=Ae(e),n=Te(r),s=Ue(e),a=W(t.previousContent||""),o=Tt(t.messages),i=xt(t.engineState),c=u=>{let f=Ut({previous:a,userText:t.userText,maxTokens:n});return{status:"written",content:f,truncated:!1,modelId:s,fallback:!0,error:f?void 0:u}};try{let u=await $e(s,t.sessionEnv,{maxOutputTokens:n});if(!u)throw new Error(`Memory model '${s}' not found in registry`);let f=_e(r,(l=u.reasoning)==null?void 0:l.kind),{system:m,user:d}=kt({previous:a,userText:t.userText,assistantText:o,answers:i,length:r,maxTokens:n,recentTurns:Et(t.messages)}),g=Ne(u.reasoning),y=De(u.provider,{effort:g,exposeReasoning:!1,maxTokens:f}),w=ht({model:u.modelHandle,system:m,messages:[{role:"user",content:d}],...Me({...u.effectiveParams??{},maxOutputTokens:f}),...y?{providerOptions:y}:{}}),R=await _t(w),I=It(await w.usage),A=W(R.text);if(be(A)&&(A=""),!A)return{...c(R.error||"Memory model returned empty text"),usage:I};let x=xe(A,n);return{status:"written",content:x.content,truncated:x.truncated,usage:I,modelId:s}}catch(u){let f=u instanceof Error?u.message:"Memory update failed";return console.error("Memory update failed:",u),c(f)}}async function ze(t,e){var n,s;let r=(n=e==null?void 0:e.flowData)==null?void 0:n.flowId;if(!(t!=null&&t.HX_CORE_URL)||!r)return{engineState:e,refreshed:!1};try{let a=await C(r,t),o={...e,flowData:{...a,tenant:e.flowData.tenant,flowId:r,chatId:e.flowData.chatId}},i=a==null?void 0:a.stateVersion,c=typeof i=="number"&&i!==((s=e.flowData)==null?void 0:s.stateVersion);return{engineState:o,refreshed:c}}catch(a){return console.error(`[flowRefresh] fetch failed for flow ${r}:`,a),{engineState:e,refreshed:!1}}}function Ge(t,e){return!t||!t.HX_ORA_URL||!t.HX_API_KEY?Promise.resolve():fetch(`${t.HX_ORA_URL}/internal/sessions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t.HX_API_KEY},body:JSON.stringify(e)}).catch(r=>{console.error("[sessionIndex] failed to index session",r)})}var Je=async(t,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),`${JSON.stringify(t)}`};async function N(t,e){var a;let r=t.id||t.name||"",[n,s]=String(r).split("::");if(!n||!s)return null;try{let i=(a=(await b(n,e)).metadata)==null?void 0:a.tenant,l={flowData:{...await C(n,e),tenant:i,flowId:n,chatId:s},executedNodes:[],context:{}};return t.setState({...t.state,engineState:l}),l}catch(o){return console.error("Failed to initialize engine state:",o),null}}async function Ot(t,e,r){var n;if(e&&t.HX_CORE_URL&&t.HX_API_KEY)try{let s=await b(e,t),a=(n=s==null?void 0:s.metadata)==null?void 0:n.org;if(typeof a=="string"&&a.trim())return X(a)}catch(s){console.warn(`[secrets] could not read org for flow ${e}`,s)}return X(r)}async function D(t){var ne,re,se,oe,ae,ie,ce,le,ue,de,pe;let{agent:e,env:r,ctx:n,payload:s,connection:a}=t,o=Date.now(),i=[],c=t.runId?Ce():void 0,l=async()=>await O(e),u=async p=>{await Le(e,p)},f=async p=>{if(e.state.modelsCache&&e.state.modelsCache[p])return e.state.modelsCache[p];try{let{fetchOraModel:h}=await import("./oraApi-YIJGMXX7.js"),T=await h(p,r);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[p]:T}}),T}catch(h){throw console.error(`Error fetching model ${p}:`,h),h}},m={id:bt(),role:"user",type:"text",content:s.text,images:s.images,ts:Date.now()};await u(m);let d={onChangeState:p=>{e.setState({...e.state,engineState:p})},onServerEvent:async p=>{var h;await((h=t.onServerEvent)==null?void 0:h.call(t,p)),i.push(p)},onTelemetry:async p=>{var _,me,fe,ge,ye,he;let h=t.user,T=typeof(h==null?void 0:h.org)=="string"&&h.org.trim()?h.org.trim():"default";await Je({...p,userId:t.resolveUserId(),tenant:((me=(_=e.state.engineState)==null?void 0:_.flowData)==null?void 0:me.tenant)||"",org:T,flowId:((ge=(fe=e.state.engineState)==null?void 0:fe.flowData)==null?void 0:ge.flowId)||"",sessionId:((he=(ye=e.state.engineState)==null?void 0:ye.flowData)==null?void 0:he.chatId)||""},r)},onError:p=>{var h;(h=t.onError)==null||h.call(t,p),e.setState({...e.state,error:p})},shouldStop:t.shouldStop},g=e.state.engineState?{...e.state.engineState}:null;if(g){let{engineState:p,refreshed:h}=await ze(r,g);g=p,h&&e.setState({...e.state,engineState:g,modelsCache:{}})}else if(g=await N(e,r),!g){let p="Failed to initialize agent";return d.onError(p),{status:"failed",error:p}}let y=t.user??void 0,w=(ne=g.flowData)==null?void 0:ne.tenant,R=await Ot(r,(re=g.flowData)==null?void 0:re.flowId,y==null?void 0:y.org),I=w?await Xe(r,w,R):{};(se=t.onSecretsLoaded)==null||se.call(t,I),g={...g,context:{...g.context||{},user:y}},e.setState({...e.state,user:y,engineState:g});let A={env:r,ctx:n,conn:a,getMessages:l,setMessages:u,getOraModel:f,secrets:I,userAuth:t.userAuth,user:y,composioSessions:t.composioSessions,publicOrigin:t.publicOrigin,skillRefCache:t.skillRefCache,runId:t.runId,outputCollector:c,agentMemory:typeof((oe=e.state.memory)==null?void 0:oe.content)=="string"?e.state.memory.content:"",shouldStop:t.shouldStop,workerStack:(ae=g.flowData)!=null&&ae.flowId?[g.flowData.flowId]:[],workerCalls:{count:0}},x=await Fe(A,g,d)(s),S=e.state.engineState??g;if(x.status==="completed")try{let p=await Ve({sessionEnv:A,engineState:S,previousContent:typeof((ie=e.state.memory)==null?void 0:ie.content)=="string"?e.state.memory.content:"",userText:s.text||"",messages:await l()});if(p.status==="skipped")await d.onServerEvent({type:"agent:memory",content:{skipped:!0,reason:p.reason},timestamp:Date.now()});else if(!p.content.trim())await d.onServerEvent({type:"agent:memory",content:{updated:!1,empty:!0,error:p.error,fallback:p.fallback},timestamp:Date.now()});else{let h={promptTokens:((ce=S.tokenUsage)==null?void 0:ce.promptTokens)??0,completionTokens:((le=S.tokenUsage)==null?void 0:le.completionTokens)??0,totalTokens:((ue=S.tokenUsage)==null?void 0:ue.totalTokens)??0};p.usage&&(h.promptTokens+=p.usage.promptTokens,h.completionTokens+=p.usage.completionTokens,h.totalTokens+=p.usage.totalTokens),S={...S,tokenUsage:h},e.setState({...e.state,engineState:S,memory:{content:p.content,updatedTs:Date.now(),...p.error?{lastError:p.error}:{},...p.fallback?{fallback:!0}:{}}}),await d.onTelemetry({type:"memory_update",payload:{model:p.modelId,truncated:p.truncated,usage:p.usage,fallback:p.fallback,error:p.error}}),await d.onServerEvent({type:"agent:memory",content:{updated:!0,truncated:p.truncated,fallback:p.fallback,error:p.error},timestamp:Date.now()})}}catch(p){let h=p instanceof Error?p.message:"Memory update failed";console.error("Memory update failed:",p),await d.onServerEvent({type:"agent:memory",content:{error:h},timestamp:Date.now()})}if(x.status==="completed"&&t.runId&&(c!=null&&c.hasOutputs())){let{flowId:p,chatId:h}=S.flowData??{};if(!p||!h)x={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await Pe(r,{flowId:p,sessionId:h,runId:t.runId,createdAt:new Date(o).toISOString(),data:c.snapshotData(),answerNodeIds:c.answerNodeIds()});let T={...S.results||{}};for(let _ of c.answerNodeIds())T[_]={...T[_]||{},persisted:!0,runId:t.runId};S={...S,results:T},e.setState({...e.state,engineState:S})}catch(T){let _=T instanceof Error?T.message:"Structured output persistence failed";d.onError(_),await d.onServerEvent({type:"error:answer-output",content:{runId:t.runId,error:_},timestamp:Date.now()}),x={status:"failed",error:_}}}let{tenant:$,flowId:G,chatId:J}=S.flowData??{},ut=(de=S.flowData)==null?void 0:de.org;return $&&G&&J&&n.waitUntil(Ge(r,{id:`${G}::${J}`,tenant:$,org:ut,flowId:G,sessionId:J,userId:t.resolveUserId(),title:(pe=s.text)==null?void 0:pe.slice(0,120),turnTs:o,events:i})),e.setState({...e.state,lastUpdated:new Date}),{status:x.status,error:x.error,engineState:S}}import{nanoid as vt}from"nanoid";function Ct(t){let e=t.headers.get("X-User-Payload");if(!e)return null;try{let r=JSON.parse(e),n=typeof(r==null?void 0:r.email)=="string"?P(r.email):null;return n?{...r,email:n}:null}catch{return null}}async function We(t,e,r,n){var s;try{let a=await e.json(),o=a.message;if(!o||typeof o!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let i=typeof a.userId=="string"?P(a.userId):null,c=Ct(e),l=c==null?void 0:c.email;c?t.setState({...t.state,user:c,injectedUserId:l}):i&&!((s=t.state.user)!=null&&s.email)&&t.setState({...t.state,injectedUserId:i});let u=()=>l??i??t.state.injectedUserId??void 0;t.skillRefCache||(t.skillRefCache=new Map);let f=a.inputs&&typeof a.inputs=="object"?a.inputs:void 0;if(!t.state.engineState&&!await N(t,r))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let m=`run-${vt(12)}`;await t.registerManualRun(m,o,u()),await M(r,m).catch(w=>{console.warn(`[AgentHTTP] could not mark manual run ${m} as running`,w)});let d;try{d=await D({agent:t,env:r,ctx:n,payload:{text:o,inputs:f},skillRefCache:t.skillRefCache,user:c??void 0,resolveUserId:u,runId:m,shouldStop:()=>t.isRunStopRequested(m)}),n.waitUntil(t.completeManualRun(m,d.status==="completed"?"succeeded":d.status==="stopped"?"skipped":"failed",d.error))}finally{await t.clearRunStopRequest(m)}if(d.status==="failed")return new Response(JSON.stringify({error:d.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});if(d.status==="stopped")return new Response(JSON.stringify({error:d.error||"Stopped by user"}),{status:409,headers:{"content-type":"application/json"}});let y=(await O(t)).reverse().find(w=>w.role==="assistant");return new Response(JSON.stringify({answer:(y==null?void 0:y.content)||""}),{headers:{"content-type":"application/json"}})}catch(a){return new Response(JSON.stringify({error:a.message}),{status:500,headers:{"content-type":"application/json"}})}}async function Ye(t){try{return await H(t),t.skillRefCache&&t.skillRefCache.clear(),t.setState({...t.state,error:"",engineState:void 0,modelsCache:{},lastUpdated:new Date}),new Response(JSON.stringify({success:!0,messages:[]}),{headers:{"content-type":"application/json"}})}catch(e){return new Response(JSON.stringify({error:e.message}),{status:500,headers:{"content-type":"application/json"}})}}var Qe="trigger:nonce:",Mt=900*1e3,ee="run:stop:",Ze=class extends Be{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{},memory:void 0};constructor(e,r){super(e,r),this.requireStateValidation()}validateStateChange(e,r){if(r!=="server")throw new Error("Client state updates are forbidden")}requireStateValidation(){if(typeof Be.prototype.validateStateChange!="function")throw new Error("AgentDO requires agents >= 0.8.7 with validateStateChange; upgrade the tenant SDK")}resolveSessionUserId(){return this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async inspectPersistedSession(e){return e==="state"?{state:this.state}:e==="memory"?{memory:this.state.memory??null}:{messages:await O(this)}}async requestRunStop(e){return e!=null&&e.trim()?(await this.ctx.storage.put(`${ee}${e}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(e){return!!await this.ctx.storage.get(`${ee}${e}`)}async clearRunStopRequest(e){await this.ctx.storage.delete(`${ee}${e}`)}async onRequest(e){this.requireStateValidation();let r=new URL(e.url);if(r.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(r.pathname.endsWith("/history")){let n=await O(this);return new Response(JSON.stringify(n),{headers:{"content-type":"application/json"}})}return e.method==="POST"&&r.pathname.endsWith("/message")?We(this,e,this.env,this.ctx):e.method==="DELETE"&&r.pathname.endsWith("/clear")?Ye(this):new Response("Ready to assist.")}async onConnect(e,r){var m,d,g,y,w;this.requireStateValidation();let[n,s]=e.server.split("::"),o=(m=(await b(n,this.env)).metadata)==null?void 0:m.tenant;this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let i=null;if(r.request){try{this.publicOrigin=new URL(r.request.url).origin}catch{}let R=r.request.headers.get("X-User-Payload");if(R)try{i=JSON.parse(R)}catch(I){console.warn("Failed to parse X-User-Payload",I)}}e.setState({...e.state,authorizedUser:i});let c=await C(n,this.env);this.setState({...this.state,user:i||null,sessionId:s,engineState:{flowData:{...c,tenant:o,flowId:n,chatId:s},executedNodes:[],context:i?{user:i}:{}}}),i||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let l=await O(this);k(e,E.SERVER_HISTORY,JSON.stringify({messages:l}));let f=(((d=c==null?void 0:c.state)==null?void 0:d.nodes)??(c==null?void 0:c.nodes)??[]).find(R=>R.type==="startNode");if(f){let R={allow_images:((g=f.data)==null?void 0:g.allow_images)??!1,allow_documents:((y=f.data)==null?void 0:y.allow_documents)??!1,greeting:(w=f.data)==null?void 0:w.greeting};k(e,E.SERVER_CONFIG,JSON.stringify(R))}}async onMessage(e,r){if(typeof r!="string")return;let n=r.indexOf(":");if(n===-1)return;let s=r.substring(0,n),a=r.substring(n+1);if(!s||!a)return;let i={[E.USER_MESSAGE]:c=>this.onUserMessage(e,c),[E.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[E.USER_AUTH]:c=>this.onUserAuth(e,c),[E.USER_IDENTITY]:c=>this.onUserIdentity(e,c)}[s];i&&await i(a)}async onUserMessage(e,r){var i;let n=Ee(r),s=((i=e.state)==null?void 0:i.authorizedUser)??void 0,a=()=>(s==null?void 0:s.email)??this.resolveSessionUserId(),o=`run-${Pt(12)}`;await this.registerManualRun(o,n.text,a()),await M(this.env,o).catch(c=>{console.warn(`[AgentDO] could not mark manual run ${o} as running`,c)});try{let c=await D({agent:this,env:this.env,ctx:this.ctx,payload:n,connection:e,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:s,resolveUserId:a,runId:o,shouldStop:()=>this.isRunStopRequested(o),onServerEvent:l=>{k(e,E.SERVER_EVENT,JSON.stringify(l))},onError:l=>{k(e,E.SERVER_ERROR,l)},onSecretsLoaded:l=>{this.secrets=l}});this.ctx.waitUntil(this.completeManualRun(o,c.status==="completed"?"succeeded":c.status==="stopped"?"skipped":"failed",c.error))}finally{await this.clearRunStopRequest(o)}}registerManualRun(e,r,n){var c;let{tenant:s,flowId:a,chatId:o}=((c=this.state.engineState)==null?void 0:c.flowData)??{};if(!s||!a||!o)return Promise.resolve();let i=je(n||this.resolveSessionUserId(),o);return Ke(this.env,{id:e,tenant:s,flowId:a,userId:i,sessionId:o,label:r==null?void 0:r.slice(0,120)})}completeManualRun(e,r,n){return K(this.env,e,{status:r,error:n})}async enqueueTrigger(e){var s;if(!(e!=null&&e.runId)||!(e!=null&&e.flowId))return{queued:!1};if(e.nonce&&!await this.claimTriggerNonce(e.nonce))return console.warn(`[AgentDO] rejected replayed trigger nonce ${e.nonce}`),{queued:!1,duplicate:!0};let r=e.runAsUserId;return r&&!((s=this.state.user)!=null&&s.email)&&this.state.injectedUserId!==r&&this.setState({...this.state,injectedUserId:r}),{queued:!0,taskId:await this.queue("processTrigger",e)}}async claimTriggerNonce(e){let r=`${Qe}${e}`;if(await this.ctx.storage.get(r))return!1;let n=Date.now();await this.ctx.storage.put(r,n);let a=[...(await this.ctx.storage.list({prefix:Qe})).entries()].filter(([,o])=>n-o>Mt).map(([o])=>o);return a.length>0&&await this.ctx.storage.delete(a),!0}async processTrigger(e){if(!(await M(this.env,e.runId)).claimed){console.warn(`[AgentDO] activation ${e.activationId} skipped \u2014 run ${e.runId} already claimed`);return}try{this.state.engineState||await N(this,this.env);let n=Re(q(this.state.engineState)),s=Se(n,e.inputs||{},e.label),a=await D({agent:this,env:this.env,ctx:this.ctx,payload:{text:s,inputs:e.inputs||{}},composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>e.runAsUserId||this.resolveSessionUserId(),runId:e.runId,shouldStop:()=>this.isRunStopRequested(e.runId),onSecretsLoaded:o=>{this.secrets=o}});await K(this.env,e.runId,{status:a.status==="completed"?"succeeded":a.status==="stopped"?"skipped":"failed",error:a.error})}catch(n){let s=n instanceof Error?n.message:"Trigger execution failed";throw await K(this.env,e.runId,{status:"failed",error:s}),n}finally{await this.clearRunStopRequest(e.runId)}}async onUserIdentity(e,r){let n=P(r);if(!n){k(e,E.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:n}),k(e,E.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,r){let n=Ie(r);if(!n){k(e,E.SERVER_ERROR,"Invalid auth payload");return}let s=n.value.trim();s===""?delete this.userAuth[n.name]:this.userAuth[n.name]=n.value,k(e,E.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:n.name,set:s!==""}}))}async onClearHistory(e){await H(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear(),this.setState({...this.state,error:"",engineState:this.state.engineState,memory:this.state.memory,modelsCache:{},lastUpdated:new Date}),e&&k(e,E.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await He(this);let e=await O(this);`${JSON.stringify(e)}`}async onClose(e,r,n,s){console.log(`Session closed: ${this.state.sessionId} ${r} - ${n}`)}async onError(e){console.error("AgentDO encountered an error:",e)}};function ds(t){let e=t.state;if(!e)return null;let r=["startNode","answerNode"];for(let n of r)if(!e.nodes.some(a=>a.type===n))return!1;return e.nodes.find(n=>n.type==="startNode")}import{importSPKI as Nt,jwtVerify as Dt}from"jose";function V(t){let e={};if(!t)return e;let r=t.split(";");for(let n of r){let s=n.indexOf("=");if(s>-1){let a=n.slice(0,s).trim(),o=n.slice(s+1).trim();a&&(e[a]=decodeURIComponent(o))}}return e}function $t(t){return(typeof t.email=="string"?t.email.trim():"")||null}async function v(t,e,r){let n=V(t.headers.get("cookie")),s=new URL(t.url),a=n.access_token||s.searchParams.get("access_token"),o=await Ft(e,a);if(o.ok){let i=o.payload,c=$t(i);return c?{id:i.sub,email:c,name:i.name,first_name:i.given_name,last_name:i.family_name,tenant:i.tenant,org:typeof i.org=="string"?i.org:null,roles:i["ora-roles"],db_name:i.db_name||null,user_id:i.user_id||null}:null}return null}async function Ft(t,e){if(!e||typeof e!="string")return{ok:!1,payload:null,protectedHeader:null};if(!t.KC_RS256_PK)throw new Error("PK is not defined");let r=`-----BEGIN PUBLIC KEY-----
6
6
  ${t.KC_RS256_PK}
7
- -----END PUBLIC KEY-----`,n=await Nt(r,"RS256");try{let{payload:s,protectedHeader:o}=await Dt(e,n);return{ok:!0,payload:s,protectedHeader:o}}catch(s){return console.error("JWT verification failed:",s),{ok:!1,payload:null,protectedHeader:null}}}async function hs(t,e,r){let n=new URL(t.url);if(n.pathname==="/favicon.ico")return new Response(null,{status:204});if(n.pathname.startsWith("/.well-known/appspecific"))return new Response(null,{status:204})}import{getAgentByName as z}from"agents";import{getAgentByName as Lt}from"agents";async function et(t,e){let r=e.sessionId||e.runAsUserId,n=e.inputs||{},s=e.runId;if(!s){let c=await B(t,{tenant:e.tenant,flowId:e.flowId,userId:e.runAsUserId,sessionId:r,triggerId:e.triggerId,triggerKind:e.triggerKind,invocationMode:e.invocationMode,activationId:e.activationId,deliveryId:void 0,externalDeliveryId:e.externalDeliveryId,correlationKey:e.correlationKey,inputs:n,label:e.label});if(!c)return{status:"error",error:"Failed to register run"};if(!c.created&&c.run.status!=="queued")return{status:"deduped",runId:c.run.id};s=c.run.id}let o={...e,sessionId:r,runId:s,inputs:n},i=await(await Lt(t.AGENT,`${e.flowId}::${r}`)).enqueueTrigger(o);return i.duplicate?{status:"deduped",runId:s}:i.queued?{status:"queued",runId:s,activation:o,taskId:i.taskId}:{status:"error",error:"Failed to queue trigger"}}var nt="x-ora-signature",rt="x-ora-timestamp",st="x-ora-nonce",ot="x-ora-tenant",Is=300,tt=new TextEncoder;function Ht(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function Kt(t){try{let e=new URL(t);return`${e.origin}${e.pathname.replace(/\/$/,"")}`}catch{return t.replace(/\/$/,"")}}function at(t){return["v1",t.timestamp,t.nonce,t.tenant,Kt(t.destination),t.body].join(`
8
- `)}async function it(t,e){let r=await crypto.subtle.importKey("raw",tt.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return Ht(await crypto.subtle.sign("HMAC",r,tt.encode(e)))}function jt(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t.charCodeAt(n)^e.charCodeAt(n);return r===0}async function xs(t){let e=String(t.timestamp??Math.floor(Date.now()/1e3)),r=await it(t.secret,at({timestamp:e,nonce:t.nonce,tenant:t.tenant,destination:t.destination,body:t.body}));return{"content-type":"application/json",[ot]:t.tenant,[rt]:e,[st]:t.nonce,[nt]:`v1=${r}`}}async function ct(t){var d,m,h,R,u;if(!((d=t.secret)!=null&&d.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(m=t.headers.get(ot))==null?void 0:m.trim(),r=(h=t.headers.get(rt))==null?void 0:h.trim(),n=(R=t.headers.get(st))==null?void 0:R.trim(),s=(u=t.headers.get(nt))==null?void 0:u.trim();if(!e||!r||!n||!s)return{ok:!1,error:"missing signature headers"};if(!s.startsWith("v1="))return{ok:!1,error:"unsupported signature version"};let o=Number(r);if(!Number.isFinite(o))return{ok:!1,error:"invalid timestamp"};let a=Math.floor((t.now??Date.now())/1e3),i=t.toleranceSeconds??300;if(Math.abs(a-o)>i)return{ok:!1,error:"stale timestamp"};let c=await it(t.secret.trim(),at({timestamp:r,nonce:n,tenant:e,destination:t.url,body:t.body}));return jt(s.slice(3),c)?{ok:!0,tenant:e,nonce:n,timestamp:o}:{ok:!1,error:"signature mismatch"}}var U=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}});async function lt(t,e,r){var d;if(new URL(t.url).pathname!=="/api/triggers/dispatch")return;if(t.method!=="POST")return U({error:"Method not allowed"},405);let s=await t.text(),o=await ct({secret:e.HX_API_KEY,body:s,url:t.url,headers:t.headers});if(!o.ok)return console.warn(`[triggers] rejected dispatch: ${o.error}`),U({error:"Invalid signature"},401);let a;try{a=JSON.parse(s)}catch{return U({error:"Invalid payload"},400)}if(!(a!=null&&a.runId)||!(a!=null&&a.flowId)||!(a!=null&&a.runAsUserId)||!(a!=null&&a.tenant)||!(a!=null&&a.activationId)||!(a!=null&&a.triggerId)||!(a!=null&&a.triggerKind)||!(a!=null&&a.invocationMode))return U({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(a.tenant!==o.tenant)return U({error:"Tenant mismatch"},403);let i;try{i=await O(a.flowId,e)}catch{return U({error:"Flow not found"},404)}if(!((d=i==null?void 0:i.metadata)!=null&&d.tenant)||i.metadata.tenant!==a.tenant)return console.warn(`[triggers] flow ${a.flowId} does not belong to tenant ${a.tenant}`),U({error:"Tenant mismatch"},403);let c=await et(e,{...a,sessionId:a.sessionId||a.runAsUserId,nonce:o.nonce});return c.status==="error"?U({error:c.error},502):c.status==="deduped"?U({deduped:!0,runId:c.runId},200):U({accepted:!0,runId:c.runId,taskId:c.taskId},202)}var Xt=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,qt=new Set(["state","messages","memory"]);async function Vt(t,e){let r=new URL(t.url);if(!r.pathname.startsWith("/api/internal/sessions/"))return;let n=r.pathname.split("/");if(n[6]!=="runs"||n[8]!=="stop"||n.length!==9)return;if(t.method!=="POST")return new Response("Method not allowed",{status:405});if(!e.HX_API_KEY||t.headers.get("Authorization")!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=decodeURIComponent(n[4]||""),o=decodeURIComponent(n[5]||""),a=decodeURIComponent(n[7]||"");if(!s||!o||!a)return new Response("Not found",{status:404});try{let i=await z(e.AGENT,`${s}::${o}`);return Response.json(await i.requestRunStop(a))}catch(i){return console.error("[agents] failed to request run stop",i),Response.json({error:"Failed to stop run"},{status:502})}}async function Gt(t,e){let r=new URL(t.url);if(!r.pathname.startsWith("/api/internal/sessions/"))return;if(t.method!=="GET")return new Response("Method not allowed",{status:405});let n=t.headers.get("Authorization")||"";if(!e.HX_API_KEY||n!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=r.pathname.split("/"),o=decodeURIComponent(s[4]||""),a=decodeURIComponent(s[5]||""),i=s[6];if(!o||!a||!i||!qt.has(i))return new Response("Not found",{status:404});try{let d=await(await z(e.AGENT,`${o}::${a}`)).inspectPersistedSession(i);return Response.json(d)}catch(c){return console.error("[agents] failed to inspect persisted session",c),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function Ps(t,e,r){var i,c,d,m,h,R;let n=new URL(t.url),s=await lt(t,e,r);if(s instanceof Response)return s;let o=await Vt(t,e);if(o instanceof Response)return o;let a=await Gt(t,e);if(a instanceof Response)return a;if(n.pathname.startsWith("/a/")){let u=n.pathname.split("/"),p=u[2],g=u[3];try{if(!p)return Response.redirect(new URL("/",n.origin).toString(),302);let f;try{f=await O(p,e)}catch{return new Response("Flow not found",{status:404})}if(!f.metadata||((i=f.metadata)==null?void 0:i.status)!=="active"&&((c=f.metadata)==null?void 0:c.status)!=="activo")return new Response("NO chat",{status:404});if(((d=f.metadata)==null?void 0:d.visibility)!=="public"){let y=await C(t,e,r);if(!y){let I=new URL("/login",n.origin);return I.searchParams.set("nextURL",`${n.pathname}${n.search}`),Response.redirect(I.toString(),302)}let E=((m=f.metadata)==null?void 0:m.org)||"default",x=typeof y=="object"&&(y==null?void 0:y.org)||"default";if(E!==x)return new Response("Forbidden",{status:403})}if(!g){let y=crypto.randomUUID(),E=new URL(`/a/${p}/${y}`,n.origin);return Response.redirect(E.toString(),302)}if(!Xt.test(g))return new Response("Id del chat no v\xE1lido",{status:400})}catch(f){return console.error("Error accessing flow KV:",f),new Response("Flow error",{status:500})}}if(n.pathname.startsWith("/api/agent/flow")){let u=n.pathname.split("/"),p=u[4],g=u[5],f=`${p}::${g}`;try{let y=await C(t,e,r);if(!y){let v=new URL(t.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${v}) \u2014 Composio connections from tool editor will not apply`)}let E=new Headers(t.headers);E.delete("X-User-Payload"),y&&E.set("X-User-Payload",JSON.stringify(y));let x=new Request(t,{headers:E});return(await z(e.AGENT,f)).fetch(x)}catch(y){return console.error("Error accessing agent:",y),new Response("Agent error",{status:500})}}if(n.pathname.startsWith("/api/ora/connect")){let u=n.pathname.split("/"),p=u[4],g=u[5];if(!p||!g)return new Response("Missing flowId or sessionId",{status:400});let f=t.headers.get("Authorization")||n.searchParams.get("authorization");if(!f)return new Response("Missing Authorization header",{status:401});try{let y=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${p}`,x=await(await fetch(y,{method:"GET",headers:{Authorization:f}})).json();if(((h=x.payload)==null?void 0:h.flowId)!==p)return console.error("FlowId mismatch:",(R=x.payload)==null?void 0:R.flowId,"!==",p),new Response("Validation error",{status:403});let I=`${p}::${g}`,S=await C(t,e,r);if(!S){let H=new URL(t.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${H}) \u2014 Composio connections from tool editor will not apply`)}let v=new Headers(t.headers);v.delete("X-User-Payload"),S&&v.set("X-User-Payload",JSON.stringify(S));let M=new Request(t,{headers:v});return(await z(e.AGENT,I)).fetch(M)}catch(y){return console.error("Error in /api/ora/connect:",y),new Response("Internal error",{status:500})}}}async function Ds(t,e,r){let n=new URL(t.url),s=t.method;if(!n.pathname.startsWith("/api/instances"))return;let o=await C(t,e,r);if(!o)return new Response("Unauthorized",{status:401});let a=e.HX_CORE_URL,i=e.HX_API_KEY;if(!a||!i)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let d=n.pathname.slice("/api/instances".length);d.startsWith("/")&&(d=d.slice(1)),d.endsWith("/")&&(d=d.slice(0,-1));let m="/ora/instances";d&&(m+=`/${d}`);let h=a.endsWith("/")?a.slice(0,-1):a,R=new URL(`${h}${m}`);n.searchParams.forEach((g,f)=>{R.searchParams.set(f,g)}),s==="GET"&&!d&&R.searchParams.set("filter_user_id",o.email);let u=new Headers;u.set("Authorization",i),u.set("Content-Type","application/json"),u.set("X-User-Payload",JSON.stringify(o));let p={method:s,headers:u};if(["POST","PATCH","PUT"].includes(s))try{p.body=await t.text()}catch(g){console.error("Error reading request body:",g)}try{let g=await fetch(R.toString(),p),f=await g.text();return new Response(f,{status:g.status,headers:{"Content-Type":"application/json"}})}catch(g){return console.error("Error proxying to flow instance backend:",g),new Response("Internal Server Error",{status:500})}}async function Ls(t,e,r){let n=new URL(t.url);if(t.method==="POST"&&n.pathname==="/auth/login")try{let s=await t.formData(),o=s.get("username"),a=s.get("password"),i=s.get("nextURL")||"/";if(!o||!a)return new Response("Missing username or password",{status:400});let c=new URLSearchParams;c.append("username",o),c.append("password",a),c.append("grant_type","password"),c.append("client_id",e.KC_CLIENT_ID),c.append("client_secret",e.KC_CLIENT_SECRET);let d=await fetch(`${e.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:c});if(!d.ok)return new Response("Unauthorized",{status:401});let m=await d.json(),h=new Response(null,{status:302,headers:{Location:i}}),u=n.protocol==="https:"?"; Secure":"",p=(g,f,y)=>{h.headers.append("Set-Cookie",`${g}=${f}; Path=/; HttpOnly${u}; SameSite=Lax; Max-Age=${y}`)};return m.access_token&&p("access_token",m.access_token,m.expires_in),m.refresh_token&&p("refresh_token",m.refresh_token,m.refresh_expires_in||3600*24*30),m.id_token&&p("id_token",m.id_token,m.expires_in),h}catch(s){return console.error("Auth error:",s),new Response("Internal Server Error",{status:500})}if(n.pathname==="/auth/logout"){let s=new Response(null,{status:302,headers:{Location:"/login"}}),o=a=>{s.headers.append("Set-Cookie",`${a}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return o("access_token"),o("refresh_token"),o("id_token"),s}if(n.pathname.startsWith("/s/")){let s=await C(t,e,r);if(!s){let o=new URL("/login",n.origin);return o.searchParams.set("nextURL",`${n.pathname}${n.search}`),Response.redirect(o.toString(),302)}return{user:s}}}export{dt as ANONYMOUS_RUN_USER_PREFIX,Qe as AgentDO,Fn as CRAWL_DEFAULTS,Ln as CRAWL_LIMITS,an as DEFAULT_MEMORY_LENGTH,cn as DEFAULT_MEMORY_MODEL,tn as FLOW_INPUT_NAME_RE,ur as FlowExecutionStoppedError,qn as GENERATION_PARAM_KEYS,Gn as GENERATION_PRESETS,rn as MAX_USER_IDENTITY_LENGTH,sn as MEMORY_LENGTH_MD_LINES,on as MEMORY_LENGTH_TOKENS,dr as MODEL_REGISTRY_SNAPSHOT,K as NodeType,dn as OUT_VAR_NAME_RE,Vn as PRESET_PARAM_KEYS,rr as REASONING_EFFORT_LEVELS,Dn as TENANT_ONLY_NODES,lr as TOOL_REGISTRY_SNAPSHOT,st as TRIGGER_NONCE_HEADER,nt as TRIGGER_SIGNATURE_HEADER,Is as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,ot as TRIGGER_TENANT_HEADER,rt as TRIGGER_TIMESTAMP_HEADER,Tn as VariableResolutionError,Wn as applyPresetToOverrides,Hn as buildCrawlRequestBody,De as buildReasoningProviderOptions,hn as buildScope,xs as buildSignedTriggerHeaders,Se as buildTriggerMessageText,Yt as buildUrl,$t as canonicalUserEmail,Te as capMemoryContent,D as claimRun,X as clearAllMessages,V as completeRun,Jt as convertTempMessure,Kn as crawlRequestKey,B as createRun,Jn as deriveParamSupport,et as dispatchTrigger,Zt as embedText,He as ensureAgentTables,ut as ensureMessagesTable,un as estimateTokens,Un as extractOutVarValues,vn as extractTemplateReferences,be as extractUserKeypoints,wn as findScopedSourceNode,b as getAllMessages,fn as getAncestorNodeIds,mn as getDefaultOutVars,gn as getEffectiveOutVars,Re as getFlowInputDefs,mr as getModelEntry,Rn as getRefTail,yn as getUpstreamOutVars,Ps as handleAgentsRoutes,Ls as handleAuthRoutes,hs as handleCommonRoutes,Ds as handleIntancesRoutes,Gt as handlePersistedSessionInspection,Vt as handleSessionRunControl,lt as handleTriggerRoutes,Qt as hashText,$ as initializeEngineState,Sn as isBinaryOutVar,En as isJsonContentType,$n as isNodeTypeAllowedForTenant,ke as isStartMemoryEnabled,Nn as jsonSchemaToZod,we as logc,Oe as looksLikeTranscript,_e as memoryGenerationMaxTokens,j as memoryMdLineLimit,xe as memoryTokenLimit,ve as mergeKeypointMemory,T as messageTypes,Kt as normalizeDestination,Bn as normalizeEffectiveParams,nn as normalizeFlowInputs,ir as normalizeModelEntry,sr as normalizeReasoning,Zn as openAiReasoningParamSupport,Qn as openAiStandardParamSupport,Ze as parseCookies,ln as parseMemoryLength,In as parsePayloadText,bn as parseTemplateExpression,Ie as parseUserAuth,Ee as parseUserMessage,Yn as pickNodeOverrides,xn as readFetchPayload,or as reasoningEffortLevels,ar as reasoningExposable,je as recordRun,cr as registerProvider,Mn as resolveAnswerMappings,$e as resolveModelById,On as resolveOutVarRef,An as resolveOutVarValue,zn as resolvePreset,Ne as resolveReasoningEffort,_n as resolveReference,Ke as resolveRunUserId,Pn as resolveTemplate,Cn as rewriteTemplateNodeRefs,F as runAgentTurn,Xn as runCrawl,Wt as safeParseJSON,W as sanitizeMemoryDocument,N as sanitizeUserIdentity,ze as sendEvent,A as serverSend,Le as setMessage,jn as shapeCrawlOutput,it as signTriggerMaterial,Fe as startEngine,Ue as startMemoryLength,Ae as startMemoryModel,nr as stripUnsupportedFromNodeData,zt as tempTool,jt as timingSafeEqualHex,Me as toStreamTextSettings,at as triggerSignatureMaterial,Bt as twitter,ds as validateFlowStart,pn as validateOutVars,en as vectorize,Ft as verifyToken,ct as verifyTriggerRequest,C as verifyUser,kn as walkPath,tr as workersAiParamSupport,er as xaiParamSupport};
7
+ -----END PUBLIC KEY-----`,n=await Nt(r,"RS256");try{let{payload:s,protectedHeader:a}=await Dt(e,n);return{ok:!0,payload:s,protectedHeader:a}}catch(s){return console.error("JWT verification failed:",s),{ok:!1,payload:null,protectedHeader:null}}}async function hs(t,e,r){let n=new URL(t.url);if(n.pathname==="/favicon.ico")return new Response(null,{status:204});if(n.pathname.startsWith("/.well-known/appspecific"))return new Response(null,{status:204})}import{getAgentByName as z}from"agents";import{getAgentByName as Lt}from"agents";async function et(t,e){let r=e.sessionId||e.runAsUserId,n=e.inputs||{},s=e.runId;if(!s){let c=await B(t,{tenant:e.tenant,flowId:e.flowId,userId:e.runAsUserId,sessionId:r,triggerId:e.triggerId,triggerKind:e.triggerKind,invocationMode:e.invocationMode,activationId:e.activationId,deliveryId:void 0,externalDeliveryId:e.externalDeliveryId,correlationKey:e.correlationKey,inputs:n,label:e.label});if(!c)return{status:"error",error:"Failed to register run"};if(!c.created&&c.run.status!=="queued")return{status:"deduped",runId:c.run.id};s=c.run.id}let a={...e,sessionId:r,runId:s,inputs:n},i=await(await Lt(t.AGENT,`${e.flowId}::${r}`)).enqueueTrigger(a);return i.duplicate?{status:"deduped",runId:s}:i.queued?{status:"queued",runId:s,activation:a,taskId:i.taskId}:{status:"error",error:"Failed to queue trigger"}}var nt="x-ora-signature",rt="x-ora-timestamp",st="x-ora-nonce",ot="x-ora-tenant",Is=300,tt=new TextEncoder;function Ht(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function jt(t){try{let e=new URL(t);return`${e.origin}${e.pathname.replace(/\/$/,"")}`}catch{return t.replace(/\/$/,"")}}function at(t){return["v1",t.timestamp,t.nonce,t.tenant,jt(t.destination),t.body].join(`
8
+ `)}async function it(t,e){let r=await crypto.subtle.importKey("raw",tt.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return Ht(await crypto.subtle.sign("HMAC",r,tt.encode(e)))}function Kt(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t.charCodeAt(n)^e.charCodeAt(n);return r===0}async function Ts(t){let e=String(t.timestamp??Math.floor(Date.now()/1e3)),r=await it(t.secret,at({timestamp:e,nonce:t.nonce,tenant:t.tenant,destination:t.destination,body:t.body}));return{"content-type":"application/json",[ot]:t.tenant,[rt]:e,[st]:t.nonce,[nt]:`v1=${r}`}}async function ct(t){var l,u,f,m,d;if(!((l=t.secret)!=null&&l.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(u=t.headers.get(ot))==null?void 0:u.trim(),r=(f=t.headers.get(rt))==null?void 0:f.trim(),n=(m=t.headers.get(st))==null?void 0:m.trim(),s=(d=t.headers.get(nt))==null?void 0:d.trim();if(!e||!r||!n||!s)return{ok:!1,error:"missing signature headers"};if(!s.startsWith("v1="))return{ok:!1,error:"unsupported signature version"};let a=Number(r);if(!Number.isFinite(a))return{ok:!1,error:"invalid timestamp"};let o=Math.floor((t.now??Date.now())/1e3),i=t.toleranceSeconds??300;if(Math.abs(o-a)>i)return{ok:!1,error:"stale timestamp"};let c=await it(t.secret.trim(),at({timestamp:r,nonce:n,tenant:e,destination:t.url,body:t.body}));return Kt(s.slice(3),c)?{ok:!0,tenant:e,nonce:n,timestamp:a}:{ok:!1,error:"signature mismatch"}}var U=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}});async function lt(t,e,r){var l;if(new URL(t.url).pathname!=="/api/triggers/dispatch")return;if(t.method!=="POST")return U({error:"Method not allowed"},405);let s=await t.text(),a=await ct({secret:e.HX_API_KEY,body:s,url:t.url,headers:t.headers});if(!a.ok)return console.warn(`[triggers] rejected dispatch: ${a.error}`),U({error:"Invalid signature"},401);let o;try{o=JSON.parse(s)}catch{return U({error:"Invalid payload"},400)}if(!(o!=null&&o.runId)||!(o!=null&&o.flowId)||!(o!=null&&o.runAsUserId)||!(o!=null&&o.tenant)||!(o!=null&&o.activationId)||!(o!=null&&o.triggerId)||!(o!=null&&o.triggerKind)||!(o!=null&&o.invocationMode))return U({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(o.tenant!==a.tenant)return U({error:"Tenant mismatch"},403);let i;try{i=await b(o.flowId,e)}catch{return U({error:"Flow not found"},404)}if(!((l=i==null?void 0:i.metadata)!=null&&l.tenant)||i.metadata.tenant!==o.tenant)return console.warn(`[triggers] flow ${o.flowId} does not belong to tenant ${o.tenant}`),U({error:"Tenant mismatch"},403);let c=await et(e,{...o,sessionId:o.sessionId||o.runAsUserId,nonce:a.nonce});return c.status==="error"?U({error:c.error},502):c.status==="deduped"?U({deduped:!0,runId:c.runId},200):U({accepted:!0,runId:c.runId,taskId:c.taskId},202)}var Xt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function te(t,e,r,n,s,a=!1){let o=(m,d)=>({response:new Response(m,{status:d})});if(!/^[A-Za-z0-9_-]+$/.test(n))return o("Invalid flowId",400);if((!a||s)&&(!s||!Xt.test(s)))return o("Invalid sessionId",400);let i;try{i=await b(n,e)}catch{return o("Flow not found",404)}let c=i==null?void 0:i.metadata;if(!c||!["active","activo"].includes(c.status))return o("Flow not found",404);if(!e.TENANT||c.tenant!==e.TENANT)return o("Forbidden",403);let l=await v(t,e,r),u=l&&typeof l=="object"?l:void 0;if(u&&u.tenant!==e.TENANT)return o("Forbidden",403);if(c.visibility==="public")return{user:u};if(!u){if(!a)return o("Unauthorized",401);let m=new URL(t.url),d=new URL("/login",m.origin);return d.searchParams.set("nextURL",`${m.pathname}${m.search}`),{response:Response.redirect(d.toString(),302)}}if((c.org||"default")!==(u.org||"default"))return o("Forbidden",403);let f=V(t.headers.get("cookie")).access_token||new URL(t.url).searchParams.get("access_token");if(!f)return o("Unauthorized",401);try{let m=await fetch(`${e.HX_CORE_URL}/flows/${encodeURIComponent(n)}`,{headers:{Authorization:f},cache:"no-store"});if(!m.ok||(await m.json()).id!==n)return o("Forbidden",403)}catch{return o("Forbidden",403)}return{user:u}}var qt=new Set(["state","messages","memory"]);async function Vt(t,e){let r=new URL(t.url);if(!r.pathname.startsWith("/api/internal/sessions/"))return;let n=r.pathname.split("/");if(n[6]!=="runs"||n[8]!=="stop"||n.length!==9)return;if(t.method!=="POST")return new Response("Method not allowed",{status:405});if(!e.HX_API_KEY||t.headers.get("Authorization")!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=decodeURIComponent(n[4]||""),a=decodeURIComponent(n[5]||""),o=decodeURIComponent(n[7]||"");if(!s||!a||!o)return new Response("Not found",{status:404});try{let i=await z(e.AGENT,`${s}::${a}`);return Response.json(await i.requestRunStop(o))}catch(i){return console.error("[agents] failed to request run stop",i),Response.json({error:"Failed to stop run"},{status:502})}}async function zt(t,e){let r=new URL(t.url);if(!r.pathname.startsWith("/api/internal/sessions/"))return;if(t.method!=="GET")return new Response("Method not allowed",{status:405});let n=t.headers.get("Authorization")||"";if(!e.HX_API_KEY||n!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=r.pathname.split("/"),a=decodeURIComponent(s[4]||""),o=decodeURIComponent(s[5]||""),i=s[6];if(!a||!o||!i||!qt.has(i))return new Response("Not found",{status:404});try{let l=await(await z(e.AGENT,`${a}::${o}`)).inspectPersistedSession(i);return Response.json(l)}catch(c){return console.error("[agents] failed to inspect persisted session",c),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function $s(t,e,r){var i,c;let n=new URL(t.url),s=await lt(t,e,r);if(s instanceof Response)return s;let a=await Vt(t,e);if(a instanceof Response)return a;let o=await zt(t,e);if(o instanceof Response)return o;if(n.pathname.startsWith("/a/")){let l=n.pathname.split("/"),u=l[2],f=l[3];try{if(!u)return Response.redirect(new URL("/",n.origin).toString(),302);let m=await te(t,e,r,u,f,!0);if(m.response)return m.response;if(!f){let d=crypto.randomUUID(),g=new URL(`/a/${u}/${d}`,n.origin);return Response.redirect(g.toString(),302)}}catch(m){return console.error("Error accessing flow KV:",m),new Response("Flow error",{status:500})}}if(n.pathname.startsWith("/api/agent/flow/")){let l=n.pathname.split("/"),u=l[4],f=l[5],m=`${u}::${f}`;try{let d=await te(t,e,r,u,f);if(d.response)return d.response;let g=d.user,y=new Headers(t.headers);y.delete("X-User-Payload"),g&&y.set("X-User-Payload",JSON.stringify(g));let w=new Request(t,{headers:y});return(await z(e.AGENT,m)).fetch(w)}catch(d){return console.error("Error accessing agent:",d),new Response("Agent error",{status:500})}}if(n.pathname.startsWith("/api/ora/connect")){let l=n.pathname.split("/"),u=l[4],f=l[5];if(!u||!f)return new Response("Missing flowId or sessionId",{status:400});let m=t.headers.get("Authorization")||n.searchParams.get("authorization");if(!m)return new Response("Missing Authorization header",{status:401});try{let d=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${u}`,y=await(await fetch(d,{method:"GET",headers:{Authorization:m}})).json();if(((i=y.payload)==null?void 0:i.flowId)!==u)return console.error("FlowId mismatch:",(c=y.payload)==null?void 0:c.flowId,"!==",u),new Response("Validation error",{status:403});let w=`${u}::${f}`,R=await v(t,e,r);if(!R){let $=new URL(t.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${$}) \u2014 Composio connections from tool editor will not apply`)}let I=new Headers(t.headers);I.delete("X-User-Payload"),R&&I.set("X-User-Payload",JSON.stringify(R));let A=new Request(t,{headers:I});return(await z(e.AGENT,w)).fetch(A)}catch(d){return console.error("Error in /api/ora/connect:",d),new Response("Internal error",{status:500})}}}async function Hs(t,e,r){let n=new URL(t.url),s=t.method;if(!n.pathname.startsWith("/api/instances"))return;let a=await v(t,e,r);if(!a)return new Response("Unauthorized",{status:401});let o=e.HX_CORE_URL,i=e.HX_API_KEY;if(!o||!i)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let l=n.pathname.slice("/api/instances".length);l.startsWith("/")&&(l=l.slice(1)),l.endsWith("/")&&(l=l.slice(0,-1));let u="/ora/instances";l&&(u+=`/${l}`);let f=o.endsWith("/")?o.slice(0,-1):o,m=new URL(`${f}${u}`);n.searchParams.forEach((y,w)=>{m.searchParams.set(w,y)}),s==="GET"&&!l&&m.searchParams.set("filter_user_id",a.email);let d=new Headers;d.set("Authorization",i),d.set("Content-Type","application/json"),d.set("X-User-Payload",JSON.stringify(a));let g={method:s,headers:d};if(["POST","PATCH","PUT"].includes(s))try{g.body=await t.text()}catch(y){console.error("Error reading request body:",y)}try{let y=await fetch(m.toString(),g),w=await y.text();return new Response(w,{status:y.status,headers:{"Content-Type":"application/json"}})}catch(y){return console.error("Error proxying to flow instance backend:",y),new Response("Internal Server Error",{status:500})}}async function Xs(t,e,r){let n=new URL(t.url);if(t.method==="POST"&&n.pathname==="/auth/login")try{let s=await t.formData(),a=s.get("username"),o=s.get("password"),i=s.get("nextURL")||"/";if(!a||!o)return new Response("Missing username or password",{status:400});let c=new URLSearchParams;c.append("username",a),c.append("password",o),c.append("grant_type","password"),c.append("client_id",e.KC_CLIENT_ID),c.append("client_secret",e.KC_CLIENT_SECRET);let l=await fetch(`${e.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:c});if(!l.ok)return new Response("Unauthorized",{status:401});let u=await l.json(),f=new Response(null,{status:302,headers:{Location:i}}),d=n.protocol==="https:"?"; Secure":"",g=(y,w,R)=>{f.headers.append("Set-Cookie",`${y}=${w}; Path=/; HttpOnly${d}; SameSite=Lax; Max-Age=${R}`)};return u.access_token&&g("access_token",u.access_token,u.expires_in),u.refresh_token&&g("refresh_token",u.refresh_token,u.refresh_expires_in||3600*24*30),u.id_token&&g("id_token",u.id_token,u.expires_in),f}catch(s){return console.error("Auth error:",s),new Response("Internal Server Error",{status:500})}if(n.pathname==="/auth/logout"){let s=new Response(null,{status:302,headers:{Location:"/login"}}),a=o=>{s.headers.append("Set-Cookie",`${o}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return a("access_token"),a("refresh_token"),a("id_token"),s}if(n.pathname.startsWith("/s/")){let s=await v(t,e,r);if(!s){let a=new URL("/login",n.origin);return a.searchParams.set("nextURL",`${n.pathname}${n.search}`),Response.redirect(a.toString(),302)}return{user:s}}}export{pt as ANONYMOUS_RUN_USER_PREFIX,Ze as AgentDO,Fn as CRAWL_DEFAULTS,Ln as CRAWL_LIMITS,an as DEFAULT_MEMORY_LENGTH,cn as DEFAULT_MEMORY_MODEL,tn as FLOW_INPUT_NAME_RE,ur as FlowExecutionStoppedError,qn as GENERATION_PARAM_KEYS,zn as GENERATION_PRESETS,rn as MAX_USER_IDENTITY_LENGTH,sn as MEMORY_LENGTH_MD_LINES,on as MEMORY_LENGTH_TOKENS,dr as MODEL_REGISTRY_SNAPSHOT,F as NodeType,dn as OUT_VAR_NAME_RE,Vn as PRESET_PARAM_KEYS,rr as REASONING_EFFORT_LEVELS,Dn as TENANT_ONLY_NODES,lr as TOOL_REGISTRY_SNAPSHOT,st as TRIGGER_NONCE_HEADER,nt as TRIGGER_SIGNATURE_HEADER,Is as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,ot as TRIGGER_TENANT_HEADER,rt as TRIGGER_TIMESTAMP_HEADER,xn as VariableResolutionError,Wn as applyPresetToOverrides,Hn as buildCrawlRequestBody,De as buildReasoningProviderOptions,hn as buildScope,Ts as buildSignedTriggerHeaders,Se as buildTriggerMessageText,Yt as buildUrl,$t as canonicalUserEmail,xe as capMemoryContent,M as claimRun,H as clearAllMessages,K as completeRun,Gt as convertTempMessure,jn as crawlRequestKey,B as createRun,Gn as deriveParamSupport,et as dispatchTrigger,Zt as embedText,He as ensureAgentTables,dt as ensureMessagesTable,un as estimateTokens,An as extractOutVarValues,vn as extractTemplateReferences,Oe as extractUserKeypoints,wn as findScopedSourceNode,O as getAllMessages,gn as getAncestorNodeIds,pn as getDefaultOutVars,fn as getEffectiveOutVars,Re as getFlowInputDefs,pr as getModelEntry,Rn as getRefTail,yn as getUpstreamOutVars,$s as handleAgentsRoutes,Xs as handleAuthRoutes,hs as handleCommonRoutes,Hs as handleIntancesRoutes,zt as handlePersistedSessionInspection,Vt as handleSessionRunControl,lt as handleTriggerRoutes,Qt as hashText,N as initializeEngineState,Sn as isBinaryOutVar,En as isJsonContentType,$n as isNodeTypeAllowedForTenant,ke as isStartMemoryEnabled,Nn as jsonSchemaToZod,we as logc,be as looksLikeTranscript,_e as memoryGenerationMaxTokens,L as memoryMdLineLimit,Te as memoryTokenLimit,ve as mergeKeypointMemory,E as messageTypes,jt as normalizeDestination,Bn as normalizeEffectiveParams,nn as normalizeFlowInputs,ir as normalizeModelEntry,sr as normalizeReasoning,Zn as openAiReasoningParamSupport,Qn as openAiStandardParamSupport,V as parseCookies,ln as parseMemoryLength,In as parsePayloadText,On as parseTemplateExpression,Ie as parseUserAuth,Ee as parseUserMessage,Yn as pickNodeOverrides,Tn as readFetchPayload,or as reasoningEffortLevels,ar as reasoningExposable,Ke as recordRun,cr as registerProvider,Mn as resolveAnswerMappings,$e as resolveModelById,bn as resolveOutVarRef,Un as resolveOutVarValue,Jn as resolvePreset,Ne as resolveReasoningEffort,_n as resolveReference,je as resolveRunUserId,Pn as resolveTemplate,Cn as rewriteTemplateNodeRefs,D as runAgentTurn,Xn as runCrawl,Wt as safeParseJSON,W as sanitizeMemoryDocument,P as sanitizeUserIdentity,Je as sendEvent,k as serverSend,Le as setMessage,Kn as shapeCrawlOutput,it as signTriggerMaterial,Fe as startEngine,Ae as startMemoryLength,Ue as startMemoryModel,nr as stripUnsupportedFromNodeData,Jt as tempTool,Kt as timingSafeEqualHex,Me as toStreamTextSettings,at as triggerSignatureMaterial,Bt as twitter,ds as validateFlowStart,mn as validateOutVars,en as vectorize,Ft as verifyToken,ct as verifyTriggerRequest,v as verifyUser,kn as walkPath,tr as workersAiParamSupport,er as xaiParamSupport};
@@ -76,7 +76,11 @@ export type PersistedSessionSectionResult = {
76
76
  };
77
77
  export declare class AgentDO extends Agent<Env, State> {
78
78
  initialState: State;
79
- /** JWT email wins; explicit client identity is fallback only. */
79
+ constructor(ctx: DurableObjectState, env: Env);
80
+ /** Only the server may change SDK-synchronized state. Supported since agents 0.8.7. */
81
+ validateStateChange(_nextState: State, source: Connection | 'server'): void;
82
+ private requireStateValidation;
83
+ /** Declared anonymous identity only; authorized user comes from the connection/request. */
80
84
  private resolveSessionUserId;
81
85
  private secrets;
82
86
  private userAuth;
@@ -0,0 +1,6 @@
1
+ import type { UserInterface } from '../../common/types/user-types';
2
+ /** Shared admission for the chat page and its HTTP/WebSocket transport. */
3
+ export declare function authorizeFlowChat(request: Request, env: Env, ctx: ExecutionContext, flowId: string, sessionId?: string, page?: boolean): Promise<{
4
+ response?: Response;
5
+ user?: UserInterface;
6
+ }>;
@@ -0,0 +1 @@
1
+ import"ai";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hugex/ai",
3
- "version": "3.1.4",
3
+ "version": "3.1.5",
4
4
  "description": "Ora AI Agent Framework",
5
5
  "author": "a@hugex.co",
6
6
  "license": "SEE LICENSE IN LICENSE",