@hugex/ai 3.0.6 → 3.1.0
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.
- package/dist/FlowEngine-XAIMWC7Y.js +1 -0
- package/dist/{chunk-CDGUEX3J.js → chunk-3K4IMMLP.js} +1 -1
- package/dist/chunk-6AZ7RATD.js +1 -0
- package/dist/chunk-BBJLGBLT.js +23 -0
- package/dist/chunk-V35SRZAO.js +1 -0
- package/dist/{chunk-MOYYZBTC.js → chunk-XXB57DMN.js} +1 -1
- package/dist/chunk-YHXUBVN2.js +1 -0
- package/dist/common/types/user-types.d.ts +1 -0
- package/dist/composioDirectTool-XOKIM5FJ.js +1 -0
- package/dist/{composioTool-5LFWUQ7F.js → composioTool-C4KZMI4Q.js} +1 -1
- package/dist/index.js +6 -6
- package/dist/oraApi-YIJGMXX7.js +1 -0
- package/dist/server/core/AgentDO.d.ts +0 -4
- package/dist/server/tools/composioDirectTool.d.ts +1 -3
- package/dist/server/utils/oraApi.d.ts +0 -8
- package/dist/server/utils/sessionIndex.d.ts +1 -0
- package/dist/server/utils/telemetry.d.ts +1 -0
- package/dist/{skillTool-AIOXPTAJ.js → skillTool-JEAL3G33.js} +1 -1
- package/package.json +1 -1
- package/dist/FlowEngine-RGHVLIOZ.js +0 -1
- package/dist/chunk-A2IRPAD4.js +0 -1
- package/dist/chunk-CRVHPQVH.js +0 -23
- package/dist/chunk-ELMOSEQ7.js +0 -1
- package/dist/chunk-OF6G42DM.js +0 -1
- package/dist/composioDirectTool-H3GSCIPY.js +0 -1
- package/dist/oraApi-4O3W5LXD.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h as a,i as b}from"./chunk-BBJLGBLT.js";import"./chunk-V35SRZAO.js";import"./chunk-YFOFZWIB.js";import"./chunk-6AZ7RATD.js";import"./chunk-XXB57DMN.js";import"./chunk-3K4IMMLP.js";import"./chunk-4XJVXKXR.js";import"./chunk-J4LJZZ67.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{
|
|
1
|
+
import{c as m}from"./chunk-YHXUBVN2.js";import{tool as p}from"ai";import{z as s}from"zod";function y(t,c){if(c.length===0)return;let f=c.map(e=>`- "${e.name}"${e.description?` \u2014 applies when: ${e.description}`:""}`);return`MANDATORY REFERENCE CHECK. This skill has reference documents, each listed below with the condition under which it applies. On EVERY turn, BEFORE you answer, evaluate whether the user's message \u2014 or the reply you are about to give \u2014 matches any condition. If it does, you MUST first call \`readSkillRef({ skill: "${t}", ref: "<name>" })\`, read the document, and follow it in your response. Never guess, summarize, or apply a reference you have not loaded this turn.
|
|
2
2
|
|
|
3
3
|
References:
|
|
4
4
|
${f.join(`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as F,b as S,c as v,e as U,f as P,g as K,h as N,i as O,j as M,k as j,l as g,m as h}from"./chunk-XXB57DMN.js";import{Composio as L}from"@composio/core";import{VercelProvider as B}from"@composio/vercel";function w(o,n,i,s,t){let r=s?g(s)??s.trim():void 0;!r||!r.startsWith("http")||o==null||o({type:"info:composio:auth_required",content:{toolkit:t,redirectUrl:r,toolRowId:n.id}})}function q(o){let n=g(o);if(n)return n;if(typeof o=="string")return g(o);try{return g(JSON.stringify(o))}catch{return}}async function W(o,n,i,s,t,r=!0){var e;let l=await o.toolkits({toolkits:n.toolkits});for(let u of l.items)if(!(u.isNoAuth||(e=u.connection)!=null&&e.isActive))try{let p=await o.authorize(u.slug,{callbackUrl:i});r&&w(t,s,n,p.redirectUrl,u.slug);break}catch(p){`${u.slug}${String(p)}`}}function H(o,n,i,s,t=!0){let r={};for(let[l,e]of Object.entries(o)){if(!e||typeof e!="object"||typeof e.execute!="function"){r[l]=e;continue}let u=e.execute.bind(e);r[l]={...e,execute:async(...p)=>{try{let c=await u(...p);if(t){let m=q(c);m&&w(s,n,i,m,h(String(c),i))}return c}catch(c){if(j(c)){let m=q(c);w(s,n,i,m,h(String(c),i))}throw c}}}}return r}async function X(o,n,i,s){var R,$,I,A,T,E;if(o.kind!=="composio")throw new Error(`loadComposioTools: unsupported kind '${o.kind}' for tool '${o.name}'`);let t=O(o.execution),r=v(n),l=t.authMode==="manual",e;if(l){let a=F(t,o.id);if(!a)throw new Error(`Composio manual tool '${o.name}' is missing connection scope (tool id or execution.connectionScope)`);e=S(a)}else e=K(n,i,{allowChatIdFallback:!0});let u=(R=i.flowData)==null?void 0:R.flowId,p=($=i.flowData)==null?void 0:$.chatId,c=((I=t.manageConnections)==null?void 0:I.callbackUrl)||N(n,u,p,o.id),m=M(t,c),C=new L({apiKey:r,provider:new B});n.composioSessions||(n.composioSessions={});let b=U(t),z=l?!1:((A=t.workbench)==null?void 0:A.enable)!==!1,d,f=n.composioSessions[o.id];f!=null&&f.sessionId&&f.userId===e&&f.configKey===b?(d=await C.use(f.sessionId),`${f.sessionId}${o.name}${e}`,void 0):(d=await C.create(e,P(t,{manageConnections:m,workbench:{enable:z}})),n.composioSessions[o.id]={sessionId:d.sessionId,userId:e,configKey:b},`${d.sessionId}${o.name}${e}${t.authMode}${t.sessionPreset??"default"}`,(T=t.sessionPreload)!=null&&T.enabled,void 0);try{let a=await d.toolkits({toolkits:t.toolkits});for(let k of a.items){let x=!!(k.isNoAuth||(E=k.connection)!=null&&E.isActive);`${k.slug}${x}${e}`}await W(d,t,c,o,s,!l)}catch(a){`${o.name}${String(a)}`}let y=await d.tools(),D=Array.isArray(y)?Object.fromEntries(y.map(a=>[a.name??a.toolName,a])):y;return H(D,o,t,s,!l)}export{X as a};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import{a as Vt}from"./chunk-V35SRZAO.js";import{a as B,b as Z,c as Lt,d as tt}from"./chunk-YFOFZWIB.js";import{a as Yt}from"./chunk-6AZ7RATD.js";import{a as bt,b as Ct,d as jt,g as Ut,i as st}from"./chunk-XXB57DMN.js";import{a as Zt,b as Qt}from"./chunk-3K4IMMLP.js";import{C as Wt,D as Jt,E as Xt,L as qt,N as zt,O as Kt,P as Bt,Q as Gt,a as z,b as Ft,k as Ot,n as _t,o as It,q as kt,z as Ht}from"./chunk-4XJVXKXR.js";import{B as Pt,c as E,d as $t,h as Dt,k as Y,r as Mt,s as C,v as S,w as H}from"./chunk-J4LJZZ67.js";import{a as xt,b as Tt,d as At}from"./chunk-YLDLDEUP.js";import{a as v}from"./chunk-YHXUBVN2.js";import{a as Q}from"./chunk-3TXHFKDN.js";async function Et(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 c=await s.json();return{name:t.name,text:c.text||""}}catch(s){return console.error(`extractDocuments: ${t.name} threw`,s),{name:t.name,text:""}}})):[]}function po(e,o,i){var t,s,c,f;return Y(((s=(t=i.flowData)==null?void 0:t.state)==null?void 0:s.nodes)??[],((f=(c=i.flowData)==null?void 0:c.state)==null?void 0:f.edges)??[],o.id).some(d=>d.ref===e&&(d.type==="image"||d.type==="file"))}function fo(e,o){var f,d,p,a,l,y,n;let i=Array.isArray((f=e.data)==null?void 0:f.outputMapping)?e.data.outputMapping:[];if(i.length===0)return null;let t=((p=(d=o.flowData)==null?void 0:d.state)==null?void 0:p.nodes)||[],s={},c=new Set;for(let g of i){let r=(a=g.key)==null?void 0:a.trim(),w=(l=g.from)==null?void 0:l.trim();if(!r||!w)throw new Error(`Answer node ${e.id} has an incomplete variable mapping`);if(c.has(r))throw new Error(`Answer node ${e.id} has duplicate output key "${r}"`);if(po(w,e,o))throw new Error(`Answer node ${e.id} cannot persist binary source "${w}"`);let u=H(w,{context:o.context||{},results:o.results||{},nodes:t,edges:((n=(y=o.flowData)==null?void 0:y.state)==null?void 0:n.edges)??[],currentNodeId:e.id}),m=u.value;if(u.missing||m===void 0||m===null){if(g.default===void 0)throw new C(u.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Answer node ${e.id} could not resolve output "${w}"`);m=g.default}s[r]=m,c.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 rt(e,o,i,t,s,c,f){var p,a,l;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let d;try{d=fo(o,i)}catch(y){throw t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(y)}}),y}d&&e.outputCollector&&e.outputCollector.add(o.id,d);try{let y=await((p=e.getMessages)==null?void 0:p.call(e))??[],n=((a=y[y.length-1])==null?void 0:a.type)==="text"?y[y.length-1].content:"NO-TEXT";f==null||f({type:"answer_node",payload:{userMessage:(l=i==null?void 0:i.context)==null?void 0:l.user_input,answer:n}})}catch(y){console.error("answerNodeRunner: failed to emit answer telemetry:",y),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:!!d&&!!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 q(e,o,i,t,s){var d,p,a,l,y;let c=(s==null?void 0:s.callerTag)??"llmNodeRunner",f=(s==null?void 0:s.serializeNonStrings)??!1;return Pt(e,o,{context:i.context??{},results:i.results??{},nodes:((p=(d=i.flowData)==null?void 0:d.state)==null?void 0:p.nodes)??[],edges:((l=(a=i.flowData)==null?void 0:a.state)==null?void 0:l.edges)??[],currentNodeId:o.id,secrets:(y=s==null?void 0:s.sessionEnv)==null?void 0:y.secrets},{callerTag:c,serializeNonStrings:f,onError:n=>{t==null||t({type:`error:${c}`,content:n})}})}var nt="[redacted]",vt=8*1024;function mo(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<=vt){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,vt);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function yo(e,o){return S(e,o)}var at=(e,o,i,t,s)=>q(e,o,i,s,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function dt(e,o,i,t,s,c,f){var a,l,y,n,g,r;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let d=null,p=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(i.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(i.results||{}));let w=((a=o.data)==null?void 0:a.url)||"",u=at(w,o,i,e,t);if(console.log("[apiNodeRunner] resolved url:",B(w)?Z(u):u),!u){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,d);return}let m=(((l=o.data)==null?void 0:l.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",m);let h=((y=o.data)==null?void 0:y.headers)||{},x={},N={};for(let U in h)if(Object.prototype.hasOwnProperty.call(h,U)){let j=String(h[U]??"");N[U]=B(j),x[U]=at(j,o,i,e,t)}let T,k=!1;if(m!=="GET"&&m!=="HEAD"&&((n=o.data)==null?void 0:n.body)!==void 0){let U=typeof o.data.body=="string"?o.data.body:JSON.stringify(o.data.body);k=B(U),T=at(U,o,i,e,t),!x["Content-Type"]&&!x["content-type"]&&(x["Content-Type"]="application/json")}let $={};for(let U in x)$[U]=N[U]?nt:x[U];console.log("[apiNodeRunner] headers:",JSON.stringify($)),console.log("[apiNodeRunner] body:",k?nt:T),t==null||t({type:"info:apiNodeRunner:request",content:{nodeId:o.id,method:m,url:B(w)?Z(u):u,headers:$,body:k?nt:T}});let P=Number((g=o.data)==null?void 0:g.timeoutMs),b=new AbortController,F=Number.isFinite(P)&&P>0?setTimeout(()=>b.abort(),P):null,R;try{console.log("[apiNodeRunner] fetching..."),R=await fetch(u,{method:m,headers:x,body:T,signal:b.signal}),console.log("[apiNodeRunner] fetch returned status:",R.status)}finally{F&&clearTimeout(F)}let D=R.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",D);let M=await Mt(R);console.log("[apiNodeRunner] payload preview:",typeof M=="string"?M.slice(0,200):JSON.stringify(M).slice(0,200)),d={ok:R.ok,status:R.status,data:M};let V=Date.now()-p;f==null||f({type:"api_call",payload:{nodeId:o.id,url:u,method:m,status:R.status,latencyMs:V}});let{value:_,truncated:X}=mo(M);t==null||t({type:"info:apiNodeRunner:response",content:{nodeId:o.id,ok:R.ok,status:R.status,latencyMs:V,data:_,truncated:X,outVars:yo(o,d)}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}catch(w){console.error("Error processing ApiNode:",w),t==null||t({type:"error:apiNodeRunner",content:`API node execution failed: ${w}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(w)}})}finally{console.log("[apiNodeRunner] final result:",(r=JSON.stringify(d))==null?void 0:r.slice(0,300)),s==null||s(o.id,d)}}var go="[redacted]",oo=8*1024;function ct(e,o){if(typeof e=="string")return B(e)?typeof o=="string"&&/^https?:\/\//i.test(o)?Z(o):go:o;if(e&&typeof e=="object"&&!Array.isArray(e)){let i={},t=o&&typeof o=="object"&&!Array.isArray(o)?o:{};for(let[s,c]of Object.entries(e))i[s]=ct(c,t[s]);return i}if(Array.isArray(e)){let i=Array.isArray(o)?o:[];return e.map((t,s)=>ct(t,i[s]))}return o}function wo(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<=oo){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,oo);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function ho(e,o){return S(e,o)}var No=(e,o,i,t,s)=>q(e,o,i,s,{callerTag:"toolNodeRunner",serializeNonStrings:!0,sessionEnv:t});function ot(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ro(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 xo(e,o){var f,d;let i={},t={},s=((f=e.data)==null?void 0:f.inputSchema)??o;if(s&&typeof s=="object"&&!Array.isArray(s)){t=ot(ot(s).properties);for(let[p,a]of Object.entries(t))i[p]=Ro(a);return{types:i,properties:t}}let c=(d=e.data)==null?void 0:d.argTypes;if(c&&typeof c=="object"&&!Array.isArray(c))for(let[p,a]of Object.entries(c))typeof a=="string"&&(i[p]=a);return{types:i,properties:t}}function To(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(c=>String(c)===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 Ao(e){return e===void 0||typeof e=="string"&&e.trim()===""}function lt(e,o,i,t,s,c,f){if(typeof e=="string"){let d=e.includes("{{")?No(e,o,i,t,s):e;return To(d,c,f)}if(e&&typeof e=="object"&&!Array.isArray(e)){let d={};for(let[p,a]of Object.entries(e))d[p]=lt(a,o,i,t,s);return d}return Array.isArray(e)?e.map(d=>lt(d,o,i,t,s)):e}function $o(e,o,i,t,s,c){let f={};for(let[d,p]of Object.entries(e)){let a=lt(p,o,i,t,s,c.types[d],c.properties[d]);Ao(a)||(f[d]=a)}return f}async function Fo(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 Oo(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 _o(e,o,i){let t=st(e.execution);if(t.authMode==="manual"){let s=bt(t,e.id);if(!s)throw new Error(`Composio tool '${e.name}' is missing connection scope`);return Ct(s)}return Ut(o,i,{allowChatIdFallback:!0})}async function ut(e,o,i,t,s,c,f){var l,y,n,g,r,w;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let d={ok:!1,data:null,error:null},p=Date.now(),a=Oo(o);try{if(a==="catalog")throw new Error("This Tool node still uses a curated catalog connector. Reconfigure it to a tenant HTTP or connector tool.");let u=(l=o.data)!=null&&l.args&&typeof o.data.args=="object"&&!Array.isArray(o.data.args)?o.data.args:{},m=typeof((y=o.data)==null?void 0:y.toolId)=="string"?o.data.toolId.trim():"";if(!m)throw new Error("Tool nodes require toolId");let x=(await Fo(e))[m];if(!x)throw new Error(`Tool ${m} not found`);let N="";if(a==="composio"){if(x.kind!=="composio")throw new Error(`Tool ${m} is not a connector tool`);if(N=typeof((n=o.data)==null?void 0:n.toolSlug)=="string"?o.data.toolSlug.trim():"",!N)throw new Error("Connector tool nodes require toolSlug");let F=st(x.execution);if(!jt(F.tools).includes(N))throw new Error(`Tool slug ${N} is not enabled on connector ${m}`)}else if(x.kind!=="http")throw new Error(`Tool ${m} is not an HTTP tool`);let T=xo(o,a==="http"?x.inputSchema:void 0),k=$o(u,o,i,e,t,T);if(t==null||t({type:"info:toolNodeRunner:request",content:{nodeId:o.id,source:a,toolSlug:(g=o.data)==null?void 0:g.toolSlug,toolId:(r=o.data)==null?void 0:r.toolId,args:ct(u,k)}}),a==="composio"){let F=typeof((w=o.data)==null?void 0:w.toolVersion)=="string"?o.data.toolVersion.trim():"",R=await Vt(e,{toolSlug:N,connectionScope:_o(x,e,i),toolVersion:F||null,arguments:k});d={ok:R.ok,data:R.ok?R.data:null,error:R.ok?null:R.error??"Tool execution failed"}}else{let F=tt(x,e,i,t);if(!F.execute)throw new Error(`Tool ${m} is missing an execute handler`);let R=await F.execute(k,{}),D=R&&typeof R=="object"&&"error"in R&&R.error?String(R.error):null;d={ok:!D,data:R,error:D}}let $=Date.now()-p;f==null||f({type:"tool_call",payload:{nodeId:o.id,url:a==="composio"?`composio:${N}`:`tool:${m}`,method:"EXECUTE",status:d.ok?200:502,latencyMs:$}});let{value:P,truncated:b}=wo(d.data);t==null||t({type:"info:toolNodeRunner:response",content:{nodeId:o.id,ok:d.ok,latencyMs:$,data:P,truncated:b,error:d.error,outVars:ho(o,d)}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:d.ok?"success":"error",error:d.error??void 0}})}catch(u){let m=u instanceof Error?u.message:String(u);d={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,d)}}function eo(){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 Io(e){return!!(e!=null&&e.HX_ORA_URL)&&!!(e!=null&&e.HX_API_KEY)}async function Te(e,o){if(!Io(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 io=3,so=10,ko=new Set(["agent:start","agent:complete","agent:telemetry"]);function Do(e){let o=e.executedNodes||[];return o.length===0?"(none)":o.map(i=>i.label?`${i.id} (${i.label})`:i.id).join(" \u2192 ")}function Mo(e){let o=e.executedNodes||[];return o[o.length-1]}function J(e,o,i){throw e==null||e({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:i.message}}),i}function Po(e,o){var c,f,d,p,a,l,y;let i=Array.isArray((c=e.data)==null?void 0:c.inputs)?e.data.inputs:[],t=((d=(f=o.flowData)==null?void 0:f.state)==null?void 0:d.nodes)||[],s={};for(let n of i){let g=(p=n.key)==null?void 0:p.trim();if(!g)continue;let r=(a=n.from)==null?void 0:a.trim();if(!r){if(n.default===void 0)continue;s[g]=n.default;continue}let w=H(r,{context:o.context||{},results:o.results||{},nodes:t,edges:((y=(l=o.flowData)==null?void 0:l.state)==null?void 0:y.edges)??[],currentNodeId:e.id}),u=w.value;if(w.missing||u===void 0||u===null){if(n.default===void 0)throw new C(w.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Worker node ${e.id} could not resolve input "${r}"`);u=n.default}s[g]=u}return s}async function pt(e,o,i,t,s,c,f){var b,F,R,D,M,V;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let d=typeof((b=o.data)==null?void 0:b.flowId)=="string"?o.data.flowId.trim():"";d||J(t,o,new Error(`Worker node ${o.id} is missing flowId`));let p=(F=i.flowData)==null?void 0:F.flowId,a=e.workerStack??(p?[p]:[]);a.includes(d)&&J(t,o,new Error(`Worker node ${o.id} cannot call ${d}: cycle detected (${[...a,d].join(" \u2192 ")})`)),a.length>=io&&J(t,o,new Error(`Worker node ${o.id} exceeded max nesting depth (${io})`));let l=e.workerCalls??{count:0};e.workerCalls=l,l.count>=so&&J(t,o,new Error(`Worker node ${o.id} exceeded max worker calls per run (${so})`)),l.count+=1;let y;try{y=Po(o,i)}catch(_){J(t,o,_ instanceof Error?_:new Error(String(_)));return}let n=e.env;n||J(t,o,new Error(`Worker node ${o.id} is missing runtime env`));let g,r;try{let _=await xt(d,n);r=(R=_==null?void 0:_.metadata)==null?void 0:R.tenant,g=await Tt(d,n)}catch(_){J(t,o,new Error(`Worker node ${o.id} could not load worker ${d}: ${_ instanceof Error?_.message:String(_)}`))}let w=(D=i.flowData)==null?void 0:D.tenant;(!r||r!==w)&&J(t,o,new Error(`Worker ${d} belongs to a different tenant`));let u=eo(),m={flowData:{...g,tenant:r,flowId:d,chatId:((M=i.flowData)==null?void 0:M.chatId)||""},executedNodes:[],context:{},results:{}},h={env:n,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:l,conn:void 0,getMessages:async()=>[],setMessages:async()=>{},agentMemory:"",outputCollector:u,workerStack:[...a,d]},x,N={onChangeState:()=>{},onServerEvent:_=>{var X;ko.has(_.type)||t==null||t({type:"worker:node",content:{workerNodeId:o.id,childNodeId:(X=_.content)==null?void 0:X.nodeId,event:_}})},onTelemetry:_=>f==null?void 0:f(_),onError:_=>{x=_},shouldStop:e.shouldStop},{startEngine:T,FlowExecutionStoppedError:k}=await import("./FlowEngine-XAIMWC7Y.js"),$=await T(h,m,N)({text:"",inputs:y});if(($.status==="stopped"||await((V=e.shouldStop)==null?void 0:V.call(e)))&&J(t,o,new k),$.status!=="completed"){let _=Mo(m),X=Do(m),U=$.error||x||"unknown error",j=_?` at node ${_.label?`${_.id} (${_.label})`:_.id}`:"";J(t,o,new Error(`Worker ${d} failed${j}: ${U}. Path: ${X}`))}u.hasOutputs()||J(t,o,new Error(`El worker ${d} complet\xF3 sin output estructurado. Agreg\xE1 un mapeo de salida en su nodo Answer.`));let P=(m.executedNodes||[]).map(_=>_.id);s==null||s(o.id,{ok:!0,data:u.snapshotData(),error:null,executed:P}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}import{generateObject as Jo}from"ai";import{z as ro}from"zod";import{openai as bo}from"@ai-sdk/openai";import{extractReasoningMiddleware as Co,wrapLanguageModel as jo}from"ai";import{createWorkersAI as Uo}from"workers-ai-provider";import{xai as Vo}from"@ai-sdk/xai";import{anthropic as Lo}from"@ai-sdk/anthropic";import{createOpenRouter as Ho}from"@openrouter/ai-sdk-provider";var mt={};function ft(e){if(e!=null){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}}function Wo(e){return{...e,defaultParams:ft(e.defaultParams)??e.defaultParams,capabilities:ft(e.capabilities)??e.capabilities,price:ft(e.price)??e.price}}async function et(e,o,i){var l,y;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=Wo(t),c=((l=s.capabilities)==null?void 0:l.params)??Ht(s),{effectiveParams:f,adjustments:d}=Jt(s.defaultParams,i,c),p;if(mt[s.provider])p=await mt[s.provider](s,o,i);else if(s.provider==="openai")p=bo(s.providerModel);else if(s.provider==="xai")p=Vo(s.providerModel);else if(s.provider==="anthropic")p=Lo(s.providerModel);else if(s.provider==="openrouter")p=Ho()(s.providerModel);else if(s.provider==="workersai"||s.provider==="cloudflare"){if(!((y=o==null?void 0:o.env)!=null&&y.AI))throw new Error("Workers AI provider requires sessionEnv.env.AI binding");p=Uo({binding:o.env.AI})(s.providerModel)}else p={provider:s.provider,providerModel:s.providerModel};let a=qt(s);return a.kind==="tag"&&p&&typeof p=="object"&&"specificationVersion"in p&&(p=jo({model:p,middleware:Co({tagName:a.tagName??"think",startWithReasoning:a.startWithReasoning??!1})})),{provider:s.provider,modelHandle:p,entry:s,effectiveParams:f,paramAdjustments:d.length>0?d:void 0,reasoning:a}}function Ue(e,o){mt[e]=o}async function yt(e,o,i,t,s,c,f){var r,w,u,m,h,x,N;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let d=String(((r=o==null?void 0:o.data)==null?void 0:r.input_variable)||"user_input").trim(),p;try{let T=H(d,{context:i.context??{},results:i.results??{},nodes:((u=(w=i.flowData)==null?void 0:w.state)==null?void 0:u.nodes)??[],edges:((h=(m=i.flowData)==null?void 0:m.state)==null?void 0:h.edges)??[],currentNodeId:o.id});if(T.missing)throw new Error(`Classifier input "${d}" did not produce a value`);p=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 a=Array.isArray((x=o==null?void 0:o.data)==null?void 0:x.items)?o.data.items:[];if(a.length===0){t==null||t({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let l=String((N=a[a.length-1])==null?void 0:N.id);if(!p||String(p).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:l}),i.context=i.context||{},i.context.classified_id=l,c==null||c(i);return}let n=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
|
|
2
|
+
If the message is ambiguous or none clearly matches, choose the LAST category in the list.
|
|
3
|
+
|
|
4
|
+
Categories:
|
|
5
|
+
${a.map(T=>{let k=T.keywords??T["keywords/topics"]??"",$=Array.isArray(k)?k.join(", "):String(k||"");return`- id: ${T.id}
|
|
6
|
+
label: ${T.label}
|
|
7
|
+
keywords/topics: ${$}`}).join(`
|
|
8
|
+
`)}
|
|
9
|
+
`,g=`User message:
|
|
10
|
+
"""${String(p).trim()}"""
|
|
11
|
+
|
|
12
|
+
Select the best matching category id.`;try{let T=Date.now(),k=a.map(V=>String(V.id)),$="gpt_4_1_mini",P=await et($,e);if(!P)throw new Error(`Model '${$}' not found in registry`);let{modelHandle:b,effectiveParams:F}=P,R=await Jo({model:b,messages:[{role:"system",content:n},{role:"user",content:g}],schema:ro.object({classification:ro.enum(k).describe("The id of the best matching category")}),temperature:F.temperature??0}),D=Date.now()-T,M=R.object.classification;f==null||f({type:"class_telemetry",payload:{nodeId:o.id,totalLatency:D,model:R.response.modelId,usage:R.usage,options:k}}),f==null||f({type:"class_result",payload:{result:R}}),s==null||s(o.id,{classification:M}),i.context=i.context||{},i.context.classified_id=M,c==null||c(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 Ko,streamText as Bo}from"ai";import{nanoid as Go}from"nanoid";import"zod";function no(e,o){var d,p,a,l,y;let i=((d=e.data)==null?void 0:d.attachments)??[];if(!Array.isArray(i))throw new C("INVALID_EXPRESSION",`Node ${e.id} attachments must be an array`);let t=((a=(p=o.flowData)==null?void 0:p.state)==null?void 0:a.nodes)??[],s=((y=(l=o.flowData)==null?void 0:l.state)==null?void 0:y.edges)??[],c=Y(t,s,e.id),f="";for(let n of i){if(typeof n!="string")throw new C("INVALID_EXPRESSION",`Node ${e.id} has an invalid attachment reference`);let g=c.find(w=>w.ref===n);if(!g)throw new C("OUT_OF_SCOPE",`Attachment "${n}" is not in this node's connection scope`);if(g.type!=="file"&&g.type!=="image")throw new C("UNKNOWN_OUTPUT",`Attachment "${n}" is not an image or file output`);if(g.type!=="file")continue;let r=H(n,{context:o.context??{},results:o.results??{},nodes:t,edges:s,currentNodeId:e.id});if(r.missing)throw new C(r.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${n}" did not produce a value`);if(typeof r.value!="string")throw new C("PATH_NOT_FOUND",`Attachment "${n}" must resolve to file text`);r.value.trim()&&(f+=(f?`
|
|
13
|
+
|
|
14
|
+
`:"")+r.value)}return f}function Xo(e,o){var s,c,f,d,p;let i=((s=e.data)==null?void 0:s.attachments)??[];if(!Array.isArray(i))throw new C("INVALID_EXPRESSION",`Node ${e.id} attachments must be an array`);let t=Y(((f=(c=o.flowData)==null?void 0:c.state)==null?void 0:f.nodes)??[],((p=(d=o.flowData)==null?void 0:d.state)==null?void 0:p.edges)??[],e.id);return i.map(a=>{if(typeof a!="string")throw new C("INVALID_EXPRESSION",`Node ${e.id} has an invalid attachment reference`);let l=t.find(y=>y.ref===a);if(!l)throw new C("OUT_OF_SCOPE",`Attachment "${a}" is not in this node's connection scope`);if(l.type!=="image"&&l.type!=="file")throw new C("UNKNOWN_OUTPUT",`Attachment "${a}" is not a binary output`);return l.type==="image"?a:null}).filter(a=>a!==null)}function ao(e,o){var s,c,f,d;let i=[],t={context:o.context??{},results:o.results??{},nodes:((c=(s=o.flowData)==null?void 0:s.state)==null?void 0:c.nodes)??[],edges:((d=(f=o.flowData)==null?void 0:f.state)==null?void 0:d.edges)??[],currentNodeId:e.id};for(let p of Xo(e,o)){let a=H(p,t);if(a.missing)throw new C(a.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${p}" did not produce a value`);if(!Array.isArray(a.value))throw new C("PATH_NOT_FOUND",`Attachment "${p}" must resolve to an image array`);i.push(...a.value)}return i}var K=(e,o,i)=>{e.send(o+"::"+i)};var qo=Q({"../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-2BU6JAAK.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 zo=Q({});async function Yo(e,o,i,t){var y;let s=Array.isArray((y=i==null?void 0:i.data)==null?void 0:y.tools)?i.data.tools:[];if(s.length===0)return{};let c={},f=n=>{var x,N;let g=typeof(n==null?void 0:n.description)=="string"?n.description:"",r=n==null?void 0:n.inputSchema,w;try{let T=(r==null?void 0:r.shape)??(typeof((x=r==null?void 0:r._def)==null?void 0:x.shape)=="function"?r._def.shape():(N=r==null?void 0:r._def)==null?void 0:N.shape);T&&typeof T=="object"&&(w=T)}catch{}let u=w?Object.keys(w):[],m=g?`description="${g.length>120?g.slice(0,120)+"\u2026":g}"`:"description=(none)",h=u.length?`inputSchema={${u.join(", ")}}`:"inputSchema=(none)";return`${m} ${h}`},d=(()=>{let n=[],g=[],r=[],w=[];for(let m=0;m<s.length;m++){let h=s[m];!h||typeof h!="object"||typeof h.id!="string"?w.push(m):h.kind==="builtin"?n.push(h.id):h.kind==="skill"?r.push(h.id):h.kind==="http"||h.kind==="mcp"||h.kind==="composio"?g.push(h.id):w.push(m)}let u=[];return n.length&&u.push(`builtin[${n.join(", ")}]`),g.length&&u.push(`custom[${g.join(", ")}]`),r.length&&u.push(`skill[${r.join(", ")}]`),w.length&&u.push(`invalid@[${w.join(", ")}]`),u.join(" ")||"(none)"})();console.log(`[tools] node ${i.id} requested (${s.length}): ${d}`);let p=!1,a=async()=>{if(p&&e.toolDefs)return e.toolDefs;if(!e.env)return e.toolDefs=e.toolDefs||{},p=!0,e.toolDefs;try{let n=await v(e.env),g={};for(let r of n)r&&r.id&&(g[r.id]=r);e.toolDefs=g}catch(n){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(n)}`}),e.toolDefs=e.toolDefs||{}}return p=!0,e.toolDefs},l=[];for(let n=0;n<s.length;n++){let g=s[n];if(!g||typeof g!="object"||typeof g.id!="string"||g.kind!=="builtin"&&g.kind!=="http"&&g.kind!=="mcp"&&g.kind!=="composio"&&g.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${n}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let r=g;if(r.kind!=="builtin"){let u=(await a())[r.id];if(!u){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 h=await Yt(u,e,o,t),x=Object.keys(h);for(let[N,T]of Object.entries(h))c[N]=T;console.log(`[tools] \u2713 composio '${r.id}' \u2192 ${x.length} tool(s)`)}catch(h){console.error(`[tools] \u2717 composio '${r.id}': ${String(h)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${r.id}': ${String(h)}`})}continue}if(r.kind==="skill"){if(u.kind!=="skill"){console.error(`[tools] \u2717 skill '${r.id}': row is of kind '${u.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${r.id}' is not a skill`});continue}let h=u.name;if(c[h]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${h}' \u2014 builtin/other already registered, skipping skill '${r.id}'`});continue}try{c[h]=Zt(u,e,o,t),l.push(u);let x=typeof u.execution=="string"?JSON.parse(u.execution):u.execution||{},N=Array.isArray(x.references)?x.references.map(T=>T==null?void 0:T.name):[];console.log(`[tools] \u2713 skill '${r.id}' \u2192 '${h}' (refs: ${N.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:h,refCount:N.length,refs:N}})}catch(x){console.error(`[tools] \u2717 skill '${r.id}': ${String(x)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${r.id}': ${String(x)}`})}continue}let m=u.name;if(c[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 h=tt(u,e,o,t);c[m]=h,console.log(`[tools] \u2713 custom '${r.id}' \u2192 '${m}'`),console.log(`[tools] ${f(c[m])}`)}catch(h){console.error(`[tools] \u2717 custom '${r.id}': ${String(h)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${r.id}': ${String(h)}`})}continue}if(!Gt[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 w;try{w=await qo(`../tools/${r.id}.ts`)}catch{w=await zo(`../tools/${r.id}.js`)}let u;if(w[r.id])u=w[r.id];else if(w.default)u=w.default;else if(w.create)u=w.create;else{let $=Object.values(w);$.length>0&&(u=$[0])}if(!u){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${r.id}'`});continue}let m,h,x={};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)?h=$:typeof $=="object"&&$!==null&&$.type==="object"&&$.properties?(h=Lt($),h||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)?x=r.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${r.id}' \u2014 must be an object`}),x={}):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`}),x={}):x={}}let N=u(e,o,x,t);m&&N&&typeof N=="object"&&(N.description=m),h&&N&&typeof N=="object"&&(N.inputSchema=h),c[r.id]=N;let T=[];m&&T.push("description"),h&&T.push("inputSchema"),Object.keys(x).length&&T.push(`defaults(${Object.keys(x).join(",")})`);let k=T.length?` [overrides: ${T.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${r.id}'${k}`),console.log(`[tools] ${f(N)}`)}catch(w){console.error(`[tools] \u2717 builtin '${r.id}': ${String(w)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${r.id}': ${String(w)}`});continue}}if(l.length>0)if(c.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{c.readSkillRef=Qt(e,l,o,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${l.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:l.map(n=>n.name)}})}catch(n){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(n)}`)}return c}async function gt(e,o,i,t,s,c,f){var $,P,b,F;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let d=!1;try{let R=($=i.flowData)==null?void 0:$.state;if(R&&R.edges&&R.nodes){let D=R.edges.filter(M=>M.source===o.id);if(D.length>0){let M=R.nodes.find(V=>V.id===D[0].target);M&&M.type==="answerNode"&&(d=!0)}}}catch(R){console.error("Error determining next node for streaming:",R)}let p=q(o.data.template,o,i,t,{sessionEnv:e});(!p||!p.trim())&&(p="Answer straight forward to the user, dont offer any other option to continue");let a=p,l=q(o.data.user_template||"",o,i,t,{sessionEnv:e}),y=R=>R&&Object.fromEntries(Object.keys(R).map(D=>[D,"[redacted]"])),n=e!=null&&e.secrets||e!=null&&e.userAuth?{...e,secrets:y(e.secrets),userAuth:y(e.userAuth)}:e,g=q(o.data.template,o,i,void 0,{sessionEnv:n})||a,r=q(o.data.user_template||"",o,i,void 0,{sessionEnv:n});t==null||t({type:`info:llmNodeRunner:${o.id}`,content:g}),t==null||t({type:`info:llmNodeRunner:${o.id}`,content:r});let w=(P=o==null?void 0:o.data)==null?void 0:P.window_size,u=Number(w);(!Number.isInteger(u)||u<=0)&&(u=5);let m=ao(o,i),h=no(o,i);t==null||t({type:"info:llmNodeRunner:attachments",content:{nodeId:o.id,refs:Array.isArray((b=o.data)==null?void 0:b.attachments)?o.data.attachments:[],images:m.length,documents:h?1:0}});let N=(await((F=e.getMessages)==null?void 0:F.call(e))??[]).slice(-u),T=N.filter(R=>R&&typeof R.role=="string"&&typeof R.content=="string");T.length!==N.length&&console.warn(`Filtered ${N.length-T.length} invalid messages from history`);let k=Qo(T,l,m,h);await Zo(p,k,e.conn,t,o,d,s,i,c,e,f)}async function Zo(e,o,i,t,s,c,f,d,p,a,l){var n;let y=Date.now();if(!((n=a.env)!=null&&n.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(g,r)=>{var D,M,V,_,X,U;let w,u={},m,h="none",x=!1,N,T=!1,k=!1,$=0,P=0,b=(D=s==null?void 0:s.data)==null?void 0:D.sendReasoning,F=b!==!1;try{let j=(M=s==null?void 0:s.data)==null?void 0:M.model,G=Array.isArray(j)?j[0]:j||"gpt_5_nano",A=Wt(s==null?void 0:s.data),I=await et(G,a,A);if(!I)throw new Error(`Model '${G}' not found in registry`);w=I.modelHandle,u=I.effectiveParams||{},h=I.reasoning.kind;let O=Kt(I.reasoning,(V=s==null?void 0:s.data)==null?void 0:V.reasoningEffort);x=F&&zt(I.reasoning);let W=typeof((_=s==null?void 0:s.data)==null?void 0:_.reasoningMaxTokens)=="number"?s.data.reasoningMaxTokens:void 0;m=Bt(I.provider,{effort:O,exposeReasoning:x,maxTokens:W}),O&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:O})),console.log(`[reasoning] ${JSON.stringify({model:G,provider:I.provider,capability:I.reasoning,requestedEffort:((X=s==null?void 0:s.data)==null?void 0:X.reasoningEffort)??null,resolvedEffort:O??null,sendReasoning:F,exposeReasoning:x,providerOptions:m??null},null,2)}`);for(let L of I.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:L});t==null||t({type:"info:llmNodeRunner:model",content:G}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(U=s==null?void 0:s.data)!=null&&U.generationPreset?{preset:s.data.generationPreset}:{},...u,...h!=="none"?{reasoning:h,configuredSendReasoning:b,sendReasoning:F,exposeReasoning:x,...O?{effort:O}:{}}:{}}})}catch(j){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(j)}`}),j}let R=await Yo(a,d,s,t);console.log(`[tools] node ${s.id} loaded ${Object.keys(R).length}: ${Object.keys(R).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:s.id,tools:Object.keys(R)}});try{let j=Bo({model:w,system:e,messages:o,stopWhen:(()=>{var L;let I=!!R.readSkillRef?10:5,O=Number(((L=s.data)==null?void 0:L.max_steps)??I),W=Number.isFinite(O)?Math.max(1,Math.min(30,O)):I;return Ko(W)})(),...Xt(u),...m?{providerOptions:m}:{},tools:R,onFinish:async A=>{var Nt,Rt;let I=A.text||"",O=A.reasoningText??((Nt=A.reasoning)==null?void 0:Nt.text)??"";if(console.log(`[reasoning] done: deltas=${$} chars=${P} result.reasoningText=${O.length} finishReason=${A.finishReason??"n/a"} reasoningTokens=${((Rt=A.usage)==null?void 0:Rt.reasoningTokens)??"n/a"}`),F&&x&&!T&&O&&i){T=!0;try{K(i,z.SERVER_REASONING_STREAM,O)}catch(uo){console.warn("Failed to send finished reasoning over connection",uo)}}let W={id:Go(),role:"assistant",type:"text",content:I,ts:Date.now()};c&&(a.setMessages?await a.setMessages(W):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),i&&F&&T&&!k&&(k=!0,K(i,z.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),c&&i&&K(i,z.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),f==null||f((s==null?void 0:s.id)||"llm_result",I),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(A)});let L=Date.now()-y,lo=N?N-y:void 0;l==null||l({type:"llm_telemetry",payload:{nodeId:s.id,totalLatency:L,timeToFirstToken:lo,model:A.response.modelId,usage:A.usage}}),l==null||l({type:"llm_result",payload:{result:A}})},onStepFinish:async A=>{let I=(O,W=200)=>{let L=typeof O=="string"?O:JSON.stringify(O);return L?L.length>W?`${L.slice(0,W)}\u2026(+${L.length-W})`:L:""};if(A.toolCalls&&A.toolCalls.length>0){for(let O of A.toolCalls)console.log(`[tools] \u2192 ${O.toolName}(${I(O.args??O.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${s.id}`,content:JSON.stringify(A.toolCalls)})}if(A.toolResults&&A.toolResults.length>0){for(let O of A.toolResults)console.log(`[tools] \u2190 ${O.toolName} \u2192 ${I(O.result??O.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${s.id}`,content:JSON.stringify(A.toolResults)})}},experimental_onToolCallStart:A=>{var I;t==null||t({type:"tool:execution",content:{nodeId:s.id,toolName:(I=A==null?void 0:A.toolCall)==null?void 0:I.toolName,status:"start"}})},experimental_onToolCallFinish:A=>{var I,O;t==null||t({type:"tool:execution",content:{nodeId:s.id,toolName:(I=A==null?void 0:A.toolCall)==null?void 0:I.toolName,status:((O=A==null?void 0:A.toolOutput)==null?void 0:O.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 O=A.chunk.text??A.chunk.delta??"";if(O&&(T=!0,$+=1,P+=O.length,$===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),F&&i&&O)try{K(i,z.SERVER_REASONING_STREAM,O)}catch(W){console.warn("Failed to send reasoning chunk over connection",W)}return}if(A.chunk.type==="text-delta"){if(N||(N=Date.now()),i&&F&&T&&!k){k=!0;try{K(i,z.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to send reasoning complete over connection",O)}}return}l==null||l({type:A.chunk.type,payload:{nodeId:s.id,chunk:A.chunk}});let I=`llm_chunk:${A.chunk.type}`;t==null||t({type:I,content:{...A}})}}),G=async()=>{let A="";for await(let I of j.fullStream)if(I.type==="text-delta"){if(A+=I.text,c&&i)try{K(i,z.SERVER_TEXT_STREAM,I.text)}catch(O){console.warn("Failed to send chunk over connection",O)}}else if(I.type==="finish-step"&&I.finishReason==="tool-calls"){if(c&&i&&A.trim())try{K(i,z.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to flush text segment over connection",O)}A=""}};await Promise.all([j,G()]),g(),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 Qo(e,o,i,t){let s=!!(i&&i.length>0),c=!!t,f=s||c,p=e.length>0&&e[e.length-1].role==="user"?e[e.length-1]:void 0,a=l=>{let y=[],n="";if(c&&(n+=`[Attached files]
|
|
15
|
+
${t}
|
|
16
|
+
[End of attached files]
|
|
17
|
+
|
|
18
|
+
`),l&&(n+=l),n&&y.push({type:"text",text:n}),s)for(let g of i)y.push({type:"image",image:g.data,mimeType:g.mimeType});return y};return o&&p&&p.content===o?[...e.slice(0,-1).map(y=>({role:y.role,content:y.content})),{role:"user",content:a(o)}]:o?[...e.map(l=>({role:l.role,content:l.content})),{role:"user",content:a(o)}]:f&&p?[...e.slice(0,-1).map(y=>({role:y.role,content:y.content})),{role:"user",content:a(p.content)}]:e.map(l=>({role:l.role,content:l.content}))}async function wt(e,o,i,t,s,c,f){var l,y,n,g,r,w,u;console.log(`**** MEMO Node id: ${o.id} ****`),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let d="",p=!1,a=Date.now();try{t==null||t({type:"info:memoNodeRunner",content:"Starting memo node execution"});let m=String(((l=o.data)==null?void 0:l.query_key)||"user_input"),h=H(m,{context:i.context??{},results:i.results??{},nodes:((n=(y=i.flowData)==null?void 0:y.state)==null?void 0:n.nodes)??[],edges:((r=(g=i.flowData)==null?void 0:g.state)==null?void 0:r.edges)??[],currentNodeId:o.id});if(h.missing)throw new Error(`Memo query "${m}" did not produce a value`);if(!e.env||!e.ctx){t==null||t({type:"error:memoNodeRunner",content:"Missing env or ctx"}),s==null||s(o.id,d);return}if(!o.data.rag_id){t==null||t({type:"error:memoNodeRunner",content:"Missing rag_id"}),s==null||s(o.id,d);return}let x=String(h.value??"");t==null||t({type:"info:memoNodeRunner",content:`Query text: ${x}`}),t==null||t({type:"info:memoNodeRunner",content:"Generating embedding for query"});let N=await At(e,x,!0);t==null||t({type:"info:memoNodeRunner",content:`Embedding generated successfully, length: ${N.data[0].length}`});let T=Array.isArray(o.data.rag_id)?o.data.rag_id:[o.data.rag_id],k=[];for(let F of T){t==null||t({type:"info:memoNodeRunner",content:`Executing RAG query with namespace: ${F}`});let R=await e.env[`VDB_${(w=i.flowData)==null?void 0:w.tenant}_1024`].query(N.data[0],{namespace:F,topK:o.data.topk,returnMetadata:"all"});t==null||t({type:"info:memoNodeRunner",content:`RAG query completed for namespace ${F}, matches: ${((u=R.matches)==null?void 0:u.length)||0}`}),Array.isArray(R.matches)&&k.push(...R.matches)}let $=Date.now()-a;d=k.map(F=>{var R;return(R=F.metadata)==null?void 0:R.value}).filter(F=>typeof F=="string").join(`
|
|
19
|
+
|
|
20
|
+
`),f==null||f({type:"memo_search",payload:{nodeId:o.id,searchLatencyMs:$,retrievedContext:d}}),t==null||t({type:"info:memoNodeRunner",content:`Context retrieval complete, length: ${d.length}, preview: ${d.substring(0,200)}...`}),t==null||t({type:"info:memoNodeRunner",content:"Memo node execution completed successfully"}),p=!0}catch(m){throw console.error("Error processing MemoNode:",m),t==null||t({type:"error:memoNodeRunner",content:`Memo node execution failed: ${m}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(m)}}),m}finally{p&&(s==null||s(o.id,d),t==null||t({type:"info:memoNodeRunner",content:`onResult called with context length: ${d.length}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}}))}}async function ht(e,o,i,t,s,c,f){var l,y,n,g,r,w,u,m;console.log(`**** START Node ${o.id} ****`),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}}),t==null||t({type:"info:flow",content:i}),f==null||f({type:"start_node",payload:{userMessage:(l=i==null?void 0:i.context)==null?void 0:l.user_input}});let d=((y=o.data)==null?void 0:y.allow_images)!==!1,p=((n=o.data)==null?void 0:n.allow_documents)!==!1;!d&&(i!=null&&i.context)&&(i.context.user_images=[],c==null||c({...i})),!p&&(i!=null&&i.context)&&(i.context.files="",c==null||c({...i}));let a={};for(let h of E(o.data))a[h.name]=(g=i==null?void 0:i.context)==null?void 0:g[h.name];s==null||s(o.id,{...a,user_input:(r=i==null?void 0:i.context)==null?void 0:r.user_input,images:d?(w=i==null?void 0:i.context)==null?void 0:w.user_images:[],files:p?(u=i==null?void 0:i.context)==null?void 0:u.files:"",memory:((m=i==null?void 0:i.context)==null?void 0:m.memory)??""}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}function Xi(e,o,i){let t=o;async function s(){var a;if(await((a=i==null?void 0:i.shouldStop)==null?void 0:a.call(i)))throw new it}async function c(a){let l=a;for(t.executedNodes=t.executedNodes||[],t.context=t.context||{},t.results=t.results||{};l&&l.id;)await s(),await f(l),await s(),l=vo(l,t.flowData,t)}async function f(a){var r,w;let l=p[a.type];if(!l){(r=i==null?void 0:i.onError)==null||r.call(i,`Unknown node type: ${a.type}`);return}t.executedNodes=t.executedNodes||[],t.executedNodes.push({id:a.id,type:a.type,label:typeof((w=a.data)==null?void 0:w.label)=="string"?a.data.label:void 0}),t.lastNodeId=a.id;let y=u=>{var m;return(m=i==null?void 0:i.onServerEvent)==null?void 0:m.call(i,{...u,ts:Date.now()})},n=u=>{var m,h;if((m=i==null?void 0:i.onTelemetry)==null||m.call(i,u),u.type==="llm_telemetry"||u.type==="class_telemetry"||u.type==="memory_update"){let x=(h=u.payload)==null?void 0:h.usage;x&&(t.tokenUsage=t.tokenUsage||{promptTokens:0,completionTokens:0,totalTokens:0},t.tokenUsage.promptTokens+=x.promptTokens||0,t.tokenUsage.completionTokens+=x.completionTokens||0,t.tokenUsage.totalTokens+=x.totalTokens||0)}};return await l(e,a,t,y,(u,m)=>{t.results[u]=m},i==null?void 0:i.onChangeState,n)}let d=async a=>{var g,r,w,u,m,h,x;let l=Date.now(),y="completed",n;try{await s();let N=typeof a=="string"?Ft(a):a,T=(N==null?void 0:N.text)||"",k=(N==null?void 0:N.images)||[],$=(N==null?void 0:N.documents)||[],P=await Et($,e.env),b=P.length>0?P.map(D=>`--- file: ${D.name} ---
|
|
21
|
+
${D.text}`).join(`
|
|
22
|
+
|
|
23
|
+
`):"";t.context={user_input:T,user_images:k,files:b},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},t.executedNodes=[],(g=i==null?void 0:i.onServerEvent)==null||g.call(i,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:F,error:R}=Eo(t.flowData);if(!F)y="failed",n=R||"Flow Format Error",(r=i==null?void 0:i.onError)==null||r.call(i,n);else{let D=E(F.data),{values:M,errors:V}=$t(D,N==null?void 0:N.inputs);if(V.length>0)return y="failed",n=`Invalid flow inputs: ${V.join("; ")}`,(w=i==null?void 0:i.onError)==null||w.call(i,n),{status:y,error:n};if(t.context={...t.context,inputs:M,...M},t.context.user_input||(t.context.user_input=T),It(F.data)){let _=Ot(kt(F.data));t.context.memory=_t(e.agentMemory||"",_).content}else t.context.memory="";await c(F),(u=i==null?void 0:i.onServerEvent)==null||u.call(i,{type:"agent:telemetry",content:{durationMs:Date.now()-l,tokenUsage:t.tokenUsage},timestamp:Date.now()})}}catch(N){N instanceof it?(y="stopped",n=N.message,(m=i==null?void 0:i.onServerEvent)==null||m.call(i,{type:"agent:stopped",content:n,timestamp:Date.now()})):(y="failed",n=N instanceof Error?N.message:"Agent execution failed",(h=i==null?void 0:i.onError)==null||h.call(i,n))}finally{(x=i==null?void 0:i.onServerEvent)==null||x.call(i,{type:"agent:complete",content:{status:y,durationMs:Date.now()-l},timestamp:Date.now()})}return{status:y,error:n}},p={startNode:ht,classifierNode:yt,llmNode:gt,memoNode:wt,answerNode:rt,apiNode:dt,toolNode:ut,workerNode:pt};return d}var it=class extends Error{constructor(){super("Stopped by user"),this.name="FlowExecutionStoppedError"}};function Eo(e){var l,y;let o=(e==null?void 0:e.state)??e;if(!o||!o.nodes||!o.edges||o.edges.length===0)return{error:"Flow is missing state, nodes, or edges."};if(o.schemaVersion!==3)return{error:"Flow uses an unsupported variable schema. Recreate it in Agent Design 3.0."};for(let n of o.nodes){if(((l=n.data)==null?void 0:l.varMapping)!==void 0)return{error:`Flow uses removed varMapping on node ${n.id}.`};let g=Dt(n);if(g.length>0)return{error:g[0]}}let i=o.nodes.filter(n=>n.type==="startNode");if(i.length!==1)return{error:`Flow must include exactly one START node, found ${i.length}.`};let t=i[0],s=o.nodes.filter(n=>n.type==="answerNode");if(s.length===0)return{error:"Flow must include at least one ANSWER node."};let c=new Map;for(let n of o.edges)c.has(n.source)||c.set(n.source,[]),c.get(n.source).push(n.target);let f=new Map;for(let n of o.edges)f.has(n.target)||f.set(n.target,[]),f.get(n.target).push(n.source);let d=co(t.id,c),p=new Set;for(let n of s){let g=co(n.id,f);for(let r of g)p.add(r)}let a=[];for(let n of d)if(!p.has(n)){let g=o.nodes.find(r=>r.id===n);if(g){let r=((y=g.data)==null?void 0:y.label)||"";a.push(`${n}(${r},${g.type})`)}}return a.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${a.join(", ")}`}:{startNode:t}}function co(e,o){let i=new Set,t=[e];for(i.add(e);t.length>0;){let s=t.shift(),c=o.get(s)||[];for(let f of c)i.has(f)||(i.add(f),t.push(f))}return i}function So(e,o){var i;return((i=e.state)==null?void 0:i.nodes.find(t=>t.id===o))||null}function vo(e,o,i){var d;let t=o==null?void 0:o.state;if(!t)return null;let s=t.edges.filter(p=>p.source===e.id);if(s.length===0)return null;let c=s[0].target;if(e.type==="classifierNode"&&((d=i==null?void 0:i.context)!=null&&d.classified_id)){let p=i.context.classified_id,a=s.find(l=>l.sourceHandle===`source-${p}`);a?c=a.target:console.log(`No matching edge, falling back to first: ${c}`)}return So(o,c)}export{K as a,fo as b,eo as c,Te as d,Wo as e,et as f,Ue as g,Xi as h,it as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as t,c as i,k as s}from"./chunk-XXB57DMN.js";import{Composio as a}from"@composio/core";function m(r){return typeof r!="string"?void 0:r.trim()||void 0}async function k(r,e){let c=i(r),l=new a({apiKey:c}),u=t(e.connectionScope),n=m(e.toolVersion);try{n||console.warn(`[composioDirectTool] No toolVersion for ${e.toolSlug}; executing with dangerouslySkipVersionCheck`);let o=await l.tools.execute(e.toolSlug,{userId:u,arguments:e.arguments,...n?{version:n}:{dangerouslySkipVersionCheck:!0}});return o&&typeof o=="object"&&"successful"in o&&o.successful===!1?{ok:!1,data:null,error:typeof o.error=="string"&&o.error.trim()?o.error:"Tool execution failed"}:{ok:!0,data:o&&typeof o=="object"&&"data"in o?o.data:o,error:null}}catch(o){return s(o)?{ok:!1,error:"This connector is not connected. Ask a tenant admin to connect it in Tools."}:{ok:!1,error:o instanceof Error?o.message:String(o)}}}export{k as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SessionPreset as g}from"@composio/core";function U(n,o){var t;return(o==null?void 0:o.trim())||((t=n.connectionScope)==null?void 0:t.trim())||void 0}function R(n){let o=n.trim();if(!o)throw new Error("Composio connection scope is required");return o}var m=/https:\/\/connect\.composio\.dev\/link\/[^\s)\]"']+/i,C=/"redirect_?[Uu]rl"\s*:\s*"(https?:\/\/[^"]+)"/;function b(n){var t;let o=(t=n.publicOrigin)==null?void 0:t.trim();return o?o.replace(/\/$/,""):O(n.env)}function v(n){var e,s,i,r;let o=(s=(e=n.secrets)==null?void 0:e.COMPOSIO_API_KEY)==null?void 0:s.trim();if(o)return o;let t=(r=(i=n.env)==null?void 0:i.COMPOSIO_API_KEY)==null?void 0:r.trim();if(t)return t;throw new Error("COMPOSIO_API_KEY is not configured (register tenant secret or set env COMPOSIO_API_KEY)")}function k(n){if(!n)return[];let o=[];for(let t of Object.values(n))o.push(...a(t.enable));return[...new Set(o)].sort()}function A(n){return JSON.stringify({toolkits:n.toolkits,tools:n.tools,authMode:n.authMode,authConfigs:n.authConfigs,workbench:n.workbench,sessionPreset:n.sessionPreset,sessionPreload:n.sessionPreload})}function L(n,o){var s;let t=E(n.tools),e=n.sessionPreset==="direct_tools";return{toolkits:n.toolkits,...n.authConfigs?{authConfigs:n.authConfigs}:{},...t?{tools:t}:{},manageConnections:o.manageConnections,workbench:o.workbench,...e?{sessionPreset:g.DIRECT_TOOLS}:{},...!e&&((s=n.sessionPreload)!=null&&s.enabled)?(()=>{let i=k(n.tools);return i.length>0?{preload:{tools:i}}:{}})():{}}}function h(n,o){var e;let t=(e=n==null?void 0:n.context)==null?void 0:e.user;return t!=null&&t.email||t!=null&&t.id?t:o.user}function j(n,o,t){var r,c,l;let e=h(o,n),s=(r=e==null?void 0:e.email)==null?void 0:r.trim();if(s&&s!=="default")return s;if((t==null?void 0:t.allowChatIdFallback)===!1)throw new Error("Composio user ID unavailable \u2014 log in so your tool-editor connections apply to your email");let i=(l=(c=o==null?void 0:o.flowData)==null?void 0:c.chatId)==null?void 0:l.trim();if(i&&i!=="default")return i;throw new Error("Composio user ID unavailable \u2014 log in (access_token cookie) or provide a chat session id")}function y(n){let o=JSON.stringify(n);return(typeof btoa=="function"?btoa(o):Buffer.from(o,"utf8").toString("base64")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function O(n){var t;let o=(t=n==null?void 0:n.ORA_PUBLIC_URL)==null?void 0:t.trim();return o?o.replace(/\/$/,""):"http://localhost:5173"}function x(n,o,t,e){let s=b(n),i=y({flowId:o??"",sessionId:t??"",toolRowId:e});return`${s}/api/composio/callback?ctx=${encodeURIComponent(i)}`}function a(n){return Array.isArray(n)?n.filter(o=>typeof o=="string"&&!!o.trim()).map(o=>o.trim()):[]}function S(n,o){var i;let t=n.toUpperCase(),e=(i=t.split("_")[0])==null?void 0:i.toLowerCase();if(!e)return;let s=o.find(r=>r.toLowerCase()===e);return s||o.find(r=>t.startsWith(`${r.toUpperCase()}_`))}function w(n,o){let t={};for(let e of n){let s=S(e,o);s&&(t[s]||(t[s]=[]),t[s].push(e))}return Object.fromEntries(Object.entries(t).map(([e,s])=>[e,{enable:s}]))}function E(n){if(!n)return;let o={};for(let[t,e]of Object.entries(n)){let s=a(e.enable),i=a(e.disable);s.length?o[t]={enable:s}:i.length&&(o[t]={disable:i})}return Object.keys(o).length>0?o:void 0}function _(n,o,t){let e=new Set(o.map(c=>c.trim()).filter(Boolean)),s={};if(n&&typeof n=="object")for(let[c,l]of Object.entries(n)){if(!e.has(c)||!l||typeof l!="object")continue;let p=l,u=a(p.enable),f=a(p.disable);u.length===0&&f.length===0||(s[c]={...u.length?{enable:u}:{},...f.length?{disable:f}:{}})}if(Object.keys(s).length>0)return s;let i=a(t==null?void 0:t.tools);if(i.length===0)return;let r=w(i,o);return Object.keys(r).length>0?r:void 0}function M(n){var c;let o=n&&typeof n=="object"?n:{},t=Array.isArray(o.toolkits)?o.toolkits.filter(l=>typeof l=="string"&&l.trim()):[];if(t.length===0)throw new Error("Composio tool execution.toolkits must be a non-empty string array");let e=_(o.tools,t,o.preload),s=typeof o.connectionScope=="string"&&o.connectionScope.trim()?o.connectionScope.trim():void 0,i=o.sessionPreset==="direct_tools"?"direct_tools":void 0,r=((c=o.sessionPreload)==null?void 0:c.enabled)===!0?{enabled:!0}:void 0;return{toolkits:t,authMode:o.authMode==="manual"?"manual":"in_app",authConfigs:o.authConfigs,...s?{connectionScope:s}:{},...e?{tools:e}:{},manageConnections:o.manageConnections,workbench:o.workbench??{enable:!0},...i?{sessionPreset:i}:{},...r?{sessionPreload:r}:{}}}function F(n,o){var e,s;return n.authMode==="manual"?!1:{callbackUrl:((s=(e=n.manageConnections)==null?void 0:e.callbackUrl)==null?void 0:s.trim())||o}}function K(n){let o=String((n==null?void 0:n.message)??n??"").toLowerCase();return o.includes("not connected")||o.includes("not authenticated")||o.includes("connection required")||o.includes("no active connection")||o.includes("authorize")||o.includes("authentication")||o.includes("connect link")||o.includes("no connected account")||o.includes("composio_manage_connections")}function T(n){if(typeof n!="string")return;let o=n.trim();if(o.startsWith("http"))return o}function I(n){for(let o of["redirectUrl","redirect_url","composio_link_redirect_url","url","link"]){let t=T(n[o]);if(t)return d(t)??t}}function d(n){if(n&&typeof n=="object"&&!Array.isArray(n)){let e=I(n);return e||d(JSON.stringify(n))}if(typeof n!="string")return;let o=n.match(m);if(o!=null&&o[0])return o[0];let t=n.match(C);if(t!=null&&t[1]){let e=t[1].replace(/\\u0026/g,"&").replace(/\\\//g,"/");return d(e)??e}}function N(n,o){var t;if(typeof n=="string"){let e=n.toLowerCase();for(let s of(o==null?void 0:o.toolkits)??[])if(e.includes(s.toLowerCase()))return s}return(t=o==null?void 0:o.toolkits)==null?void 0:t[0]}export{U as a,R as b,v as c,
|
|
1
|
+
import{SessionPreset as g}from"@composio/core";function U(n,o){var t;return(o==null?void 0:o.trim())||((t=n.connectionScope)==null?void 0:t.trim())||void 0}function R(n){let o=n.trim();if(!o)throw new Error("Composio connection scope is required");return o}var m=/https:\/\/connect\.composio\.dev\/link\/[^\s)\]"']+/i,C=/"redirect_?[Uu]rl"\s*:\s*"(https?:\/\/[^"]+)"/;function b(n){var t;let o=(t=n.publicOrigin)==null?void 0:t.trim();return o?o.replace(/\/$/,""):O(n.env)}function v(n){var e,s,i,r;let o=(s=(e=n.secrets)==null?void 0:e.COMPOSIO_API_KEY)==null?void 0:s.trim();if(o)return o;let t=(r=(i=n.env)==null?void 0:i.COMPOSIO_API_KEY)==null?void 0:r.trim();if(t)return t;throw new Error("COMPOSIO_API_KEY is not configured (register tenant secret or set env COMPOSIO_API_KEY)")}function k(n){if(!n)return[];let o=[];for(let t of Object.values(n))o.push(...a(t.enable));return[...new Set(o)].sort()}function A(n){return JSON.stringify({toolkits:n.toolkits,tools:n.tools,authMode:n.authMode,authConfigs:n.authConfigs,workbench:n.workbench,sessionPreset:n.sessionPreset,sessionPreload:n.sessionPreload})}function L(n,o){var s;let t=E(n.tools),e=n.sessionPreset==="direct_tools";return{toolkits:n.toolkits,...n.authConfigs?{authConfigs:n.authConfigs}:{},...t?{tools:t}:{},manageConnections:o.manageConnections,workbench:o.workbench,...e?{sessionPreset:g.DIRECT_TOOLS}:{},...!e&&((s=n.sessionPreload)!=null&&s.enabled)?(()=>{let i=k(n.tools);return i.length>0?{preload:{tools:i}}:{}})():{}}}function h(n,o){var e;let t=(e=n==null?void 0:n.context)==null?void 0:e.user;return t!=null&&t.email||t!=null&&t.id?t:o.user}function j(n,o,t){var r,c,l;let e=h(o,n),s=(r=e==null?void 0:e.email)==null?void 0:r.trim();if(s&&s!=="default")return s;if((t==null?void 0:t.allowChatIdFallback)===!1)throw new Error("Composio user ID unavailable \u2014 log in so your tool-editor connections apply to your email");let i=(l=(c=o==null?void 0:o.flowData)==null?void 0:c.chatId)==null?void 0:l.trim();if(i&&i!=="default")return i;throw new Error("Composio user ID unavailable \u2014 log in (access_token cookie) or provide a chat session id")}function y(n){let o=JSON.stringify(n);return(typeof btoa=="function"?btoa(o):Buffer.from(o,"utf8").toString("base64")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function O(n){var t;let o=(t=n==null?void 0:n.ORA_PUBLIC_URL)==null?void 0:t.trim();return o?o.replace(/\/$/,""):"http://localhost:5173"}function x(n,o,t,e){let s=b(n),i=y({flowId:o??"",sessionId:t??"",toolRowId:e});return`${s}/api/composio/callback?ctx=${encodeURIComponent(i)}`}function a(n){return Array.isArray(n)?n.filter(o=>typeof o=="string"&&!!o.trim()).map(o=>o.trim()):[]}function S(n,o){var i;let t=n.toUpperCase(),e=(i=t.split("_")[0])==null?void 0:i.toLowerCase();if(!e)return;let s=o.find(r=>r.toLowerCase()===e);return s||o.find(r=>t.startsWith(`${r.toUpperCase()}_`))}function w(n,o){let t={};for(let e of n){let s=S(e,o);s&&(t[s]||(t[s]=[]),t[s].push(e))}return Object.fromEntries(Object.entries(t).map(([e,s])=>[e,{enable:s}]))}function E(n){if(!n)return;let o={};for(let[t,e]of Object.entries(n)){let s=a(e.enable),i=a(e.disable);s.length?o[t]={enable:s}:i.length&&(o[t]={disable:i})}return Object.keys(o).length>0?o:void 0}function _(n,o,t){let e=new Set(o.map(c=>c.trim()).filter(Boolean)),s={};if(n&&typeof n=="object")for(let[c,l]of Object.entries(n)){if(!e.has(c)||!l||typeof l!="object")continue;let p=l,u=a(p.enable),f=a(p.disable);u.length===0&&f.length===0||(s[c]={...u.length?{enable:u}:{},...f.length?{disable:f}:{}})}if(Object.keys(s).length>0)return s;let i=a(t==null?void 0:t.tools);if(i.length===0)return;let r=w(i,o);return Object.keys(r).length>0?r:void 0}function M(n){var c;let o=n&&typeof n=="object"?n:{},t=Array.isArray(o.toolkits)?o.toolkits.filter(l=>typeof l=="string"&&l.trim()):[];if(t.length===0)throw new Error("Composio tool execution.toolkits must be a non-empty string array");let e=_(o.tools,t,o.preload),s=typeof o.connectionScope=="string"&&o.connectionScope.trim()?o.connectionScope.trim():void 0,i=o.sessionPreset==="direct_tools"?"direct_tools":void 0,r=((c=o.sessionPreload)==null?void 0:c.enabled)===!0?{enabled:!0}:void 0;return{toolkits:t,authMode:o.authMode==="manual"?"manual":"in_app",authConfigs:o.authConfigs,...s?{connectionScope:s}:{},...e?{tools:e}:{},manageConnections:o.manageConnections,workbench:o.workbench??{enable:!0},...i?{sessionPreset:i}:{},...r?{sessionPreload:r}:{}}}function F(n,o){var e,s;return n.authMode==="manual"?!1:{callbackUrl:((s=(e=n.manageConnections)==null?void 0:e.callbackUrl)==null?void 0:s.trim())||o}}function K(n){let o=String((n==null?void 0:n.message)??n??"").toLowerCase();return o.includes("not connected")||o.includes("not authenticated")||o.includes("connection required")||o.includes("no active connection")||o.includes("authorize")||o.includes("authentication")||o.includes("connect link")||o.includes("no connected account")||o.includes("composio_manage_connections")}function T(n){if(typeof n!="string")return;let o=n.trim();if(o.startsWith("http"))return o}function I(n){for(let o of["redirectUrl","redirect_url","composio_link_redirect_url","url","link"]){let t=T(n[o]);if(t)return d(t)??t}}function d(n){if(n&&typeof n=="object"&&!Array.isArray(n)){let e=I(n);return e||d(JSON.stringify(n))}if(typeof n!="string")return;let o=n.match(m);if(o!=null&&o[0])return o[0];let t=n.match(C);if(t!=null&&t[1]){let e=t[1].replace(/\\u0026/g,"&").replace(/\\\//g,"/");return d(e)??e}}function N(n,o){var t;if(typeof n=="string"){let e=n.toLowerCase();for(let s of(o==null?void 0:o.toolkits)??[])if(e.includes(s.toLowerCase()))return s}return(t=o==null?void 0:o.toolkits)==null?void 0:t[0]}export{U as a,R as b,v as c,k as d,A as e,L as f,j as g,x as h,M as i,F as j,K as k,d as l,N as m};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
async function s(o){let n=await fetch(`${o.HX_ORA_URL}/internal/tools`,{method:"GET",headers:{Authorization:`${o.HX_API_KEY}`},cache:"no-store"});if(!n.ok)throw new Error("Failed to fetch tool defs");return(await n.json()).tools??[]}async function i(o,n){let t=await fetch(`${n.HX_ORA_URL}/internal/models/${o}`,{method:"GET",headers:{Authorization:`${n.HX_API_KEY}`},cache:"no-store"});if(!t.ok)throw new Error(`Failed to fetch model ${o} from registry`);return(await t.json()).model}async function a(o,n,t){let e=await fetch(`${o.HX_ORA_URL}/internal/tools/${n}/refs/${encodeURIComponent(t)}`,{method:"GET",headers:{Authorization:`${o.HX_API_KEY}`},cache:"no-store"});if(!e.ok)throw e.status===404?new Error(`Reference "${t}" not found`):new Error(`Failed to fetch skill reference "${t}"`);let r=await e.json();if(!r.ref)throw new Error(`Reference "${t}" not found in response`);return r.ref}export{s as a,i as b,a as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-V35SRZAO.js";import"./chunk-XXB57DMN.js";import"./chunk-3TXHFKDN.js";export{a as executeComposioDirectTool};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
1
|
+
import{a}from"./chunk-6AZ7RATD.js";import"./chunk-XXB57DMN.js";import"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{a as loadComposioTools};
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as k,b as
|
|
2
|
-
`)}function
|
|
3
|
-
`)}function
|
|
1
|
+
import{a as k,b as Un,c as _e,d as be,e as Gn,f as Pe,g as Jn,h as Me,i as Wn}from"./chunk-BBJLGBLT.js";import"./chunk-V35SRZAO.js";import{c as _n}from"./chunk-YFOFZWIB.js";import"./chunk-6AZ7RATD.js";import"./chunk-XXB57DMN.js";import"./chunk-3K4IMMLP.js";import{a as Yn,b as Bn}from"./chunk-VS4EXG76.js";import{A as Pn,B as Mn,C as Nn,D as Dn,E as Oe,F as $n,G as Fn,H as Ln,I as Hn,J as jn,K as Kn,L as Xn,M as qn,N as Vn,O as ve,P as Ce,Q as zn,a as I,b as he,c as Yt,d as M,e as we,f as Bt,g as Qt,h as Zt,i as en,j as tn,k as Re,l as H,m as nn,n as Se,o as Ee,p as Ie,q as Te,r as xe,s as ke,t as Y,u as Ae,v as Ue,w as bn,x as On,y as vn,z as Cn}from"./chunk-4XJVXKXR.js";import{A as kn,B as An,a as L,b as zt,c as ge,d as Wt,e as ye,f as rn,g as sn,h as on,i as an,j as cn,k as ln,l as un,m as dn,n as pn,o as mn,p as fn,q as gn,r as yn,s as hn,t as wn,u as Rn,v as Sn,w as En,x as In,y as Tn,z as xn}from"./chunk-J4LJZZ67.js";import{a as Ht}from"./chunk-RYHQGPX5.js";import{a as jt}from"./chunk-R6EKV3WR.js";import{a as qt}from"./chunk-6HY7QUMP.js";import{a as Kt,b as Xt}from"./chunk-V6JSMX5A.js";import{a as Jt}from"./chunk-Q7QHJJGR.js";import{a as v,b as P,c as Vt,d as Gt}from"./chunk-YLDLDEUP.js";import{a as fe}from"./chunk-U56YWPSI.js";import"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";import{Agent as kt}from"agents";import{nanoid as At}from"nanoid";async function at(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 Ne(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 j(t){t.sql`DELETE FROM messages`}async function De(t){await at(t)}function B(t){return{"Content-Type":"application/json",Authorization:t.HX_API_KEY}}function K(t){return!!(t!=null&&t.HX_ORA_URL)&&!!(t!=null&&t.HX_API_KEY)}var it="anonymous:";function $e(t,e){return(t==null?void 0:t.trim())||`${it}${e}`}async function Q(t,e){if(!K(t))return null;let r=await fetch(`${t.HX_ORA_URL}/internal/runs`,{method:"POST",headers:B(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 N(t,e){if(!K(t))return{claimed:!0};let r=await fetch(`${t.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/claim`,{method:"POST",headers:B(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 X(t,e,r,n=3){if(!K(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:B(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 Fe(t,e){if(!K(t))return Promise.resolve();try{return await Q(t,e)}catch(r){return console.error("[oraTriggers] recordRun failed",r),null}}var Z=Object.freeze({}),ct="__SYSTEM_";function Le(t){return t.startsWith(ct)}function lt(t){let e={};for(let[r,n]of Object.entries(t))Le(r)||(e[r]=n);return Object.freeze(e)}async function q(t,e){if(!e)return Z;if(t.HX_ORA_URL&&t.HX_API_KEY)try{let s=await fetch(`${t.HX_ORA_URL}/internal/secrets`,{headers:{Authorization:t.HX_API_KEY}});if(s.ok){let o=await s.json();if(o.secrets)return lt(o.secrets)}else console.warn(`[secrets] API failed with status ${s.status}, falling back to KV`)}catch(s){console.error("[secrets] API request failed, falling back to KV",s)}let r=t.ORA_SECRETS;if(!r)return Z;let n=`${e}:`;try{let s=await r.list({prefix:n,limit:1e3});s.list_complete===!1&&console.warn(`[secrets] tenant=${e} exceeded list page; truncating to first 1000 keys`);let o=s.keys.filter(i=>!Le(i.name.slice(n.length))),a=await Promise.all(o.map(async i=>{let d=await r.get(i.name);return d!==null?[i.name.slice(n.length),d]:null})),c={};for(let i of a){if(!i)continue;let[d,u]=i;d&&(c[d]=u)}return Object.freeze(c)}catch(s){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,err:s}),Z}}function V(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 It}from"nanoid";import{streamText as ut}from"ai";var dt={short:`Up to ${H("short")} markdown lines (one fact or bullet per line). Keep constraints, working agreements, and the outline of anything already settled.`,medium:`Up to ${H("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 ${H("long")} markdown lines. Same as medium, with one-line context on a decision or plan block when later turns will need it.`},pt=12,mt=400,He=700;function ft(t,e=pt){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"?He:mt,c=o.trim().replace(/\s+/g," ").slice(0,a);c&&n.push(`${s.role==="user"?"U":"A"}: ${c}`)}return n.join(`
|
|
2
|
+
`)}function gt(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 yt(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 ht(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 c=(o=t.results)==null?void 0:o[a.id];c!=null&&n.push(typeof c=="string"?c:JSON.stringify(c))}return n.join(`
|
|
3
|
+
`)}function wt(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.`,dt[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,He)}`:"",t.answers.trim()?`Answer outputs:
|
|
4
4
|
${t.answers.trim()}`:""].filter(Boolean).join(`
|
|
5
|
-
`);return{system:e,user:r}}function gt(t){return Te(t.previous,Ie(t.userText),t.maxTokens)}async function yt(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 ht(t){if(t.fullStream&&typeof t.fullStream[Symbol.asyncIterator]=="function")return yt({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 $e(t){var d;let e=V(t.engineState);if(!e)return{status:"skipped",reason:"start_node_missing"};if(!he(e))return{status:"skipped",reason:"memory_disabled"};let r=Re(e),n=ge(r),s=we(e),o=z(t.previousContent||""),a=pt(t.messages),c=mt(t.engineState),i=u=>{let y=gt({previous:o,userText:t.userText,maxTokens:n});return{status:"written",content:y,truncated:!1,modelId:s,fallback:!0,error:y?void 0:u}};try{let u=await be(s,t.sessionEnv,{maxOutputTokens:n});if(!u)throw new Error(`Memory model '${s}' not found in registry`);let y=Se(r,(d=u.reasoning)==null?void 0:d.kind),{system:f,user:p}=ft({previous:o,userText:t.userText,assistantText:a,answers:c,length:r,maxTokens:n,recentTurns:ut(t.messages)}),g=Ue(u.reasoning),m=_e(u.provider,{effort:g,exposeReasoning:!1,maxTokens:y}),h=at({model:u.modelHandle,system:f,messages:[{role:"user",content:p}],...Ae({...u.effectiveParams??{},maxOutputTokens:y}),...m?{providerOptions:m}:{}}),S=await ht(h),E=dt(await h.usage),R=z(S.text);if(Ee(R)&&(R=""),!R)return{...i(S.error||"Memory model returned empty text"),usage:E};let x=ye(R,n);return{status:"written",content:x.content,truncated:x.truncated,usage:E,modelId:s}}catch(u){let y=u instanceof Error?u.message:"Memory update failed";return console.error("Memory update failed:",u),i(y)}}async function Fe(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 C(r,t),a={...e,flowData:{...o,tenant:e.flowData.tenant,flowId:r,chatId:e.flowData.chatId}},c=o==null?void 0:o.stateVersion,i=typeof c=="number"&&c!==((s=e.flowData)==null?void 0:s.stateVersion);return{engineState:a,refreshed:i}}catch(o){return console.error(`[flowRefresh] fetch failed for flow ${r}:`,o),{engineState:e,refreshed:!1}}}function Le(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 He=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 o,a;let r=t.id||t.name||"",[n,s]=String(r).split("::");if(!n||!s)return null;try{let i=(o=(await b(n,e)).metadata)==null?void 0:o.tenant,d=await C(n,e),u=(a=t.state)==null?void 0:a.user,y={flowData:{...d,tenant:i,flowId:n,chatId:s},executedNodes:[],context:u?{user:u}:{}};return t.setState({...t.state,engineState:y}),y}catch(c){return console.error("Failed to initialize engine state:",c),null}}async function D(t){var J,F,Z,ee,te,ne,re,se,oe,ae;let{agent:e,env:r,ctx:n,payload:s,connection:o}=t,a=Date.now(),c=[],i=t.runId?xe():void 0,d=async()=>await _(e),u=async l=>{await Ce(e,l)},y=async l=>{if(e.state.modelsCache&&e.state.modelsCache[l])return e.state.modelsCache[l];try{let{fetchOraModel:w}=await import("./oraApi-4O3W5LXD.js"),T=await w(l,r);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[l]:T}}),T}catch(w){throw console.error(`Error fetching model ${l}:`,w),w}},f={id:wt(),role:"user",type:"text",content:s.text,images:s.images,ts:Date.now()};await u(f);let p={onChangeState:l=>{e.setState({...e.state,engineState:l})},onServerEvent:async l=>{var w;await((w=t.onServerEvent)==null?void 0:w.call(t,l)),c.push(l)},onTelemetry:async l=>{var w,T,U,ie,ce,le;await He({...l,userId:t.resolveUserId(),tenant:((T=(w=e.state.engineState)==null?void 0:w.flowData)==null?void 0:T.tenant)||"",flowId:((ie=(U=e.state.engineState)==null?void 0:U.flowData)==null?void 0:ie.flowId)||"",sessionId:((le=(ce=e.state.engineState)==null?void 0:ce.flowData)==null?void 0:le.chatId)||""},r)},onError:l=>{var w;(w=t.onError)==null||w.call(t,l),e.setState({...e.state,error:l})},shouldStop:t.shouldStop},g=e.state.engineState?{...e.state.engineState}:null;if(g){let{engineState:l,refreshed:w}=await Fe(r,g);g=l,w&&e.setState({...e.state,engineState:g,modelsCache:{}})}else if(g=await N(e,r),!g){let l="Failed to initialize agent";return p.onError(l),{status:"failed",error:l}}let m=t.secrets;if(!m||Object.keys(m).length===0){let l=(J=g.flowData)==null?void 0:J.tenant;m=l?await q(r,l):{},(F=t.onSecretsLoaded)==null||F.call(t,m)}let h=t.user??e.state.user??void 0;h&&!((Z=g.context)!=null&&Z.user)&&(g.context={...g.context||{},user:h});let S={env:r,ctx:n,conn:o,getMessages:d,setMessages:u,getOraModel:y,secrets:m,userAuth:t.userAuth,user:h,composioSessions:t.composioSessions,publicOrigin:t.publicOrigin,skillRefCache:t.skillRefCache,runId:t.runId,outputCollector:i,agentMemory:typeof((ee=e.state.memory)==null?void 0:ee.content)=="string"?e.state.memory.content:"",shouldStop:t.shouldStop,workerStack:(te=g.flowData)!=null&&te.flowId?[g.flowData.flowId]:[],workerCalls:{count:0}},E=await Oe(S,g,p)(s),R=e.state.engineState??g;if(E.status==="completed")try{let l=await $e({sessionEnv:S,engineState:R,previousContent:typeof((ne=e.state.memory)==null?void 0:ne.content)=="string"?e.state.memory.content:"",userText:s.text||"",messages:await d()});if(l.status==="skipped")await p.onServerEvent({type:"agent:memory",content:{skipped:!0,reason:l.reason},timestamp:Date.now()});else if(!l.content.trim())await p.onServerEvent({type:"agent:memory",content:{updated:!1,empty:!0,error:l.error,fallback:l.fallback},timestamp:Date.now()});else{let w={promptTokens:((re=R.tokenUsage)==null?void 0:re.promptTokens)??0,completionTokens:((se=R.tokenUsage)==null?void 0:se.completionTokens)??0,totalTokens:((oe=R.tokenUsage)==null?void 0:oe.totalTokens)??0};l.usage&&(w.promptTokens+=l.usage.promptTokens,w.completionTokens+=l.usage.completionTokens,w.totalTokens+=l.usage.totalTokens),R={...R,tokenUsage:w},e.setState({...e.state,engineState:R,memory:{content:l.content,updatedTs:Date.now(),...l.error?{lastError:l.error}:{},...l.fallback?{fallback:!0}:{}}}),await p.onTelemetry({type:"memory_update",payload:{model:l.modelId,truncated:l.truncated,usage:l.usage,fallback:l.fallback,error:l.error}}),await p.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 p.onServerEvent({type:"agent:memory",content:{error:w},timestamp:Date.now()})}if(E.status==="completed"&&t.runId&&(i!=null&&i.hasOutputs())){let{flowId:l,chatId:w}=R.flowData??{};if(!l||!w)E={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await ke(r,{flowId:l,sessionId:w,runId:t.runId,createdAt:new Date(a).toISOString(),data:i.snapshotData(),answerNodeIds:i.answerNodeIds()});let T={...R.results||{}};for(let U of i.answerNodeIds())T[U]={...T[U]||{},persisted:!0,runId:t.runId};R={...R,results:T},e.setState({...e.state,engineState:R})}catch(T){let U=T instanceof Error?T.message:"Structured output persistence failed";p.onError(U),await p.onServerEvent({type:"error:answer-output",content:{runId:t.runId,error:U},timestamp:Date.now()}),E={status:"failed",error:U}}}let{tenant:x,flowId:v,chatId:$}=R.flowData??{};return x&&v&&$&&n.waitUntil(Le(r,{id:`${v}::${$}`,tenant:x,flowId:v,sessionId:$,userId:t.resolveUserId(),title:(ae=s.text)==null?void 0:ae.slice(0,120),turnTs:a,events:c})),e.setState({...e.state,lastUpdated:new Date}),{status:E.status,error:E.error,engineState:R}}import{nanoid as Rt}from"nanoid";function St(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 je(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 c=typeof o.userId=="string"?P(o.userId):null,i=St(e),d=i==null?void 0:i.email;i?t.setState({...t.state,user:i,injectedUserId:d}):c&&!((s=t.state.user)!=null&&s.email)&&t.setState({...t.state,injectedUserId:c});let u=()=>d??c??t.state.injectedUserId??void 0;t.skillRefCache||(t.skillRefCache=new Map);let y=o.inputs&&typeof o.inputs=="object"?o.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 f=`run-${Rt(12)}`;await t.registerManualRun(f,a,u()),await M(r,f).catch(h=>{console.warn(`[AgentHTTP] could not mark manual run ${f} as running`,h)});let p;try{p=await D({agent:t,env:r,ctx:n,payload:{text:a,inputs:y},skillRefCache:t.skillRefCache,user:i??void 0,resolveUserId:u,runId:f,shouldStop:()=>t.isRunStopRequested(f)}),n.waitUntil(t.completeManualRun(f,p.status==="completed"?"succeeded":p.status==="stopped"?"skipped":"failed",p.error))}finally{await t.clearRunStopRequest(f)}if(p.status==="failed")return new Response(JSON.stringify({error:p.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});if(p.status==="stopped")return new Response(JSON.stringify({error:p.error||"Stopped by user"}),{status:409,headers:{"content-type":"application/json"}});let m=(await _(t)).reverse().find(h=>h.role==="assistant");return new Response(JSON.stringify({answer:(m==null?void 0:m.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 Ke(t){try{return await j(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 Xe="trigger:nonce:",Tt=900*1e3,Q="run:stop:",qe=class extends Et{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 _(this)}}async requestRunStop(e){return e!=null&&e.trim()?(await this.ctx.storage.put(`${Q}${e}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(e){return!!await this.ctx.storage.get(`${Q}${e}`)}async clearRunStopRequest(e){await this.ctx.storage.delete(`${Q}${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 _(this);return new Response(JSON.stringify(n),{headers:{"content-type":"application/json"}})}return e.method==="POST"&&r.pathname.endsWith("/message")?je(this,e,this.env,this.ctx):e.method==="DELETE"&&r.pathname.endsWith("/clear")?Ke(this):new Response("Ready to assist.")}async onConnect(e,r){var f,p,g,m,h;let[n,s]=e.server.split("::"),a=(f=(await b(n,this.env)).metadata)==null?void 0:f.tenant;this.secrets=await q(this.env,a),this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let c=null;if(r.request){try{this.publicOrigin=new URL(r.request.url).origin}catch{}let S=r.request.headers.get("X-User-Payload");if(S)try{c=JSON.parse(S)}catch(E){console.warn("Failed to parse X-User-Payload",E)}}let i=await C(n,this.env);this.setState({...this.state,user:c||null,sessionId:s,engineState:{flowData:{...i,tenant:a,flowId:n,chatId:s},executedNodes:[],context:c?{user:c}:{}}}),c||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let d=await _(this);k(e,I.SERVER_HISTORY,JSON.stringify({messages:d}));let y=(((p=i==null?void 0:i.state)==null?void 0:p.nodes)??(i==null?void 0:i.nodes)??[]).find(S=>S.type==="startNode");if(y){let S={allow_images:((g=y.data)==null?void 0:g.allow_images)??!1,allow_documents:((m=y.data)==null?void 0:m.allow_documents)??!1,greeting:(h=y.data)==null?void 0:h.greeting};k(e,I.SERVER_CONFIG,JSON.stringify(S))}}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 c={[I.USER_MESSAGE]:i=>this.onUserMessage(e,i),[I.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[I.USER_AUTH]:i=>this.onUserAuth(e,i),[I.USER_IDENTITY]:i=>this.onUserIdentity(e,i)}[s];c&&await c(o)}async onUserMessage(e,r){let n=me(r),s=`run-${It(12)}`;await this.registerManualRun(s,n.text),await M(this.env,s).catch(o=>{console.warn(`[AgentDO] could not mark manual run ${s} as running`,o)});try{let o=await D({agent:this,env:this.env,ctx:this.ctx,payload:n,connection:e,secrets:this.secrets,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=>{k(e,I.SERVER_EVENT,JSON.stringify(a))},onError:a=>{k(e,I.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 i;let{tenant:s,flowId:o,chatId:a}=((i=this.state.engineState)==null?void 0:i.flowData)??{};if(!s||!o||!a)return Promise.resolve();let c=Pe(n||this.resolveSessionUserId(),a);return Me(this.env,{id:e,tenant:s,flowId:o,userId:c,sessionId:a,label:r==null?void 0:r.slice(0,120)})}completeManualRun(e,r,n){return X(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=`${Xe}${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:Xe})).entries()].filter(([,a])=>n-a>Tt).map(([a])=>a);return o.length>0&&await this.ctx.storage.delete(o),!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=de(V(this.state.engineState)),s=pe(n,e.inputs||{},e.label),o=await D({agent:this,env:this.env,ctx:this.ctx,payload:{text:s,inputs:e.inputs||{}},secrets:this.secrets,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 X(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 X(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,I.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:n}),k(e,I.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,r){let n=fe(r);if(!n){k(e,I.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,I.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:n.name,set:s!==""}}))}async onClearHistory(e){await j(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,I.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await ve(this);let e=await _(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 Gr(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 xt,jwtVerify as kt}from"jose";function Ve(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 At(t){return(typeof t.email=="string"?t.email.trim():"")||null}async function O(t,e,r){let n=Ve(t.headers.get("cookie")),s=new URL(t.url),o=n.access_token||s.searchParams.get("access_token"),a=await Ut(e,o);if(a.ok){let c=a.payload,i=At(c);return i?{id:c.sub,email:i,name:c.name,first_name:c.given_name,last_name:c.family_name,tenant:c.tenant,roles:c["ora-roles"],db_name:c.db_name||null,user_id:c.user_id||null}:null}return null}async function Ut(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 Rt(t){return Ue(t.previous,Ae(t.userText),t.maxTokens)}async function St(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 Et(t){if(t.fullStream&&typeof t.fullStream[Symbol.asyncIterator]=="function")return St({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 je(t){var d;let e=V(t.engineState);if(!e)return{status:"skipped",reason:"start_node_missing"};if(!Ee(e))return{status:"skipped",reason:"memory_disabled"};let r=Te(e),n=Re(r),s=Ie(e),o=Y(t.previousContent||""),a=yt(t.messages),c=ht(t.engineState),i=u=>{let h=Rt({previous:o,userText:t.userText,maxTokens:n});return{status:"written",content:h,truncated:!1,modelId:s,fallback:!0,error:h?void 0:u}};try{let u=await Pe(s,t.sessionEnv,{maxOutputTokens:n});if(!u)throw new Error(`Memory model '${s}' not found in registry`);let h=xe(r,(d=u.reasoning)==null?void 0:d.kind),{system:S,user:p}=wt({previous:o,userText:t.userText,assistantText:a,answers:c,length:r,maxTokens:n,recentTurns:ft(t.messages)}),m=ve(u.reasoning),f=Ce(u.provider,{effort:m,exposeReasoning:!1,maxTokens:h}),g=ut({model:u.modelHandle,system:S,messages:[{role:"user",content:p}],...Oe({...u.effectiveParams??{},maxOutputTokens:h}),...f?{providerOptions:f}:{}}),y=await Et(g),E=gt(await g.usage),R=Y(y.text);if(ke(R)&&(R=""),!R)return{...i(y.error||"Memory model returned empty text"),usage:E};let T=Se(R,n);return{status:"written",content:T.content,truncated:T.truncated,usage:E,modelId:s}}catch(u){let h=u instanceof Error?u.message:"Memory update failed";return console.error("Memory update failed:",u),i(h)}}async function Ke(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}},c=o==null?void 0:o.stateVersion,i=typeof c=="number"&&c!==((s=e.flowData)==null?void 0:s.stateVersion);return{engineState:a,refreshed:i}}catch(o){return console.error(`[flowRefresh] fetch failed for flow ${r}:`,o),{engineState:e,refreshed:!1}}}function Xe(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 qe=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 D(t,e){var o,a;let r=t.id||t.name||"",[n,s]=String(r).split("::");if(!n||!s)return null;try{let i=(o=(await v(n,e)).metadata)==null?void 0:o.tenant,d=await P(n,e),u=(a=t.state)==null?void 0:a.user,h={flowData:{...d,tenant:i,flowId:n,chatId:s},executedNodes:[],context:u?{user:u}:{}};return t.setState({...t.state,engineState:h}),h}catch(c){return console.error("Failed to initialize engine state:",c),null}}async function $(t){var z,W,F,te,ne,re,se,oe,ae,ie,ce;let{agent:e,env:r,ctx:n,payload:s,connection:o}=t,a=Date.now(),c=[],i=t.runId?_e():void 0,d=async()=>await b(e),u=async l=>{await Ne(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"),x=await w(l,r);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[l]:x}}),x}catch(w){throw console.error(`Error fetching model ${l}:`,w),w}},S={id:It(),role:"user",type:"text",content:s.text,images:s.images,ts:Date.now()};await u(S);let p={onChangeState:l=>{e.setState({...e.state,engineState:l})},onServerEvent:async l=>{var w;await((w=t.onServerEvent)==null?void 0:w.call(t,l)),c.push(l)},onTelemetry:async l=>{var _,le,ue,de,pe,me;let w=t.user??e.state.user,x=typeof(w==null?void 0:w.org)=="string"&&w.org.trim()?w.org.trim():"default";await qe({...l,userId:t.resolveUserId(),tenant:((le=(_=e.state.engineState)==null?void 0:_.flowData)==null?void 0:le.tenant)||"",org:x,flowId:((de=(ue=e.state.engineState)==null?void 0:ue.flowData)==null?void 0:de.flowId)||"",sessionId:((me=(pe=e.state.engineState)==null?void 0:pe.flowData)==null?void 0:me.chatId)||""},r)},onError:l=>{var w;(w=t.onError)==null||w.call(t,l),e.setState({...e.state,error:l})},shouldStop:t.shouldStop},m=e.state.engineState?{...e.state.engineState}:null;if(m){let{engineState:l,refreshed:w}=await Ke(r,m);m=l,w&&e.setState({...e.state,engineState:m,modelsCache:{}})}else if(m=await D(e,r),!m){let l="Failed to initialize agent";return p.onError(l),{status:"failed",error:l}}let f=t.secrets;if(!f||Object.keys(f).length===0){let l=(z=m.flowData)==null?void 0:z.tenant;f=l?await q(r,l):{},(W=t.onSecretsLoaded)==null||W.call(t,f)}let g=t.user??e.state.user??void 0;g&&!((F=m.context)!=null&&F.user)&&(m.context={...m.context||{},user:g});let y={env:r,ctx:n,conn:o,getMessages:d,setMessages:u,getOraModel:h,secrets:f,userAuth:t.userAuth,user:g,composioSessions:t.composioSessions,publicOrigin:t.publicOrigin,skillRefCache:t.skillRefCache,runId:t.runId,outputCollector:i,agentMemory:typeof((te=e.state.memory)==null?void 0:te.content)=="string"?e.state.memory.content:"",shouldStop:t.shouldStop,workerStack:(ne=m.flowData)!=null&&ne.flowId?[m.flowData.flowId]:[],workerCalls:{count:0}},E=await Me(y,m,p)(s),R=e.state.engineState??m;if(E.status==="completed")try{let l=await je({sessionEnv:y,engineState:R,previousContent:typeof((re=e.state.memory)==null?void 0:re.content)=="string"?e.state.memory.content:"",userText:s.text||"",messages:await d()});if(l.status==="skipped")await p.onServerEvent({type:"agent:memory",content:{skipped:!0,reason:l.reason},timestamp:Date.now()});else if(!l.content.trim())await p.onServerEvent({type:"agent:memory",content:{updated:!1,empty:!0,error:l.error,fallback:l.fallback},timestamp:Date.now()});else{let w={promptTokens:((se=R.tokenUsage)==null?void 0:se.promptTokens)??0,completionTokens:((oe=R.tokenUsage)==null?void 0:oe.completionTokens)??0,totalTokens:((ae=R.tokenUsage)==null?void 0:ae.totalTokens)??0};l.usage&&(w.promptTokens+=l.usage.promptTokens,w.completionTokens+=l.usage.completionTokens,w.totalTokens+=l.usage.totalTokens),R={...R,tokenUsage:w},e.setState({...e.state,engineState:R,memory:{content:l.content,updatedTs:Date.now(),...l.error?{lastError:l.error}:{},...l.fallback?{fallback:!0}:{}}}),await p.onTelemetry({type:"memory_update",payload:{model:l.modelId,truncated:l.truncated,usage:l.usage,fallback:l.fallback,error:l.error}}),await p.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 p.onServerEvent({type:"agent:memory",content:{error:w},timestamp:Date.now()})}if(E.status==="completed"&&t.runId&&(i!=null&&i.hasOutputs())){let{flowId:l,chatId:w}=R.flowData??{};if(!l||!w)E={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await be(r,{flowId:l,sessionId:w,runId:t.runId,createdAt:new Date(a).toISOString(),data:i.snapshotData(),answerNodeIds:i.answerNodeIds()});let x={...R.results||{}};for(let _ of i.answerNodeIds())x[_]={...x[_]||{},persisted:!0,runId:t.runId};R={...R,results:x},e.setState({...e.state,engineState:R})}catch(x){let _=x instanceof Error?x.message:"Structured output persistence failed";p.onError(_),await p.onServerEvent({type:"error:answer-output",content:{runId:t.runId,error:_},timestamp:Date.now()}),E={status:"failed",error:_}}}let{tenant:T,flowId:O,chatId:U}=R.flowData??{},J=(ie=R.flowData)==null?void 0:ie.org;return T&&O&&U&&n.waitUntil(Xe(r,{id:`${O}::${U}`,tenant:T,org:J,flowId:O,sessionId:U,userId:t.resolveUserId(),title:(ce=s.text)==null?void 0:ce.slice(0,120),turnTs:a,events:c})),e.setState({...e.state,lastUpdated:new Date}),{status:E.status,error:E.error,engineState:R}}import{nanoid as Tt}from"nanoid";function xt(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"?M(r.email):null;return n?{...r,email:n}:null}catch{return null}}async function Ve(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 c=typeof o.userId=="string"?M(o.userId):null,i=xt(e),d=i==null?void 0:i.email;i?t.setState({...t.state,user:i,injectedUserId:d}):c&&!((s=t.state.user)!=null&&s.email)&&t.setState({...t.state,injectedUserId:c});let u=()=>d??c??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 D(t,r))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let S=`run-${Tt(12)}`;await t.registerManualRun(S,a,u()),await N(r,S).catch(g=>{console.warn(`[AgentHTTP] could not mark manual run ${S} as running`,g)});let p;try{p=await $({agent:t,env:r,ctx:n,payload:{text:a,inputs:h},skillRefCache:t.skillRefCache,user:i??void 0,resolveUserId:u,runId:S,shouldStop:()=>t.isRunStopRequested(S)}),n.waitUntil(t.completeManualRun(S,p.status==="completed"?"succeeded":p.status==="stopped"?"skipped":"failed",p.error))}finally{await t.clearRunStopRequest(S)}if(p.status==="failed")return new Response(JSON.stringify({error:p.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});if(p.status==="stopped")return new Response(JSON.stringify({error:p.error||"Stopped by user"}),{status:409,headers:{"content-type":"application/json"}});let f=(await b(t)).reverse().find(g=>g.role==="assistant");return new Response(JSON.stringify({answer:(f==null?void 0:f.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 Ge(t){try{return await j(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 Je="trigger:nonce:",Ut=900*1e3,ee="run:stop:",ze=class extends kt{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")?Ve(this,e,this.env,this.ctx):e.method==="DELETE"&&r.pathname.endsWith("/clear")?Ge(this):new Response("Ready to assist.")}async onConnect(e,r){var S,p,m,f,g;let[n,s]=e.server.split("::"),a=(S=(await v(n,this.env)).metadata)==null?void 0:S.tenant;this.secrets=await q(this.env,a),this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let c=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{c=JSON.parse(y)}catch(E){console.warn("Failed to parse X-User-Payload",E)}}let i=await P(n,this.env);this.setState({...this.state,user:c||null,sessionId:s,engineState:{flowData:{...i,tenant:a,flowId:n,chatId:s},executedNodes:[],context:c?{user:c}:{}}}),c||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let d=await b(this);k(e,I.SERVER_HISTORY,JSON.stringify({messages:d}));let h=(((p=i==null?void 0:i.state)==null?void 0:p.nodes)??(i==null?void 0:i.nodes)??[]).find(y=>y.type==="startNode");if(h){let y={allow_images:((m=h.data)==null?void 0:m.allow_images)??!1,allow_documents:((f=h.data)==null?void 0:f.allow_documents)??!1,greeting:(g=h.data)==null?void 0:g.greeting};k(e,I.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 c={[I.USER_MESSAGE]:i=>this.onUserMessage(e,i),[I.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[I.USER_AUTH]:i=>this.onUserAuth(e,i),[I.USER_IDENTITY]:i=>this.onUserIdentity(e,i)}[s];c&&await c(o)}async onUserMessage(e,r){let n=he(r),s=`run-${At(12)}`;await this.registerManualRun(s,n.text),await N(this.env,s).catch(o=>{console.warn(`[AgentDO] could not mark manual run ${s} as running`,o)});try{let o=await $({agent:this,env:this.env,ctx:this.ctx,payload:n,connection:e,secrets:this.secrets,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=>{k(e,I.SERVER_EVENT,JSON.stringify(a))},onError:a=>{k(e,I.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 i;let{tenant:s,flowId:o,chatId:a}=((i=this.state.engineState)==null?void 0:i.flowData)??{};if(!s||!o||!a)return Promise.resolve();let c=$e(n||this.resolveSessionUserId(),a);return Fe(this.env,{id:e,tenant:s,flowId:o,userId:c,sessionId:a,label:r==null?void 0:r.slice(0,120)})}completeManualRun(e,r,n){return X(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=`${Je}${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:Je})).entries()].filter(([,a])=>n-a>Ut).map(([a])=>a);return o.length>0&&await this.ctx.storage.delete(o),!0}async processTrigger(e){if(!(await N(this.env,e.runId)).claimed){console.warn(`[AgentDO] activation ${e.activationId} skipped \u2014 run ${e.runId} already claimed`);return}try{this.state.engineState||await D(this,this.env);let n=ge(V(this.state.engineState)),s=ye(n,e.inputs||{},e.label),o=await $({agent:this,env:this.env,ctx:this.ctx,payload:{text:s,inputs:e.inputs||{}},secrets:this.secrets,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 X(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 X(this.env,e.runId,{status:"failed",error:s}),n}finally{await this.clearRunStopRequest(e.runId)}}async onUserIdentity(e,r){let n=M(r);if(!n){k(e,I.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:n}),k(e,I.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,r){let n=we(r);if(!n){k(e,I.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,I.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:n.name,set:s!==""}}))}async onClearHistory(e){await j(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,I.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await De(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 Yr(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 _t,jwtVerify as bt}from"jose";function We(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 Ot(t){return(typeof t.email=="string"?t.email.trim():"")||null}async function C(t,e,r){let n=We(t.headers.get("cookie")),s=new URL(t.url),o=n.access_token||s.searchParams.get("access_token"),a=await vt(e,o);if(a.ok){let c=a.payload,i=Ot(c);return i?{id:c.sub,email:i,name:c.name,first_name:c.given_name,last_name:c.family_name,tenant:c.tenant,org:typeof c.org=="string"?c.org:null,roles:c["ora-roles"],db_name:c.db_name||null,user_id:c.user_id||null}:null}return null}async function vt(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
|
|
8
|
-
`)}async function Ze(t,e){let r=await crypto.subtle.importKey("raw",Je.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return bt(await crypto.subtle.sign("HMAC",r,Je.encode(e)))}function Ct(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 ss(t){let e=String(t.timestamp??Math.floor(Date.now()/1e3)),r=await Ze(t.secret,Qe({timestamp:e,nonce:t.nonce,tenant:t.tenant,destination:t.destination,body:t.body}));return{"content-type":"application/json",[Be]:t.tenant,[We]:e,[Ye]:t.nonce,[ze]:`v1=${r}`}}async function et(t){var d,u,y,f,p;if(!((d=t.secret)!=null&&d.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(u=t.headers.get(Be))==null?void 0:u.trim(),r=(y=t.headers.get(We))==null?void 0:y.trim(),n=(f=t.headers.get(Ye))==null?void 0:f.trim(),s=(p=t.headers.get(ze))==null?void 0:p.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),c=t.toleranceSeconds??300;if(Math.abs(a-o)>c)return{ok:!1,error:"stale timestamp"};let i=await Ze(t.secret.trim(),Qe({timestamp:r,nonce:n,tenant:e,destination:t.url,body:t.body}));return Ct(s.slice(3),i)?{ok:!0,tenant:e,nonce:n,timestamp:o}:{ok:!1,error:"signature mismatch"}}var A=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}});async function tt(t,e,r){var d;if(new URL(t.url).pathname!=="/api/triggers/dispatch")return;if(t.method!=="POST")return A({error:"Method not allowed"},405);let s=await t.text(),o=await et({secret:e.HX_API_KEY,body:s,url:t.url,headers:t.headers});if(!o.ok)return console.warn(`[triggers] rejected dispatch: ${o.error}`),A({error:"Invalid signature"},401);let a;try{a=JSON.parse(s)}catch{return A({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 A({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(a.tenant!==o.tenant)return A({error:"Tenant mismatch"},403);let c;try{c=await b(a.flowId,e)}catch{return A({error:"Flow not found"},404)}if(!((d=c==null?void 0:c.metadata)!=null&&d.tenant)||c.metadata.tenant!==a.tenant)return console.warn(`[triggers] flow ${a.flowId} does not belong to tenant ${a.tenant}`),A({error:"Tenant mismatch"},403);let i=await Ge(e,{...a,sessionId:a.sessionId||a.runAsUserId,nonce:o.nonce});return i.status==="error"?A({error:i.error},502):i.status==="deduped"?A({deduped:!0,runId:i.runId},200):A({accepted:!0,runId:i.runId,taskId:i.taskId},202)}var vt=/^[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}$/,Pt=new Set(["state","messages","memory"]);async function Mt(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 c=await G(e.AGENT,`${s}::${o}`);return Response.json(await c.requestRunStop(a))}catch(c){return console.error("[agents] failed to request run stop",c),Response.json({error:"Failed to stop run"},{status:502})}}async function Nt(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]||""),c=s[6];if(!o||!a||!c||!Pt.has(c))return new Response("Not found",{status:404});try{let d=await(await G(e.AGENT,`${o}::${a}`)).inspectPersistedSession(c);return Response.json(d)}catch(i){return console.error("[agents] failed to inspect persisted session",i),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function fs(t,e,r){var c,i,d,u;let n=new URL(t.url),s=await tt(t,e,r);if(s instanceof Response)return s;let o=await Mt(t,e);if(o instanceof Response)return o;let a=await Nt(t,e);if(a instanceof Response)return a;if(n.pathname.startsWith("/a/")){let y=n.pathname.split("/"),f=y[2],p=y[3];try{if(!f)return Response.redirect(new URL("/",n.origin).toString(),302);let g;try{g=await b(f,e)}catch{return new Response("Flow not found",{status:404})}if(!g.metadata||((c=g.metadata)==null?void 0:c.status)!=="active")return new Response("NO chat",{status:404});if(((i=g.metadata)==null?void 0:i.visibility)==="private"&&!await O(t,e,r)){let h=new URL("/login",n.origin);return h.searchParams.set("nextURL",`${n.pathname}${n.search}`),Response.redirect(h.toString(),302)}if(!p){let m=crypto.randomUUID(),h=new URL(`/a/${f}/${m}`,n.origin);return Response.redirect(h.toString(),302)}if(!vt.test(p))return new Response("Id del chat no v\xE1lido",{status:400})}catch(g){return console.error("Error accessing flow KV:",g),new Response("Flow error",{status:500})}}if(n.pathname.startsWith("/api/agent/flow")){let y=n.pathname.split("/"),f=y[4],p=y[5],g=`${f}::${p}`;try{let m=await O(t,e,r);if(!m){let x=new URL(t.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${x}) \u2014 Composio connections from tool editor will not apply`)}let h=new Headers(t.headers);h.delete("X-User-Payload"),m&&h.set("X-User-Payload",JSON.stringify(m));let S=new Request(t,{headers:h});return(await G(e.AGENT,g)).fetch(S)}catch(m){return console.error("Error accessing agent:",m),new Response("Agent error",{status:500})}}if(n.pathname.startsWith("/api/ora/connect")){let y=n.pathname.split("/"),f=y[4],p=y[5];if(!f||!p)return new Response("Missing flowId or sessionId",{status:400});let g=t.headers.get("Authorization")||n.searchParams.get("authorization");if(!g)return new Response("Missing Authorization header",{status:401});try{let m=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${f}`,S=await(await fetch(m,{method:"GET",headers:{Authorization:g}})).json();if(((d=S.payload)==null?void 0:d.flowId)!==f)return console.error("FlowId mismatch:",(u=S.payload)==null?void 0:u.flowId,"!==",f),new Response("Validation error",{status:403});let E=`${f}::${p}`,R=await O(t,e,r);if(!R){let F=new URL(t.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${F}) \u2014 Composio connections from tool editor will not apply`)}let x=new Headers(t.headers);x.delete("X-User-Payload"),R&&x.set("X-User-Payload",JSON.stringify(R));let v=new Request(t,{headers:x});return(await G(e.AGENT,E)).fetch(v)}catch(m){return console.error("Error in /api/ora/connect:",m),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 o=await O(t,e,r);if(!o)return new Response("Unauthorized",{status:401});let a=e.HX_CORE_URL,c=e.HX_API_KEY;if(!a||!c)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 u="/ora/instances";d&&(u+=`/${d}`);let y=a.endsWith("/")?a.slice(0,-1):a,f=new URL(`${y}${u}`);n.searchParams.forEach((m,h)=>{f.searchParams.set(h,m)}),s==="GET"&&!d&&f.searchParams.set("filter_user_id",o.email);let p=new Headers;p.set("Authorization",c),p.set("Content-Type","application/json"),p.set("X-User-Payload",JSON.stringify(o));let g={method:s,headers:p};if(["POST","PATCH","PUT"].includes(s))try{g.body=await t.text()}catch(m){console.error("Error reading request body:",m)}try{let m=await fetch(f.toString(),g),h=await m.text();return new Response(h,{status:m.status,headers:{"Content-Type":"application/json"}})}catch(m){return console.error("Error proxying to flow instance backend:",m),new Response("Internal Server Error",{status:500})}}async function Ss(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"),c=s.get("nextURL")||"/";if(!o||!a)return new Response("Missing username or password",{status:400});let i=new URLSearchParams;i.append("username",o),i.append("password",a),i.append("grant_type","password"),i.append("client_id",e.KC_CLIENT_ID),i.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:i});if(!d.ok)return new Response("Unauthorized",{status:401});let u=await d.json(),y=new Response(null,{status:302,headers:{Location:c}}),f=(p,g,m)=>{y.headers.append("Set-Cookie",`${p}=${g}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${m}`)};return u.access_token&&f("access_token",u.access_token,u.expires_in),u.refresh_token&&f("refresh_token",u.refresh_token,u.refresh_expires_in||3600*24*30),u.id_token&&f("id_token",u.id_token,u.expires_in),y}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 O(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{rt as ANONYMOUS_RUN_USER_PREFIX,qe as AgentDO,Wt as DEFAULT_MEMORY_LENGTH,Yt as DEFAULT_MEMORY_MODEL,qt as FLOW_INPUT_NAME_RE,Vn as FlowExecutionStoppedError,kn as GENERATION_PARAM_KEYS,Un as GENERATION_PRESETS,Gt as MAX_USER_IDENTITY_LENGTH,Jt as MEMORY_LENGTH_MD_LINES,zt as MEMORY_LENGTH_TOKENS,Gn as MODEL_REGISTRY_SNAPSHOT,L as NodeType,Zt as OUT_VAR_NAME_RE,An as PRESET_PARAM_KEYS,Fn as REASONING_EFFORT_LEVELS,qn as TOOL_REGISTRY_SNAPSHOT,Ye as TRIGGER_NONCE_HEADER,ze as TRIGGER_SIGNATURE_HEADER,rs as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,Be as TRIGGER_TENANT_HEADER,We as TRIGGER_TIMESTAMP_HEADER,mn as VariableResolutionError,On as applyPresetToOverrides,_e as buildReasoningProviderOptions,on as buildScope,ss as buildSignedTriggerHeaders,pe as buildTriggerMessageText,Lt as buildUrl,At as canonicalUserEmail,ye as capMemoryContent,M as claimRun,j as clearAllMessages,X as completeRun,Dt as convertTempMessure,Y as createRun,_n as deriveParamSupport,Ge as dispatchTrigger,Kt as embedText,ve as ensureAgentTables,nt as ensureMessagesTable,Qt as estimateTokens,yn as extractOutVarValues,Sn as extractTemplateReferences,Ie as extractUserKeypoints,an as findScopedSourceNode,_ as getAllMessages,rn as getAncestorNodeIds,en as getDefaultOutVars,nn as getEffectiveOutVars,de as getFlowInputDefs,Jn as getModelEntry,cn as getRefTail,sn as getUpstreamOutVars,fs as handleAgentsRoutes,Ss as handleAuthRoutes,Qr as handleCommonRoutes,hs as handleIntancesRoutes,Nt as handlePersistedSessionInspection,Mt as handleSessionRunControl,tt as handleTriggerRoutes,jt as hashText,N as initializeEngineState,ln as isBinaryOutVar,un as isJsonContentType,he as isStartMemoryEnabled,xn as jsonSchemaToZod,ue as logc,Ee as looksLikeTranscript,Se as memoryGenerationMaxTokens,H as memoryMdLineLimit,ge as memoryTokenLimit,Te as mergeKeypointMemory,I as messageTypes,Ot as normalizeDestination,vn as normalizeEffectiveParams,Vt as normalizeFlowInputs,Kn as normalizeModelEntry,Ln as normalizeReasoning,Mn as openAiReasoningParamSupport,Pn as openAiStandardParamSupport,Ve as parseCookies,Bt as parseMemoryLength,dn as parsePayloadText,Rn as parseTemplateExpression,fe as parseUserAuth,me as parseUserMessage,Cn as pickNodeOverrides,pn as readFetchPayload,Hn as reasoningEffortLevels,jn as reasoningExposable,Me as recordRun,Xn as registerProvider,Tn as resolveAnswerMappings,be as resolveModelById,wn as resolveOutVarRef,gn as resolveOutVarValue,bn as resolvePreset,Ue as resolveReasoningEffort,hn as resolveReference,Pe as resolveRunUserId,In as resolveTemplate,En as rewriteTemplateNodeRefs,D as runAgentTurn,Ft as safeParseJSON,z as sanitizeMemoryDocument,P as sanitizeUserIdentity,He as sendEvent,k as serverSend,Ce as setMessage,Ze as signTriggerMaterial,Oe as startEngine,Re as startMemoryLength,we as startMemoryModel,$n as stripUnsupportedFromNodeData,$t as tempTool,Ct as timingSafeEqualHex,Ae as toStreamTextSettings,Qe as triggerSignatureMaterial,Ht as twitter,Gr as validateFlowStart,tn as validateOutVars,Xt as vectorize,Ut as verifyToken,et as verifyTriggerRequest,O as verifyUser,fn as walkPath,Dn as workersAiParamSupport,Nn as xaiParamSupport};
|
|
7
|
+
-----END PUBLIC KEY-----`,n=await _t(r,"RS256");try{let{payload:s,protectedHeader:o}=await bt(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 ns(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 G}from"agents";import{getAgentByName as Ct}from"agents";async function Ye(t,e){let r=e.sessionId||e.runAsUserId,n=e.inputs||{},s=e.runId;if(!s){let i=await Q(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(!i)return{status:"error",error:"Failed to register run"};if(!i.created&&i.run.status!=="queued")return{status:"deduped",runId:i.run.id};s=i.run.id}let o={...e,sessionId:r,runId:s,inputs:n},c=await(await Ct(t.AGENT,`${e.flowId}::${r}`)).enqueueTrigger(o);return c.duplicate?{status:"deduped",runId:s}:c.queued?{status:"queued",runId:s,activation:o,taskId:c.taskId}:{status:"error",error:"Failed to queue trigger"}}var Qe="x-ora-signature",Ze="x-ora-timestamp",et="x-ora-nonce",tt="x-ora-tenant",is=300,Be=new TextEncoder;function Pt(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function Mt(t){try{let e=new URL(t);return`${e.origin}${e.pathname.replace(/\/$/,"")}`}catch{return t.replace(/\/$/,"")}}function nt(t){return["v1",t.timestamp,t.nonce,t.tenant,Mt(t.destination),t.body].join(`
|
|
8
|
+
`)}async function rt(t,e){let r=await crypto.subtle.importKey("raw",Be.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return Pt(await crypto.subtle.sign("HMAC",r,Be.encode(e)))}function Nt(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 cs(t){let e=String(t.timestamp??Math.floor(Date.now()/1e3)),r=await rt(t.secret,nt({timestamp:e,nonce:t.nonce,tenant:t.tenant,destination:t.destination,body:t.body}));return{"content-type":"application/json",[tt]:t.tenant,[Ze]:e,[et]:t.nonce,[Qe]:`v1=${r}`}}async function st(t){var d,u,h,S,p;if(!((d=t.secret)!=null&&d.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(u=t.headers.get(tt))==null?void 0:u.trim(),r=(h=t.headers.get(Ze))==null?void 0:h.trim(),n=(S=t.headers.get(et))==null?void 0:S.trim(),s=(p=t.headers.get(Qe))==null?void 0:p.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),c=t.toleranceSeconds??300;if(Math.abs(a-o)>c)return{ok:!1,error:"stale timestamp"};let i=await rt(t.secret.trim(),nt({timestamp:r,nonce:n,tenant:e,destination:t.url,body:t.body}));return Nt(s.slice(3),i)?{ok:!0,tenant:e,nonce:n,timestamp:o}:{ok:!1,error:"signature mismatch"}}var A=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}});async function ot(t,e,r){var d;if(new URL(t.url).pathname!=="/api/triggers/dispatch")return;if(t.method!=="POST")return A({error:"Method not allowed"},405);let s=await t.text(),o=await st({secret:e.HX_API_KEY,body:s,url:t.url,headers:t.headers});if(!o.ok)return console.warn(`[triggers] rejected dispatch: ${o.error}`),A({error:"Invalid signature"},401);let a;try{a=JSON.parse(s)}catch{return A({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 A({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(a.tenant!==o.tenant)return A({error:"Tenant mismatch"},403);let c;try{c=await v(a.flowId,e)}catch{return A({error:"Flow not found"},404)}if(!((d=c==null?void 0:c.metadata)!=null&&d.tenant)||c.metadata.tenant!==a.tenant)return console.warn(`[triggers] flow ${a.flowId} does not belong to tenant ${a.tenant}`),A({error:"Tenant mismatch"},403);let i=await Ye(e,{...a,sessionId:a.sessionId||a.runAsUserId,nonce:o.nonce});return i.status==="error"?A({error:i.error},502):i.status==="deduped"?A({deduped:!0,runId:i.runId},200):A({accepted:!0,runId:i.runId,taskId:i.taskId},202)}var Dt=/^[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}$/,$t=new Set(["state","messages","memory"]);async function Ft(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 c=await G(e.AGENT,`${s}::${o}`);return Response.json(await c.requestRunStop(a))}catch(c){return console.error("[agents] failed to request run stop",c),Response.json({error:"Failed to stop run"},{status:502})}}async function Lt(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]||""),c=s[6];if(!o||!a||!c||!$t.has(c))return new Response("Not found",{status:404});try{let d=await(await G(e.AGENT,`${o}::${a}`)).inspectPersistedSession(c);return Response.json(d)}catch(i){return console.error("[agents] failed to inspect persisted session",i),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function ws(t,e,r){var c,i,d,u,h,S;let n=new URL(t.url),s=await ot(t,e,r);if(s instanceof Response)return s;let o=await Ft(t,e);if(o instanceof Response)return o;let a=await Lt(t,e);if(a instanceof Response)return a;if(n.pathname.startsWith("/a/")){let p=n.pathname.split("/"),m=p[2],f=p[3];try{if(!m)return Response.redirect(new URL("/",n.origin).toString(),302);let g;try{g=await v(m,e)}catch{return new Response("Flow not found",{status:404})}if(!g.metadata||((c=g.metadata)==null?void 0:c.status)!=="active"&&((i=g.metadata)==null?void 0:i.status)!=="activo")return new Response("NO chat",{status:404});if(((d=g.metadata)==null?void 0:d.visibility)!=="public"){let y=await C(t,e,r);if(!y){let T=new URL("/login",n.origin);return T.searchParams.set("nextURL",`${n.pathname}${n.search}`),Response.redirect(T.toString(),302)}let E=((u=g.metadata)==null?void 0:u.org)||"default",R=typeof y=="object"&&(y==null?void 0:y.org)||"default";if(E!==R)return new Response("Forbidden",{status:403})}if(!f){let y=crypto.randomUUID(),E=new URL(`/a/${m}/${y}`,n.origin);return Response.redirect(E.toString(),302)}if(!Dt.test(f))return new Response("Id del chat no v\xE1lido",{status:400})}catch(g){return console.error("Error accessing flow KV:",g),new Response("Flow error",{status:500})}}if(n.pathname.startsWith("/api/agent/flow")){let p=n.pathname.split("/"),m=p[4],f=p[5],g=`${m}::${f}`;try{let y=await C(t,e,r);if(!y){let U=new URL(t.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${U}) \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 R=new Request(t,{headers:E});return(await G(e.AGENT,g)).fetch(R)}catch(y){return console.error("Error accessing agent:",y),new Response("Agent error",{status:500})}}if(n.pathname.startsWith("/api/ora/connect")){let p=n.pathname.split("/"),m=p[4],f=p[5];if(!m||!f)return new Response("Missing flowId or sessionId",{status:400});let g=t.headers.get("Authorization")||n.searchParams.get("authorization");if(!g)return new Response("Missing Authorization header",{status:401});try{let y=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${m}`,R=await(await fetch(y,{method:"GET",headers:{Authorization:g}})).json();if(((h=R.payload)==null?void 0:h.flowId)!==m)return console.error("FlowId mismatch:",(S=R.payload)==null?void 0:S.flowId,"!==",m),new Response("Validation error",{status:403});let T=`${m}::${f}`,O=await C(t,e,r);if(!O){let F=new URL(t.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${F}) \u2014 Composio connections from tool editor will not apply`)}let U=new Headers(t.headers);U.delete("X-User-Payload"),O&&U.set("X-User-Payload",JSON.stringify(O));let J=new Request(t,{headers:U});return(await G(e.AGENT,T)).fetch(J)}catch(y){return console.error("Error in /api/ora/connect:",y),new Response("Internal error",{status:500})}}}async function Es(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,c=e.HX_API_KEY;if(!a||!c)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 u="/ora/instances";d&&(u+=`/${d}`);let h=a.endsWith("/")?a.slice(0,-1):a,S=new URL(`${h}${u}`);n.searchParams.forEach((f,g)=>{S.searchParams.set(g,f)}),s==="GET"&&!d&&S.searchParams.set("filter_user_id",o.email);let p=new Headers;p.set("Authorization",c),p.set("Content-Type","application/json"),p.set("X-User-Payload",JSON.stringify(o));let m={method:s,headers:p};if(["POST","PATCH","PUT"].includes(s))try{m.body=await t.text()}catch(f){console.error("Error reading request body:",f)}try{let f=await fetch(S.toString(),m),g=await f.text();return new Response(g,{status:f.status,headers:{"Content-Type":"application/json"}})}catch(f){return console.error("Error proxying to flow instance backend:",f),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(),o=s.get("username"),a=s.get("password"),c=s.get("nextURL")||"/";if(!o||!a)return new Response("Missing username or password",{status:400});let i=new URLSearchParams;i.append("username",o),i.append("password",a),i.append("grant_type","password"),i.append("client_id",e.KC_CLIENT_ID),i.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:i});if(!d.ok)return new Response("Unauthorized",{status:401});let u=await d.json(),h=new Response(null,{status:302,headers:{Location:c}}),p=n.protocol==="https:"?"; Secure":"",m=(f,g,y)=>{h.headers.append("Set-Cookie",`${f}=${g}; Path=/; HttpOnly${p}; SameSite=Lax; Max-Age=${y}`)};return u.access_token&&m("access_token",u.access_token,u.expires_in),u.refresh_token&&m("refresh_token",u.refresh_token,u.refresh_expires_in||3600*24*30),u.id_token&&m("id_token",u.id_token,u.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{it as ANONYMOUS_RUN_USER_PREFIX,ze as AgentDO,Zt as DEFAULT_MEMORY_LENGTH,en as DEFAULT_MEMORY_MODEL,zt as FLOW_INPUT_NAME_RE,Wn as FlowExecutionStoppedError,bn as GENERATION_PARAM_KEYS,vn as GENERATION_PRESETS,Yt as MAX_USER_IDENTITY_LENGTH,Bt as MEMORY_LENGTH_MD_LINES,Qt as MEMORY_LENGTH_TOKENS,Yn as MODEL_REGISTRY_SNAPSHOT,L as NodeType,rn as OUT_VAR_NAME_RE,On as PRESET_PARAM_KEYS,Kn as REASONING_EFFORT_LEVELS,zn as TOOL_REGISTRY_SNAPSHOT,et as TRIGGER_NONCE_HEADER,Qe as TRIGGER_SIGNATURE_HEADER,is as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,tt as TRIGGER_TENANT_HEADER,Ze as TRIGGER_TIMESTAMP_HEADER,hn as VariableResolutionError,Mn as applyPresetToOverrides,Ce as buildReasoningProviderOptions,un as buildScope,cs as buildSignedTriggerHeaders,ye as buildTriggerMessageText,Xt as buildUrl,Ot as canonicalUserEmail,Se as capMemoryContent,N as claimRun,j as clearAllMessages,X as completeRun,Ht as convertTempMessure,Q as createRun,Cn as deriveParamSupport,Ye as dispatchTrigger,Gt as embedText,De as ensureAgentTables,at as ensureMessagesTable,nn as estimateTokens,Sn as extractOutVarValues,xn as extractTemplateReferences,Ae as extractUserKeypoints,dn as findScopedSourceNode,b as getAllMessages,cn as getAncestorNodeIds,sn as getDefaultOutVars,an as getEffectiveOutVars,ge as getFlowInputDefs,Bn as getModelEntry,pn as getRefTail,ln as getUpstreamOutVars,ws as handleAgentsRoutes,xs as handleAuthRoutes,ns as handleCommonRoutes,Es as handleIntancesRoutes,Lt as handlePersistedSessionInspection,Ft as handleSessionRunControl,ot as handleTriggerRoutes,Vt as hashText,D as initializeEngineState,mn as isBinaryOutVar,fn as isJsonContentType,Ee as isStartMemoryEnabled,_n as jsonSchemaToZod,fe as logc,ke as looksLikeTranscript,xe as memoryGenerationMaxTokens,H as memoryMdLineLimit,Re as memoryTokenLimit,Ue as mergeKeypointMemory,I as messageTypes,Mt as normalizeDestination,Dn as normalizeEffectiveParams,Wt as normalizeFlowInputs,Gn as normalizeModelEntry,Xn as normalizeReasoning,Fn as openAiReasoningParamSupport,$n as openAiStandardParamSupport,We as parseCookies,tn as parseMemoryLength,gn as parsePayloadText,Tn as parseTemplateExpression,we as parseUserAuth,he as parseUserMessage,Nn as pickNodeOverrides,yn as readFetchPayload,qn as reasoningEffortLevels,Vn as reasoningExposable,Fe as recordRun,Jn as registerProvider,Un as resolveAnswerMappings,Pe as resolveModelById,In as resolveOutVarRef,Rn as resolveOutVarValue,Pn as resolvePreset,ve as resolveReasoningEffort,En as resolveReference,$e as resolveRunUserId,An as resolveTemplate,kn as rewriteTemplateNodeRefs,$ as runAgentTurn,Kt as safeParseJSON,Y as sanitizeMemoryDocument,M as sanitizeUserIdentity,qe as sendEvent,k as serverSend,Ne as setMessage,rt as signTriggerMaterial,Me as startEngine,Te as startMemoryLength,Ie as startMemoryModel,jn as stripUnsupportedFromNodeData,jt as tempTool,Nt as timingSafeEqualHex,Oe as toStreamTextSettings,nt as triggerSignatureMaterial,qt as twitter,Yr as validateFlowStart,on as validateOutVars,Jt as vectorize,vt as verifyToken,st as verifyTriggerRequest,C as verifyUser,wn as walkPath,Hn as workersAiParamSupport,Ln as xaiParamSupport};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c}from"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";export{b as fetchOraModel,c as fetchSkillRef,a as fetchToolDefs};
|
|
@@ -4,10 +4,8 @@ import { type Message } from '../../common/types/agent-types';
|
|
|
4
4
|
import type { TriggerActivation } from '../../common/types/trigger-types';
|
|
5
5
|
import type { FlowEngineState } from '../logic/FlowEngine';
|
|
6
6
|
import type { ComposioSessionMeta } from '../utils/composio';
|
|
7
|
-
import type { ToolCatalogEntry } from '../utils/oraApi';
|
|
8
7
|
import type { RunOutputCollector } from '../utils/oraOutputs';
|
|
9
8
|
import { type SecretsMap } from '../utils/secrets';
|
|
10
|
-
export type { ToolCatalogEntry };
|
|
11
9
|
export interface SessionEnv {
|
|
12
10
|
env?: Env;
|
|
13
11
|
ctx?: DurableObjectState;
|
|
@@ -21,8 +19,6 @@ export interface SessionEnv {
|
|
|
21
19
|
userAuth?: SecretsMap;
|
|
22
20
|
/** Custom tool definitions for the tenant, lazy-loaded on first custom-tool reference and cached for the session. Keyed by row.id. */
|
|
23
21
|
toolDefs?: Record<string, any>;
|
|
24
|
-
/** Curated tool catalog entries for the tenant, lazy-loaded and cached for the session. Keyed by entry id. */
|
|
25
|
-
toolCatalog?: Record<string, ToolCatalogEntry>;
|
|
26
22
|
/** In-memory cache for skill references fetched during this session. Keyed by toolId:refName. */
|
|
27
23
|
skillRefCache?: Map<string, string>;
|
|
28
24
|
/** Composio session metadata keyed by composio tool row id — reused within the agent chat session. */
|
|
@@ -4,12 +4,10 @@ export type ComposioDirectToolResult = {
|
|
|
4
4
|
data?: unknown;
|
|
5
5
|
error?: string | null;
|
|
6
6
|
};
|
|
7
|
-
export declare function
|
|
7
|
+
export declare function executeComposioDirectTool(sessionEnv: SessionEnv, opts: {
|
|
8
8
|
toolSlug: string;
|
|
9
9
|
connectionScope: string;
|
|
10
10
|
/** Pinned version of the selected tool (preferred — from node.data.toolVersion). */
|
|
11
11
|
toolVersion?: string | null;
|
|
12
|
-
/** Catalog-level hint from toolkit snapshot (may be first-tool only). */
|
|
13
|
-
toolkitVersion?: string | null;
|
|
14
12
|
arguments: Record<string, unknown>;
|
|
15
13
|
}): Promise<ComposioDirectToolResult>;
|
|
@@ -1,12 +1,4 @@
|
|
|
1
1
|
export declare function fetchToolDefs(env: Env): Promise<any[]>;
|
|
2
|
-
export type ToolCatalogEntry = {
|
|
3
|
-
id: string;
|
|
4
|
-
toolkitSlug: string;
|
|
5
|
-
toolkitVersion: string | null;
|
|
6
|
-
connectionScope: string;
|
|
7
|
-
label: string;
|
|
8
|
-
};
|
|
9
|
-
export declare function fetchToolCatalog(env: Env): Promise<ToolCatalogEntry[]>;
|
|
10
2
|
export declare function fetchOraModel(modelId: string, env: Env): Promise<any>;
|
|
11
3
|
export declare function fetchSkillRef(env: Env, toolId: string, refName: string): Promise<{
|
|
12
4
|
name: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b}from"./chunk-
|
|
1
|
+
import{a,b}from"./chunk-3K4IMMLP.js";import"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";export{b as readSkillRef,a as skillTool};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{h as a,i as b}from"./chunk-CRVHPQVH.js";import"./chunk-ELMOSEQ7.js";import"./chunk-YFOFZWIB.js";import"./chunk-OF6G42DM.js";import"./chunk-MOYYZBTC.js";import"./chunk-CDGUEX3J.js";import"./chunk-4XJVXKXR.js";import"./chunk-J4LJZZ67.js";import"./chunk-V6JSMX5A.js";import"./chunk-YLDLDEUP.js";import"./chunk-U56YWPSI.js";import"./chunk-A2IRPAD4.js";import"./chunk-3TXHFKDN.js";export{b as FlowExecutionStoppedError,a as startEngine};
|
package/dist/chunk-A2IRPAD4.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
async function s(o){let t=await fetch(`${o.HX_ORA_URL}/internal/tools`,{method:"GET",headers:{Authorization:`${o.HX_API_KEY}`},cache:"no-store"});if(!t.ok)throw new Error("Failed to fetch tool defs");return(await t.json()).tools??[]}async function a(o){let t=await fetch(`${o.HX_ORA_URL}/internal/tool-catalog`,{method:"GET",headers:{Authorization:`${o.HX_API_KEY}`},cache:"no-store"});if(!t.ok)throw new Error("Failed to fetch tool catalog");return(await t.json()).entries??[]}async function i(o,t){let n=await fetch(`${t.HX_ORA_URL}/internal/models/${o}`,{method:"GET",headers:{Authorization:`${t.HX_API_KEY}`},cache:"no-store"});if(!n.ok)throw new Error(`Failed to fetch model ${o} from registry`);return(await n.json()).model}async function c(o,t,n){let e=await fetch(`${o.HX_ORA_URL}/internal/tools/${t}/refs/${encodeURIComponent(n)}`,{method:"GET",headers:{Authorization:`${o.HX_API_KEY}`},cache:"no-store"});if(!e.ok)throw e.status===404?new Error(`Reference "${n}" not found`):new Error(`Failed to fetch skill reference "${n}"`);let r=await e.json();if(!r.ref)throw new Error(`Reference "${n}" not found in response`);return r.ref}export{s as a,a as b,i as c,c as d};
|
package/dist/chunk-CRVHPQVH.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import{a as bt}from"./chunk-ELMOSEQ7.js";import{a as G,b as Z,c as Ct,d as tt}from"./chunk-YFOFZWIB.js";import{a as zt}from"./chunk-OF6G42DM.js";import{a as Kt,b as Bt}from"./chunk-CDGUEX3J.js";import{C as Ut,D as Vt,E as Lt,L as Ht,N as Wt,O as Jt,P as Xt,Q as qt,a as K,b as $t,k as Ft,n as It,o as Ot,q as _t,z as jt}from"./chunk-4XJVXKXR.js";import{B as Mt,c as E,d as At,h as kt,k as Y,r as Dt,s as V,v as S,w as J}from"./chunk-J4LJZZ67.js";import{a as Rt,b as xt,d as Tt}from"./chunk-YLDLDEUP.js";import{a as v,b as Pt}from"./chunk-A2IRPAD4.js";import{a as Q}from"./chunk-3TXHFKDN.js";async function Gt(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 l=await s.json();return{name:t.name,text:l.text||""}}catch(s){return console.error(`extractDocuments: ${t.name} threw`,s),{name:t.name,text:""}}})):[]}function ao(e,o,i){var t,s,l,p;return Y(((s=(t=i.flowData)==null?void 0:t.state)==null?void 0:s.nodes)??[],((p=(l=i.flowData)==null?void 0:l.state)==null?void 0:p.edges)??[],o.id).some(d=>d.ref===e&&(d.type==="image"||d.type==="file"))}function lo(e,o){var p,d,u,a,c,m,n;let i=Array.isArray((p=e.data)==null?void 0:p.outputMapping)?e.data.outputMapping:[];if(i.length===0)return null;let t=((u=(d=o.flowData)==null?void 0:d.state)==null?void 0:u.nodes)||[],s={},l=new Set;for(let y of i){let r=(a=y.key)==null?void 0:a.trim(),h=(c=y.from)==null?void 0:c.trim();if(!r||!h)throw new Error(`Answer node ${e.id} has an incomplete variable mapping`);if(l.has(r))throw new Error(`Answer node ${e.id} has duplicate output key "${r}"`);if(ao(h,e,o))throw new Error(`Answer node ${e.id} cannot persist binary source "${h}"`);let f=J(h,{context:o.context||{},results:o.results||{},nodes:t,edges:((n=(m=o.flowData)==null?void 0:m.state)==null?void 0:n.edges)??[],currentNodeId:e.id}),g=f.value;if(f.missing||g===void 0||g===null){if(y.default===void 0)throw new V(f.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Answer node ${e.id} could not resolve output "${h}"`);g=y.default}s[r]=g,l.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 st(e,o,i,t,s,l,p){var u,a,c;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let d;try{d=lo(o,i)}catch(m){throw t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(m)}}),m}d&&e.outputCollector&&e.outputCollector.add(o.id,d);try{let m=await((u=e.getMessages)==null?void 0:u.call(e))??[],n=((a=m[m.length-1])==null?void 0:a.type)==="text"?m[m.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:n}})}catch(m){console.error("answerNodeRunner: failed to emit answer telemetry:",m),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:!!d&&!!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 z(e,o,i,t,s){var d,u,a,c,m;let l=(s==null?void 0:s.callerTag)??"llmNodeRunner",p=(s==null?void 0:s.serializeNonStrings)??!1;return Mt(e,o,{context:i.context??{},results:i.results??{},nodes:((u=(d=i.flowData)==null?void 0:d.state)==null?void 0:u.nodes)??[],edges:((c=(a=i.flowData)==null?void 0:a.state)==null?void 0:c.edges)??[],currentNodeId:o.id,secrets:(m=s==null?void 0:s.sessionEnv)==null?void 0:m.secrets},{callerTag:l,serializeNonStrings:p,onError:n=>{t==null||t({type:`error:${l}`,content:n})}})}var rt="[redacted]",Zt=8*1024;function co(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<=Zt){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,Zt);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function uo(e,o){return S(e,o)}var nt=(e,o,i,t,s)=>z(e,o,i,s,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function at(e,o,i,t,s,l,p){var a,c,m,n,y,r;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let d=null,u=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(i.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(i.results||{}));let h=((a=o.data)==null?void 0:a.url)||"",f=nt(h,o,i,e,t);if(console.log("[apiNodeRunner] resolved url:",G(h)?Z(f):f),!f){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,d);return}let g=(((c=o.data)==null?void 0:c.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",g);let w=((m=o.data)==null?void 0:m.headers)||{},x={},N={};for(let C in w)if(Object.prototype.hasOwnProperty.call(w,C)){let j=String(w[C]??"");N[C]=G(j),x[C]=nt(j,o,i,e,t)}let R,_=!1;if(g!=="GET"&&g!=="HEAD"&&((n=o.data)==null?void 0:n.body)!==void 0){let C=typeof o.data.body=="string"?o.data.body:JSON.stringify(o.data.body);_=G(C),R=nt(C,o,i,e,t),!x["Content-Type"]&&!x["content-type"]&&(x["Content-Type"]="application/json")}let F={};for(let C in x)F[C]=N[C]?rt:x[C];console.log("[apiNodeRunner] headers:",JSON.stringify(F)),console.log("[apiNodeRunner] body:",_?rt:R),t==null||t({type:"info:apiNodeRunner:request",content:{nodeId:o.id,method:g,url:G(h)?Z(f):f,headers:F,body:_?rt:R}});let P=Number((y=o.data)==null?void 0:y.timeoutMs),U=new AbortController,O=Number.isFinite(P)&&P>0?setTimeout(()=>U.abort(),P):null,T;try{console.log("[apiNodeRunner] fetching..."),T=await fetch(f,{method:g,headers:x,body:R,signal:U.signal}),console.log("[apiNodeRunner] fetch returned status:",T.status)}finally{O&&clearTimeout(O)}let b=T.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",b);let M=await Dt(T);console.log("[apiNodeRunner] payload preview:",typeof M=="string"?M.slice(0,200):JSON.stringify(M).slice(0,200)),d={ok:T.ok,status:T.status,data:M};let D=Date.now()-u;p==null||p({type:"api_call",payload:{nodeId:o.id,url:f,method:g,status:T.status,latencyMs:D}});let{value:$,truncated:L}=co(M);t==null||t({type:"info:apiNodeRunner:response",content:{nodeId:o.id,ok:T.ok,status:T.status,latencyMs:D,data:$,truncated:L,outVars:uo(o,d)}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}catch(h){console.error("Error processing ApiNode:",h),t==null||t({type:"error:apiNodeRunner",content:`API node execution failed: ${h}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(h)}})}finally{console.log("[apiNodeRunner] final result:",(r=JSON.stringify(d))==null?void 0:r.slice(0,300)),s==null||s(o.id,d)}}var po="[redacted]",Et=8*1024;function dt(e,o){if(typeof e=="string")return G(e)?typeof o=="string"&&/^https?:\/\//i.test(o)?Z(o):po:o;if(e&&typeof e=="object"&&!Array.isArray(e)){let i={},t=o&&typeof o=="object"&&!Array.isArray(o)?o:{};for(let[s,l]of Object.entries(e))i[s]=dt(l,t[s]);return i}if(Array.isArray(e)){let i=Array.isArray(o)?o:[];return e.map((t,s)=>dt(t,i[s]))}return o}function fo(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<=Et){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,Et);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function mo(e,o){return S(e,o)}var yo=(e,o,i,t,s)=>z(e,o,i,s,{callerTag:"toolNodeRunner",serializeNonStrings:!0,sessionEnv:t});function ot(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}function go(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 wo(e,o){var p,d;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[u,a]of Object.entries(t))i[u]=go(a);return{types:i,properties:t}}let l=(d=e.data)==null?void 0:d.argTypes;if(l&&typeof l=="object"&&!Array.isArray(l))for(let[u,a]of Object.entries(l))typeof a=="string"&&(i[u]=a);return{types:i,properties:t}}function ho(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(l=>String(l)===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 No(e){return e===void 0||typeof e=="string"&&e.trim()===""}function lt(e,o,i,t,s,l,p){if(typeof e=="string"){let d=e.includes("{{")?yo(e,o,i,t,s):e;return ho(d,l,p)}if(e&&typeof e=="object"&&!Array.isArray(e)){let d={};for(let[u,a]of Object.entries(e))d[u]=lt(a,o,i,t,s);return d}return Array.isArray(e)?e.map(d=>lt(d,o,i,t,s)):e}function Ro(e,o,i,t,s,l){let p={};for(let[d,u]of Object.entries(e)){let a=lt(u,o,i,t,s,l.types[d],l.properties[d]);No(a)||(p[d]=a)}return p}async function xo(e){if(e.toolCatalog)return e.toolCatalog;if(!e.env)return e.toolCatalog={},e.toolCatalog;let o=await Pt(e.env),i={};for(let t of o)t!=null&&t.id&&(i[t.id]=t);return e.toolCatalog=i,i}async function To(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}async function ct(e,o,i,t,s,l,p){var c,m,n,y,r,h,f,g,w,x,N,R;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let d={ok:!1,data:null,error:null},u=Date.now(),a=((c=o.data)==null?void 0:c.source)==="http"?"http":"catalog";try{let _=(m=o.data)!=null&&m.args&&typeof o.data.args=="object"&&!Array.isArray(o.data.args)?o.data.args:{},F,P;if(a==="http"){let D=typeof((n=o.data)==null?void 0:n.toolId)=="string"?o.data.toolId.trim():"";if(!D)throw new Error("HTTP tool nodes require toolId");if(P=(await To(e))[D],!P)throw new Error(`Tool ${D} not found`);F=P.inputSchema}let U=wo(o,F),O=Ro(_,o,i,e,t,U);if(t==null||t({type:"info:toolNodeRunner:request",content:{nodeId:o.id,source:a,catalogId:(y=o.data)==null?void 0:y.catalogId,toolSlug:(r=o.data)==null?void 0:r.toolSlug,toolId:(h=o.data)==null?void 0:h.toolId,args:dt(_,O)}}),a==="catalog"){let D=typeof((f=o.data)==null?void 0:f.catalogId)=="string"?o.data.catalogId.trim():"",$=typeof((g=o.data)==null?void 0:g.toolSlug)=="string"?o.data.toolSlug.trim():"";if(!D||!$)throw new Error("Catalog tool nodes require catalogId and toolSlug");let C=(await xo(e))[D];if(!C)throw new Error(`Tool catalog entry ${D} not found or disabled`);let j=typeof((w=o.data)==null?void 0:w.toolVersion)=="string"?o.data.toolVersion.trim():"",H=await bt(e,{toolSlug:$,connectionScope:C.connectionScope,toolVersion:j||null,toolkitVersion:C.toolkitVersion,arguments:O});d={ok:H.ok,data:H.ok?H.data:null,error:H.ok?null:H.error??"Tool execution failed"}}else{let D=tt(P,e,i,t);if(!D.execute)throw new Error(`Tool ${(x=o.data)==null?void 0:x.toolId} is missing an execute handler`);let $=await D.execute(O,{}),L=$&&typeof $=="object"&&"error"in $&&$.error?String($.error):null;d={ok:!L,data:$,error:L}}let T=Date.now()-u;p==null||p({type:"tool_call",payload:{nodeId:o.id,url:a==="catalog"?`composio:${((N=o.data)==null?void 0:N.toolSlug)??""}`:`tool:${((R=o.data)==null?void 0:R.toolId)??""}`,method:"EXECUTE",status:d.ok?200:502,latencyMs:T}});let{value:b,truncated:M}=fo(d.data);t==null||t({type:"info:toolNodeRunner:response",content:{nodeId:o.id,ok:d.ok,latencyMs:T,data:b,truncated:M,error:d.error,outVars:mo(o,d)}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:d.ok?"success":"error",error:d.error??void 0}})}catch(_){let F=_ instanceof Error?_.message:String(_);d={ok:!1,data:null,error:F},t==null||t({type:"error:toolNodeRunner",content:`Tool node execution failed: ${F}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:F}})}finally{s==null||s(o.id,d)}}function St(){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 Ao(e){return!!(e!=null&&e.HX_ORA_URL)&&!!(e!=null&&e.HX_API_KEY)}async function ge(e,o){if(!Ao(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 vt=3,to=10,$o=new Set(["agent:start","agent:complete","agent:telemetry"]);function Fo(e){let o=e.executedNodes||[];return o.length===0?"(none)":o.map(i=>i.label?`${i.id} (${i.label})`:i.id).join(" \u2192 ")}function Io(e){let o=e.executedNodes||[];return o[o.length-1]}function q(e,o,i){throw e==null||e({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:i.message}}),i}function Oo(e,o){var l,p,d,u,a,c,m;let i=Array.isArray((l=e.data)==null?void 0:l.inputs)?e.data.inputs:[],t=((d=(p=o.flowData)==null?void 0:p.state)==null?void 0:d.nodes)||[],s={};for(let n of i){let y=(u=n.key)==null?void 0:u.trim();if(!y)continue;let r=(a=n.from)==null?void 0:a.trim();if(!r){if(n.default===void 0)continue;s[y]=n.default;continue}let h=J(r,{context:o.context||{},results:o.results||{},nodes:t,edges:((m=(c=o.flowData)==null?void 0:c.state)==null?void 0:m.edges)??[],currentNodeId:e.id}),f=h.value;if(h.missing||f===void 0||f===null){if(n.default===void 0)throw new V(h.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Worker node ${e.id} could not resolve input "${r}"`);f=n.default}s[y]=f}return s}async function ut(e,o,i,t,s,l,p){var U,O,T,b,M,D;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let d=typeof((U=o.data)==null?void 0:U.flowId)=="string"?o.data.flowId.trim():"";d||q(t,o,new Error(`Worker node ${o.id} is missing flowId`));let u=(O=i.flowData)==null?void 0:O.flowId,a=e.workerStack??(u?[u]:[]);a.includes(d)&&q(t,o,new Error(`Worker node ${o.id} cannot call ${d}: cycle detected (${[...a,d].join(" \u2192 ")})`)),a.length>=vt&&q(t,o,new Error(`Worker node ${o.id} exceeded max nesting depth (${vt})`));let c=e.workerCalls??{count:0};e.workerCalls=c,c.count>=to&&q(t,o,new Error(`Worker node ${o.id} exceeded max worker calls per run (${to})`)),c.count+=1;let m;try{m=Oo(o,i)}catch($){q(t,o,$ instanceof Error?$:new Error(String($)));return}let n=e.env;n||q(t,o,new Error(`Worker node ${o.id} is missing runtime env`));let y,r;try{let $=await Rt(d,n);r=(T=$==null?void 0:$.metadata)==null?void 0:T.tenant,y=await xt(d,n)}catch($){q(t,o,new Error(`Worker node ${o.id} could not load worker ${d}: ${$ instanceof Error?$.message:String($)}`))}let h=(b=i.flowData)==null?void 0:b.tenant;(!r||r!==h)&&q(t,o,new Error(`Worker ${d} belongs to a different tenant`));let f=St(),g={flowData:{...y,tenant:r,flowId:d,chatId:((M=i.flowData)==null?void 0:M.chatId)||""},executedNodes:[],context:{},results:{}},w={env:n,ctx:e.ctx,secrets:e.secrets,userAuth:e.userAuth,user:e.user,toolDefs:e.toolDefs,toolCatalog:e.toolCatalog,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:f,workerStack:[...a,d]},x,N={onChangeState:()=>{},onServerEvent:$=>{var L;$o.has($.type)||t==null||t({type:"worker:node",content:{workerNodeId:o.id,childNodeId:(L=$.content)==null?void 0:L.nodeId,event:$}})},onTelemetry:$=>p==null?void 0:p($),onError:$=>{x=$},shouldStop:e.shouldStop},{startEngine:R,FlowExecutionStoppedError:_}=await import("./FlowEngine-RGHVLIOZ.js"),F=await R(w,g,N)({text:"",inputs:m});if((F.status==="stopped"||await((D=e.shouldStop)==null?void 0:D.call(e)))&&q(t,o,new _),F.status!=="completed"){let $=Io(g),L=Fo(g),C=F.error||x||"unknown error",j=$?` at node ${$.label?`${$.id} (${$.label})`:$.id}`:"";q(t,o,new Error(`Worker ${d} failed${j}: ${C}. Path: ${L}`))}f.hasOutputs()||q(t,o,new Error(`El worker ${d} complet\xF3 sin output estructurado. Agreg\xE1 un mapeo de salida en su nodo Answer.`));let P=(g.executedNodes||[]).map($=>$.id);s==null||s(o.id,{ok:!0,data:f.snapshotData(),error:null,executed:P}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}import{generateObject as Uo}from"ai";import{z as oo}from"zod";import{openai as _o}from"@ai-sdk/openai";import{extractReasoningMiddleware as ko,wrapLanguageModel as Do}from"ai";import{createWorkersAI as Mo}from"workers-ai-provider";import{xai as Po}from"@ai-sdk/xai";import{anthropic as bo}from"@ai-sdk/anthropic";import{createOpenRouter as Co}from"@openrouter/ai-sdk-provider";var ft={};function pt(e){if(e!=null){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}}function jo(e){return{...e,defaultParams:pt(e.defaultParams)??e.defaultParams,capabilities:pt(e.capabilities)??e.capabilities,price:pt(e.price)??e.price}}async function et(e,o,i){var c,m;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=jo(t),l=((c=s.capabilities)==null?void 0:c.params)??jt(s),{effectiveParams:p,adjustments:d}=Vt(s.defaultParams,i,l),u;if(ft[s.provider])u=await ft[s.provider](s,o,i);else if(s.provider==="openai")u=_o(s.providerModel);else if(s.provider==="xai")u=Po(s.providerModel);else if(s.provider==="anthropic")u=bo(s.providerModel);else if(s.provider==="openrouter")u=Co()(s.providerModel);else if(s.provider==="workersai"||s.provider==="cloudflare"){if(!((m=o==null?void 0:o.env)!=null&&m.AI))throw new Error("Workers AI provider requires sessionEnv.env.AI binding");u=Mo({binding:o.env.AI})(s.providerModel)}else u={provider:s.provider,providerModel:s.providerModel};let a=Ht(s);return a.kind==="tag"&&u&&typeof u=="object"&&"specificationVersion"in u&&(u=Do({model:u,middleware:ko({tagName:a.tagName??"think",startWithReasoning:a.startWithReasoning??!1})})),{provider:s.provider,modelHandle:u,entry:s,effectiveParams:p,paramAdjustments:d.length>0?d:void 0,reasoning:a}}function De(e,o){ft[e]=o}async function mt(e,o,i,t,s,l,p){var r,h,f,g,w,x,N;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let d=String(((r=o==null?void 0:o.data)==null?void 0:r.input_variable)||"user_input").trim(),u;try{let R=J(d,{context:i.context??{},results:i.results??{},nodes:((f=(h=i.flowData)==null?void 0:h.state)==null?void 0:f.nodes)??[],edges:((w=(g=i.flowData)==null?void 0:g.state)==null?void 0:w.edges)??[],currentNodeId:o.id});if(R.missing)throw new Error(`Classifier input "${d}" did not produce a value`);u=R.value}catch(R){throw t==null||t({type:"error:classifier",content:String(R)}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(R)}}),R}let a=Array.isArray((x=o==null?void 0:o.data)==null?void 0:x.items)?o.data.items:[];if(a.length===0){t==null||t({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let c=String((N=a[a.length-1])==null?void 0:N.id);if(!u||String(u).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,l==null||l(i);return}let n=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
|
|
2
|
-
If the message is ambiguous or none clearly matches, choose the LAST category in the list.
|
|
3
|
-
|
|
4
|
-
Categories:
|
|
5
|
-
${a.map(R=>{let _=R.keywords??R["keywords/topics"]??"",F=Array.isArray(_)?_.join(", "):String(_||"");return`- id: ${R.id}
|
|
6
|
-
label: ${R.label}
|
|
7
|
-
keywords/topics: ${F}`}).join(`
|
|
8
|
-
`)}
|
|
9
|
-
`,y=`User message:
|
|
10
|
-
"""${String(u).trim()}"""
|
|
11
|
-
|
|
12
|
-
Select the best matching category id.`;try{let R=Date.now(),_=a.map(D=>String(D.id)),F="gpt_4_1_mini",P=await et(F,e);if(!P)throw new Error(`Model '${F}' not found in registry`);let{modelHandle:U,effectiveParams:O}=P,T=await Uo({model:U,messages:[{role:"system",content:n},{role:"user",content:y}],schema:oo.object({classification:oo.enum(_).describe("The id of the best matching category")}),temperature:O.temperature??0}),b=Date.now()-R,M=T.object.classification;p==null||p({type:"class_telemetry",payload:{nodeId:o.id,totalLatency:b,model:T.response.modelId,usage:T.usage,options:_}}),p==null||p({type:"class_result",payload:{result:T}}),s==null||s(o.id,{classification:M}),i.context=i.context||{},i.context.classified_id=M,l==null||l(i),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}catch(R){throw t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(R)}}),R}}import{stepCountIs as Wo,streamText as Jo}from"ai";import{nanoid as Xo}from"nanoid";import"zod";function eo(e,o){var d,u,a,c,m;let i=((d=e.data)==null?void 0:d.attachments)??[];if(!Array.isArray(i))throw new V("INVALID_EXPRESSION",`Node ${e.id} attachments must be an array`);let t=((a=(u=o.flowData)==null?void 0:u.state)==null?void 0:a.nodes)??[],s=((m=(c=o.flowData)==null?void 0:c.state)==null?void 0:m.edges)??[],l=Y(t,s,e.id),p="";for(let n of i){if(typeof n!="string")throw new V("INVALID_EXPRESSION",`Node ${e.id} has an invalid attachment reference`);let y=l.find(h=>h.ref===n);if(!y)throw new V("OUT_OF_SCOPE",`Attachment "${n}" is not in this node's connection scope`);if(y.type!=="file"&&y.type!=="image")throw new V("UNKNOWN_OUTPUT",`Attachment "${n}" is not an image or file output`);if(y.type!=="file")continue;let r=J(n,{context:o.context??{},results:o.results??{},nodes:t,edges:s,currentNodeId:e.id});if(r.missing)throw new V(r.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${n}" did not produce a value`);if(typeof r.value!="string")throw new V("PATH_NOT_FOUND",`Attachment "${n}" must resolve to file text`);r.value.trim()&&(p+=(p?`
|
|
13
|
-
|
|
14
|
-
`:"")+r.value)}return p}function Vo(e,o){var s,l,p,d,u;let i=((s=e.data)==null?void 0:s.attachments)??[];if(!Array.isArray(i))throw new V("INVALID_EXPRESSION",`Node ${e.id} attachments must be an array`);let t=Y(((p=(l=o.flowData)==null?void 0:l.state)==null?void 0:p.nodes)??[],((u=(d=o.flowData)==null?void 0:d.state)==null?void 0:u.edges)??[],e.id);return i.map(a=>{if(typeof a!="string")throw new V("INVALID_EXPRESSION",`Node ${e.id} has an invalid attachment reference`);let c=t.find(m=>m.ref===a);if(!c)throw new V("OUT_OF_SCOPE",`Attachment "${a}" is not in this node's connection scope`);if(c.type!=="image"&&c.type!=="file")throw new V("UNKNOWN_OUTPUT",`Attachment "${a}" is not a binary output`);return c.type==="image"?a:null}).filter(a=>a!==null)}function io(e,o){var s,l,p,d;let i=[],t={context:o.context??{},results:o.results??{},nodes:((l=(s=o.flowData)==null?void 0:s.state)==null?void 0:l.nodes)??[],edges:((d=(p=o.flowData)==null?void 0:p.state)==null?void 0:d.edges)??[],currentNodeId:e.id};for(let u of Vo(e,o)){let a=J(u,t);if(a.missing)throw new V(a.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${u}" did not produce a value`);if(!Array.isArray(a.value))throw new V("PATH_NOT_FOUND",`Attachment "${u}" must resolve to an image array`);i.push(...a.value)}return i}var B=(e,o,i)=>{e.send(o+"::"+i)};var Lo=Q({"../tools/composioDirectTool.ts":()=>import("./composioDirectTool-H3GSCIPY.js"),"../tools/composioTool.ts":()=>import("./composioTool-5LFWUQ7F.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-2BU6JAAK.js"),"../tools/skillTool.ts":()=>import("./skillTool-AIOXPTAJ.js"),"../tools/tempTool.ts":()=>import("./tempTool-2RXAF56M.js"),"../tools/twitter.ts":()=>import("./twitter-OMDEG7T2.js"),"../tools/vectorize.ts":()=>import("./vectorize-CDB26DMD.js")});var Ho=Q({});async function qo(e,o,i,t){var m;let s=Array.isArray((m=i==null?void 0:i.data)==null?void 0:m.tools)?i.data.tools:[];if(s.length===0)return{};let l={},p=n=>{var x,N;let y=typeof(n==null?void 0:n.description)=="string"?n.description:"",r=n==null?void 0:n.inputSchema,h;try{let R=(r==null?void 0:r.shape)??(typeof((x=r==null?void 0:r._def)==null?void 0:x.shape)=="function"?r._def.shape():(N=r==null?void 0:r._def)==null?void 0:N.shape);R&&typeof R=="object"&&(h=R)}catch{}let f=h?Object.keys(h):[],g=y?`description="${y.length>120?y.slice(0,120)+"\u2026":y}"`:"description=(none)",w=f.length?`inputSchema={${f.join(", ")}}`:"inputSchema=(none)";return`${g} ${w}`},d=(()=>{let n=[],y=[],r=[],h=[];for(let g=0;g<s.length;g++){let w=s[g];!w||typeof w!="object"||typeof w.id!="string"?h.push(g):w.kind==="builtin"?n.push(w.id):w.kind==="skill"?r.push(w.id):w.kind==="http"||w.kind==="mcp"||w.kind==="composio"?y.push(w.id):h.push(g)}let f=[];return n.length&&f.push(`builtin[${n.join(", ")}]`),y.length&&f.push(`custom[${y.join(", ")}]`),r.length&&f.push(`skill[${r.join(", ")}]`),h.length&&f.push(`invalid@[${h.join(", ")}]`),f.join(" ")||"(none)"})();console.log(`[tools] node ${i.id} requested (${s.length}): ${d}`);let u=!1,a=async()=>{if(u&&e.toolDefs)return e.toolDefs;if(!e.env)return e.toolDefs=e.toolDefs||{},u=!0,e.toolDefs;try{let n=await v(e.env),y={};for(let r of n)r&&r.id&&(y[r.id]=r);e.toolDefs=y}catch(n){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(n)}`}),e.toolDefs=e.toolDefs||{}}return u=!0,e.toolDefs},c=[];for(let n=0;n<s.length;n++){let y=s[n];if(!y||typeof y!="object"||typeof y.id!="string"||y.kind!=="builtin"&&y.kind!=="http"&&y.kind!=="mcp"&&y.kind!=="composio"&&y.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${n}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let r=y;if(r.kind!=="builtin"){let f=(await a())[r.id];if(!f){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 w=await zt(f,e,o,t),x=Object.keys(w);for(let[N,R]of Object.entries(w))l[N]=R;console.log(`[tools] \u2713 composio '${r.id}' \u2192 ${x.length} tool(s)`)}catch(w){console.error(`[tools] \u2717 composio '${r.id}': ${String(w)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${r.id}': ${String(w)}`})}continue}if(r.kind==="skill"){if(f.kind!=="skill"){console.error(`[tools] \u2717 skill '${r.id}': row is of kind '${f.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${r.id}' is not a skill`});continue}let w=f.name;if(l[w]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin/other already registered, skipping skill '${r.id}'`});continue}try{l[w]=Kt(f,e,o,t),c.push(f);let x=typeof f.execution=="string"?JSON.parse(f.execution):f.execution||{},N=Array.isArray(x.references)?x.references.map(R=>R==null?void 0:R.name):[];console.log(`[tools] \u2713 skill '${r.id}' \u2192 '${w}' (refs: ${N.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:w,refCount:N.length,refs:N}})}catch(x){console.error(`[tools] \u2717 skill '${r.id}': ${String(x)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${r.id}': ${String(x)}`})}continue}let g=f.name;if(l[g]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${g}' \u2014 builtin already registered, skipping custom tool '${r.id}'`});continue}try{let w=tt(f,e,o,t);l[g]=w,console.log(`[tools] \u2713 custom '${r.id}' \u2192 '${g}'`),console.log(`[tools] ${p(l[g])}`)}catch(w){console.error(`[tools] \u2717 custom '${r.id}': ${String(w)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${r.id}': ${String(w)}`})}continue}if(!qt[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 h;try{h=await Lo(`../tools/${r.id}.ts`)}catch{h=await Ho(`../tools/${r.id}.js`)}let f;if(h[r.id])f=h[r.id];else if(h.default)f=h.default;else if(h.create)f=h.create;else{let F=Object.values(h);F.length>0&&(f=F[0])}if(!f){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${r.id}'`});continue}let g,w,x={};if(r.params&&typeof r.params=="object"){if(typeof r.params.description=="string"?g=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 F=r.params.inputSchema;typeof F=="object"&&(typeof F.safeParse=="function"||F._def)?w=F:typeof F=="object"&&F!==null&&F.type==="object"&&F.properties?(w=Ct(F),w||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)?x=r.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${r.id}' \u2014 must be an object`}),x={}):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`}),x={}):x={}}let N=f(e,o,x,t);g&&N&&typeof N=="object"&&(N.description=g),w&&N&&typeof N=="object"&&(N.inputSchema=w),l[r.id]=N;let R=[];g&&R.push("description"),w&&R.push("inputSchema"),Object.keys(x).length&&R.push(`defaults(${Object.keys(x).join(",")})`);let _=R.length?` [overrides: ${R.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${r.id}'${_}`),console.log(`[tools] ${p(N)}`)}catch(h){console.error(`[tools] \u2717 builtin '${r.id}': ${String(h)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${r.id}': ${String(h)}`});continue}}if(c.length>0)if(l.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{l.readSkillRef=Bt(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(n=>n.name)}})}catch(n){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(n)}`)}return l}async function yt(e,o,i,t,s,l,p){var F,P,U,O;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let d=!1;try{let T=(F=i.flowData)==null?void 0:F.state;if(T&&T.edges&&T.nodes){let b=T.edges.filter(M=>M.source===o.id);if(b.length>0){let M=T.nodes.find(D=>D.id===b[0].target);M&&M.type==="answerNode"&&(d=!0)}}}catch(T){console.error("Error determining next node for streaming:",T)}let u=z(o.data.template,o,i,t,{sessionEnv:e});(!u||!u.trim())&&(u="Answer straight forward to the user, dont offer any other option to continue");let a=u,c=z(o.data.user_template||"",o,i,t,{sessionEnv:e}),m=T=>T&&Object.fromEntries(Object.keys(T).map(b=>[b,"[redacted]"])),n=e!=null&&e.secrets||e!=null&&e.userAuth?{...e,secrets:m(e.secrets),userAuth:m(e.userAuth)}:e,y=z(o.data.template,o,i,void 0,{sessionEnv:n})||a,r=z(o.data.user_template||"",o,i,void 0,{sessionEnv:n});t==null||t({type:`info:llmNodeRunner:${o.id}`,content:y}),t==null||t({type:`info:llmNodeRunner:${o.id}`,content:r});let h=(P=o==null?void 0:o.data)==null?void 0:P.window_size,f=Number(h);(!Number.isInteger(f)||f<=0)&&(f=5);let g=io(o,i),w=eo(o,i);t==null||t({type:"info:llmNodeRunner:attachments",content:{nodeId:o.id,refs:Array.isArray((U=o.data)==null?void 0:U.attachments)?o.data.attachments:[],images:g.length,documents:w?1:0}});let N=(await((O=e.getMessages)==null?void 0:O.call(e))??[]).slice(-f),R=N.filter(T=>T&&typeof T.role=="string"&&typeof T.content=="string");R.length!==N.length&&console.warn(`Filtered ${N.length-R.length} invalid messages from history`);let _=Ko(R,c,g,w);await zo(u,_,e.conn,t,o,d,s,i,l,e,p)}async function zo(e,o,i,t,s,l,p,d,u,a,c){var n;let m=Date.now();if(!((n=a.env)!=null&&n.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(y,r)=>{var b,M,D,$,L,C;let h,f={},g,w="none",x=!1,N,R=!1,_=!1,F=0,P=0,U=(b=s==null?void 0:s.data)==null?void 0:b.sendReasoning,O=U!==!1;try{let j=(M=s==null?void 0:s.data)==null?void 0:M.model,H=Array.isArray(j)?j[0]:j||"gpt_5_nano",A=Ut(s==null?void 0:s.data),k=await et(H,a,A);if(!k)throw new Error(`Model '${H}' not found in registry`);h=k.modelHandle,f=k.effectiveParams||{},w=k.reasoning.kind;let I=Jt(k.reasoning,(D=s==null?void 0:s.data)==null?void 0:D.reasoningEffort);x=O&&Wt(k.reasoning);let X=typeof(($=s==null?void 0:s.data)==null?void 0:$.reasoningMaxTokens)=="number"?s.data.reasoningMaxTokens:void 0;g=Xt(k.provider,{effort:I,exposeReasoning:x,maxTokens:X}),I&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:I})),console.log(`[reasoning] ${JSON.stringify({model:H,provider:k.provider,capability:k.reasoning,requestedEffort:((L=s==null?void 0:s.data)==null?void 0:L.reasoningEffort)??null,resolvedEffort:I??null,sendReasoning:O,exposeReasoning:x,providerOptions:g??null},null,2)}`);for(let W of k.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:W});t==null||t({type:"info:llmNodeRunner:model",content:H}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(C=s==null?void 0:s.data)!=null&&C.generationPreset?{preset:s.data.generationPreset}:{},...f,...w!=="none"?{reasoning:w,configuredSendReasoning:U,sendReasoning:O,exposeReasoning:x,...I?{effort:I}:{}}:{}}})}catch(j){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(j)}`}),j}let T=await qo(a,d,s,t);console.log(`[tools] node ${s.id} loaded ${Object.keys(T).length}: ${Object.keys(T).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:s.id,tools:Object.keys(T)}});try{let j=Jo({model:h,system:e,messages:o,stopWhen:(()=>{var W;let k=!!T.readSkillRef?10:5,I=Number(((W=s.data)==null?void 0:W.max_steps)??k),X=Number.isFinite(I)?Math.max(1,Math.min(30,I)):k;return Wo(X)})(),...Lt(f),...g?{providerOptions:g}:{},tools:T,onFinish:async A=>{var ht,Nt;let k=A.text||"",I=A.reasoningText??((ht=A.reasoning)==null?void 0:ht.text)??"";if(console.log(`[reasoning] done: deltas=${F} chars=${P} result.reasoningText=${I.length} finishReason=${A.finishReason??"n/a"} reasoningTokens=${((Nt=A.usage)==null?void 0:Nt.reasoningTokens)??"n/a"}`),O&&x&&!R&&I&&i){R=!0;try{B(i,K.SERVER_REASONING_STREAM,I)}catch(no){console.warn("Failed to send finished reasoning over connection",no)}}let X={id:Xo(),role:"assistant",type:"text",content:k,ts:Date.now()};l&&(a.setMessages?await a.setMessages(X):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),i&&O&&R&&!_&&(_=!0,B(i,K.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),l&&i&&B(i,K.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),p==null||p((s==null?void 0:s.id)||"llm_result",k),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(A)});let W=Date.now()-m,ro=N?N-m:void 0;c==null||c({type:"llm_telemetry",payload:{nodeId:s.id,totalLatency:W,timeToFirstToken:ro,model:A.response.modelId,usage:A.usage}}),c==null||c({type:"llm_result",payload:{result:A}})},onStepFinish:async A=>{let k=(I,X=200)=>{let W=typeof I=="string"?I:JSON.stringify(I);return W?W.length>X?`${W.slice(0,X)}\u2026(+${W.length-X})`:W:""};if(A.toolCalls&&A.toolCalls.length>0){for(let I of A.toolCalls)console.log(`[tools] \u2192 ${I.toolName}(${k(I.args??I.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${s.id}`,content:JSON.stringify(A.toolCalls)})}if(A.toolResults&&A.toolResults.length>0){for(let I of A.toolResults)console.log(`[tools] \u2190 ${I.toolName} \u2192 ${k(I.result??I.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${s.id}`,content:JSON.stringify(A.toolResults)})}},experimental_onToolCallStart:A=>{var k;t==null||t({type:"tool:execution",content:{nodeId:s.id,toolName:(k=A==null?void 0:A.toolCall)==null?void 0:k.toolName,status:"start"}})},experimental_onToolCallFinish:A=>{var k,I;t==null||t({type:"tool:execution",content:{nodeId:s.id,toolName:(k=A==null?void 0:A.toolCall)==null?void 0:k.toolName,status:((I=A==null?void 0:A.toolOutput)==null?void 0:I.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 I=A.chunk.text??A.chunk.delta??"";if(I&&(R=!0,F+=1,P+=I.length,F===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),O&&i&&I)try{B(i,K.SERVER_REASONING_STREAM,I)}catch(X){console.warn("Failed to send reasoning chunk over connection",X)}return}if(A.chunk.type==="text-delta"){if(N||(N=Date.now()),i&&O&&R&&!_){_=!0;try{B(i,K.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(I){console.warn("Failed to send reasoning complete over connection",I)}}return}c==null||c({type:A.chunk.type,payload:{nodeId:s.id,chunk:A.chunk}});let k=`llm_chunk:${A.chunk.type}`;t==null||t({type:k,content:{...A}})}}),H=async()=>{let A="";for await(let k of j.fullStream)if(k.type==="text-delta"){if(A+=k.text,l&&i)try{B(i,K.SERVER_TEXT_STREAM,k.text)}catch(I){console.warn("Failed to send chunk over connection",I)}}else if(k.type==="finish-step"&&k.finishReason==="tool-calls"){if(l&&i&&A.trim())try{B(i,K.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(I){console.warn("Failed to flush text segment over connection",I)}A=""}};await Promise.all([j,H()]),y(),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 Ko(e,o,i,t){let s=!!(i&&i.length>0),l=!!t,p=s||l,u=e.length>0&&e[e.length-1].role==="user"?e[e.length-1]:void 0,a=c=>{let m=[],n="";if(l&&(n+=`[Attached files]
|
|
15
|
-
${t}
|
|
16
|
-
[End of attached files]
|
|
17
|
-
|
|
18
|
-
`),c&&(n+=c),n&&m.push({type:"text",text:n}),s)for(let y of i)m.push({type:"image",image:y.data,mimeType:y.mimeType});return m};return o&&u&&u.content===o?[...e.slice(0,-1).map(m=>({role:m.role,content:m.content})),{role:"user",content:a(o)}]:o?[...e.map(c=>({role:c.role,content:c.content})),{role:"user",content:a(o)}]:p&&u?[...e.slice(0,-1).map(m=>({role:m.role,content:m.content})),{role:"user",content:a(u.content)}]:e.map(c=>({role:c.role,content:c.content}))}async function gt(e,o,i,t,s,l,p){var c,m,n,y,r,h,f;console.log(`**** MEMO Node id: ${o.id} ****`),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let d="",u=!1,a=Date.now();try{t==null||t({type:"info:memoNodeRunner",content:"Starting memo node execution"});let g=String(((c=o.data)==null?void 0:c.query_key)||"user_input"),w=J(g,{context:i.context??{},results:i.results??{},nodes:((n=(m=i.flowData)==null?void 0:m.state)==null?void 0:n.nodes)??[],edges:((r=(y=i.flowData)==null?void 0:y.state)==null?void 0:r.edges)??[],currentNodeId:o.id});if(w.missing)throw new Error(`Memo query "${g}" did not produce a value`);if(!e.env||!e.ctx){t==null||t({type:"error:memoNodeRunner",content:"Missing env or ctx"}),s==null||s(o.id,d);return}if(!o.data.rag_id){t==null||t({type:"error:memoNodeRunner",content:"Missing rag_id"}),s==null||s(o.id,d);return}let x=String(w.value??"");t==null||t({type:"info:memoNodeRunner",content:`Query text: ${x}`}),t==null||t({type:"info:memoNodeRunner",content:"Generating embedding for query"});let N=await Tt(e,x,!0);t==null||t({type:"info:memoNodeRunner",content:`Embedding generated successfully, length: ${N.data[0].length}`});let R=Array.isArray(o.data.rag_id)?o.data.rag_id:[o.data.rag_id],_=[];for(let O of R){t==null||t({type:"info:memoNodeRunner",content:`Executing RAG query with namespace: ${O}`});let T=await e.env[`VDB_${(h=i.flowData)==null?void 0:h.tenant}_1024`].query(N.data[0],{namespace:O,topK:o.data.topk,returnMetadata:"all"});t==null||t({type:"info:memoNodeRunner",content:`RAG query completed for namespace ${O}, matches: ${((f=T.matches)==null?void 0:f.length)||0}`}),Array.isArray(T.matches)&&_.push(...T.matches)}let F=Date.now()-a;d=_.map(O=>{var T;return(T=O.metadata)==null?void 0:T.value}).filter(O=>typeof O=="string").join(`
|
|
19
|
-
|
|
20
|
-
`),p==null||p({type:"memo_search",payload:{nodeId:o.id,searchLatencyMs:F,retrievedContext:d}}),t==null||t({type:"info:memoNodeRunner",content:`Context retrieval complete, length: ${d.length}, preview: ${d.substring(0,200)}...`}),t==null||t({type:"info:memoNodeRunner",content:"Memo node execution completed successfully"}),u=!0}catch(g){throw console.error("Error processing MemoNode:",g),t==null||t({type:"error:memoNodeRunner",content:`Memo node execution failed: ${g}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(g)}}),g}finally{u&&(s==null||s(o.id,d),t==null||t({type:"info:memoNodeRunner",content:`onResult called with context length: ${d.length}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}}))}}async function wt(e,o,i,t,s,l,p){var c,m,n,y,r,h,f,g;console.log(`**** START Node ${o.id} ****`),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}}),t==null||t({type:"info:flow",content:i}),p==null||p({type:"start_node",payload:{userMessage:(c=i==null?void 0:i.context)==null?void 0:c.user_input}});let d=((m=o.data)==null?void 0:m.allow_images)!==!1,u=((n=o.data)==null?void 0:n.allow_documents)!==!1;!d&&(i!=null&&i.context)&&(i.context.user_images=[],l==null||l({...i})),!u&&(i!=null&&i.context)&&(i.context.files="",l==null||l({...i}));let a={};for(let w of E(o.data))a[w.name]=(y=i==null?void 0:i.context)==null?void 0:y[w.name];s==null||s(o.id,{...a,user_input:(r=i==null?void 0:i.context)==null?void 0:r.user_input,images:d?(h=i==null?void 0:i.context)==null?void 0:h.user_images:[],files:u?(f=i==null?void 0:i.context)==null?void 0:f.files:"",memory:((g=i==null?void 0:i.context)==null?void 0:g.memory)??""}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}function Ui(e,o,i){let t=o;async function s(){var a;if(await((a=i==null?void 0:i.shouldStop)==null?void 0:a.call(i)))throw new it}async function l(a){let c=a;for(t.executedNodes=t.executedNodes||[],t.context=t.context||{},t.results=t.results||{};c&&c.id;)await s(),await p(c),await s(),c=Yo(c,t.flowData,t)}async function p(a){var r,h;let c=u[a.type];if(!c){(r=i==null?void 0:i.onError)==null||r.call(i,`Unknown node type: ${a.type}`);return}t.executedNodes=t.executedNodes||[],t.executedNodes.push({id:a.id,type:a.type,label:typeof((h=a.data)==null?void 0:h.label)=="string"?a.data.label:void 0}),t.lastNodeId=a.id;let m=f=>{var g;return(g=i==null?void 0:i.onServerEvent)==null?void 0:g.call(i,{...f,ts:Date.now()})},n=f=>{var g,w;if((g=i==null?void 0:i.onTelemetry)==null||g.call(i,f),f.type==="llm_telemetry"||f.type==="class_telemetry"||f.type==="memory_update"){let x=(w=f.payload)==null?void 0:w.usage;x&&(t.tokenUsage=t.tokenUsage||{promptTokens:0,completionTokens:0,totalTokens:0},t.tokenUsage.promptTokens+=x.promptTokens||0,t.tokenUsage.completionTokens+=x.completionTokens||0,t.tokenUsage.totalTokens+=x.totalTokens||0)}};return await c(e,a,t,m,(f,g)=>{t.results[f]=g},i==null?void 0:i.onChangeState,n)}let d=async a=>{var y,r,h,f,g,w,x;let c=Date.now(),m="completed",n;try{await s();let N=typeof a=="string"?$t(a):a,R=(N==null?void 0:N.text)||"",_=(N==null?void 0:N.images)||[],F=(N==null?void 0:N.documents)||[],P=await Gt(F,e.env),U=P.length>0?P.map(b=>`--- file: ${b.name} ---
|
|
21
|
-
${b.text}`).join(`
|
|
22
|
-
|
|
23
|
-
`):"";t.context={user_input:R,user_images:_,files:U},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},t.executedNodes=[],(y=i==null?void 0:i.onServerEvent)==null||y.call(i,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:O,error:T}=Bo(t.flowData);if(!O)m="failed",n=T||"Flow Format Error",(r=i==null?void 0:i.onError)==null||r.call(i,n);else{let b=E(O.data),{values:M,errors:D}=At(b,N==null?void 0:N.inputs);if(D.length>0)return m="failed",n=`Invalid flow inputs: ${D.join("; ")}`,(h=i==null?void 0:i.onError)==null||h.call(i,n),{status:m,error:n};if(t.context={...t.context,inputs:M,...M},t.context.user_input||(t.context.user_input=R),Ot(O.data)){let $=Ft(_t(O.data));t.context.memory=It(e.agentMemory||"",$).content}else t.context.memory="";await l(O),(f=i==null?void 0:i.onServerEvent)==null||f.call(i,{type:"agent:telemetry",content:{durationMs:Date.now()-c,tokenUsage:t.tokenUsage},timestamp:Date.now()})}}catch(N){N instanceof it?(m="stopped",n=N.message,(g=i==null?void 0:i.onServerEvent)==null||g.call(i,{type:"agent:stopped",content:n,timestamp:Date.now()})):(m="failed",n=N instanceof Error?N.message:"Agent execution failed",(w=i==null?void 0:i.onError)==null||w.call(i,n))}finally{(x=i==null?void 0:i.onServerEvent)==null||x.call(i,{type:"agent:complete",content:{status:m,durationMs:Date.now()-c},timestamp:Date.now()})}return{status:m,error:n}},u={startNode:wt,classifierNode:mt,llmNode:yt,memoNode:gt,answerNode:st,apiNode:at,toolNode:ct,workerNode:ut};return d}var it=class extends Error{constructor(){super("Stopped by user"),this.name="FlowExecutionStoppedError"}};function Bo(e){var c,m;let o=(e==null?void 0:e.state)??e;if(!o||!o.nodes||!o.edges||o.edges.length===0)return{error:"Flow is missing state, nodes, or edges."};if(o.schemaVersion!==3)return{error:"Flow uses an unsupported variable schema. Recreate it in Agent Design 3.0."};for(let n of o.nodes){if(((c=n.data)==null?void 0:c.varMapping)!==void 0)return{error:`Flow uses removed varMapping on node ${n.id}.`};let y=kt(n);if(y.length>0)return{error:y[0]}}let i=o.nodes.filter(n=>n.type==="startNode");if(i.length!==1)return{error:`Flow must include exactly one START node, found ${i.length}.`};let t=i[0],s=o.nodes.filter(n=>n.type==="answerNode");if(s.length===0)return{error:"Flow must include at least one ANSWER node."};let l=new Map;for(let n of o.edges)l.has(n.source)||l.set(n.source,[]),l.get(n.source).push(n.target);let p=new Map;for(let n of o.edges)p.has(n.target)||p.set(n.target,[]),p.get(n.target).push(n.source);let d=so(t.id,l),u=new Set;for(let n of s){let y=so(n.id,p);for(let r of y)u.add(r)}let a=[];for(let n of d)if(!u.has(n)){let y=o.nodes.find(r=>r.id===n);if(y){let r=((m=y.data)==null?void 0:m.label)||"";a.push(`${n}(${r},${y.type})`)}}return a.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${a.join(", ")}`}:{startNode:t}}function so(e,o){let i=new Set,t=[e];for(i.add(e);t.length>0;){let s=t.shift(),l=o.get(s)||[];for(let p of l)i.has(p)||(i.add(p),t.push(p))}return i}function Go(e,o){var i;return((i=e.state)==null?void 0:i.nodes.find(t=>t.id===o))||null}function Yo(e,o,i){var d;let t=o==null?void 0:o.state;if(!t)return null;let s=t.edges.filter(u=>u.source===e.id);if(s.length===0)return null;let l=s[0].target;if(e.type==="classifierNode"&&((d=i==null?void 0:i.context)!=null&&d.classified_id)){let u=i.context.classified_id,a=s.find(c=>c.sourceHandle===`source-${u}`);a?l=a.target:console.log(`No matching edge, falling back to first: ${l}`)}return Go(o,l)}export{B as a,lo as b,St as c,ge as d,jo as e,et as f,De as g,Ui as h,it as i};
|
package/dist/chunk-ELMOSEQ7.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as t,c as i,j as s}from"./chunk-MOYYZBTC.js";import{Composio as m}from"@composio/core";function c(r){return typeof r!="string"?void 0:r.trim()||void 0}async function k(r,e){let l=i(r),u=new m({apiKey:l}),a=t(e.connectionScope),n=c(e.toolVersion)??c(e.toolkitVersion);try{n||console.warn(`[composioDirectTool] No toolVersion/toolkitVersion for ${e.toolSlug}; executing with dangerouslySkipVersionCheck`);let o=await u.tools.execute(e.toolSlug,{userId:a,arguments:e.arguments,...n?{version:n}:{dangerouslySkipVersionCheck:!0}});return o&&typeof o=="object"&&"successful"in o&&o.successful===!1?{ok:!1,data:null,error:typeof o.error=="string"&&o.error.trim()?o.error:"Tool execution failed"}:{ok:!0,data:o&&typeof o=="object"&&"data"in o?o.data:o,error:null}}catch(o){return s(o)?{ok:!1,error:"This connector is not connected. Ask a tenant admin to connect it in Tools."}:{ok:!1,error:o instanceof Error?o.message:String(o)}}}export{k as a};
|
package/dist/chunk-OF6G42DM.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as F,b as S,c as v,d as U,e as P,f as K,g as N,h as O,i as M,j,k as g,l as h}from"./chunk-MOYYZBTC.js";import{Composio as L}from"@composio/core";import{VercelProvider as B}from"@composio/vercel";function w(o,n,i,s,t){let r=s?g(s)??s.trim():void 0;!r||!r.startsWith("http")||o==null||o({type:"info:composio:auth_required",content:{toolkit:t,redirectUrl:r,toolRowId:n.id}})}function q(o){let n=g(o);if(n)return n;if(typeof o=="string")return g(o);try{return g(JSON.stringify(o))}catch{return}}async function W(o,n,i,s,t,r=!0){var e;let l=await o.toolkits({toolkits:n.toolkits});for(let u of l.items)if(!(u.isNoAuth||(e=u.connection)!=null&&e.isActive))try{let p=await o.authorize(u.slug,{callbackUrl:i});r&&w(t,s,n,p.redirectUrl,u.slug);break}catch(p){`${u.slug}${String(p)}`}}function H(o,n,i,s,t=!0){let r={};for(let[l,e]of Object.entries(o)){if(!e||typeof e!="object"||typeof e.execute!="function"){r[l]=e;continue}let u=e.execute.bind(e);r[l]={...e,execute:async(...p)=>{try{let c=await u(...p);if(t){let m=q(c);m&&w(s,n,i,m,h(String(c),i))}return c}catch(c){if(j(c)){let m=q(c);w(s,n,i,m,h(String(c),i))}throw c}}}}return r}async function X(o,n,i,s){var R,$,I,A,T,E;if(o.kind!=="composio")throw new Error(`loadComposioTools: unsupported kind '${o.kind}' for tool '${o.name}'`);let t=O(o.execution),r=v(n),l=t.authMode==="manual",e;if(l){let a=F(t,o.id);if(!a)throw new Error(`Composio manual tool '${o.name}' is missing connection scope (tool id or execution.connectionScope)`);e=S(a)}else e=K(n,i,{allowChatIdFallback:!0});let u=(R=i.flowData)==null?void 0:R.flowId,p=($=i.flowData)==null?void 0:$.chatId,c=((I=t.manageConnections)==null?void 0:I.callbackUrl)||N(n,u,p,o.id),m=M(t,c),C=new L({apiKey:r,provider:new B});n.composioSessions||(n.composioSessions={});let b=U(t),z=l?!1:((A=t.workbench)==null?void 0:A.enable)!==!1,d,f=n.composioSessions[o.id];f!=null&&f.sessionId&&f.userId===e&&f.configKey===b?(d=await C.use(f.sessionId),`${f.sessionId}${o.name}${e}`,void 0):(d=await C.create(e,P(t,{manageConnections:m,workbench:{enable:z}})),n.composioSessions[o.id]={sessionId:d.sessionId,userId:e,configKey:b},`${d.sessionId}${o.name}${e}${t.authMode}${t.sessionPreset??"default"}`,(T=t.sessionPreload)!=null&&T.enabled,void 0);try{let a=await d.toolkits({toolkits:t.toolkits});for(let k of a.items){let x=!!(k.isNoAuth||(E=k.connection)!=null&&E.isActive);`${k.slug}${x}${e}`}await W(d,t,c,o,s,!l)}catch(a){`${o.name}${String(a)}`}let y=await d.tools(),D=Array.isArray(y)?Object.fromEntries(y.map(a=>[a.name??a.toolName,a])):y;return H(D,o,t,s,!l)}export{X as a};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a}from"./chunk-ELMOSEQ7.js";import"./chunk-MOYYZBTC.js";import"./chunk-3TXHFKDN.js";export{a as executeComposioCatalogTool};
|
package/dist/oraApi-4O3W5LXD.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d}from"./chunk-A2IRPAD4.js";import"./chunk-3TXHFKDN.js";export{c as fetchOraModel,d as fetchSkillRef,b as fetchToolCatalog,a as fetchToolDefs};
|