@hugex/ai 3.2.0-canary.3 → 3.3.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.
@@ -1 +1 @@
1
- import{h as a,i as b}from"./chunk-DEW7U7V7.js";import"./chunk-V35SRZAO.js";import"./chunk-ZYIULB2P.js";import"./chunk-6AZ7RATD.js";import"./chunk-XXB57DMN.js";import"./chunk-3K4IMMLP.js";import"./chunk-6JUKM6LT.js";import"./chunk-QEZQZG6Z.js";import"./chunk-V6JSMX5A.js";import"./chunk-YLDLDEUP.js";import"./chunk-U56YWPSI.js";import"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";export{b as FlowExecutionStoppedError,a as startEngine};
1
+ import{h as a,i as b}from"./chunk-WOY6GG37.js";import"./chunk-V35SRZAO.js";import"./chunk-Z4CYLB7J.js";import"./chunk-6AZ7RATD.js";import"./chunk-XXB57DMN.js";import"./chunk-3K4IMMLP.js";import"./chunk-P6YUTKRM.js";import"./chunk-KKJW6HJA.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};
@@ -0,0 +1,3 @@
1
+ var g=(a=>(a.START_NODE="startNode",a.CLASSIFIER_NODE="classifierNode",a.MEMO_NODE="memoNode",a.LLM_NODE="llmNode",a.ANSWER_NODE="answerNode",a.API_NODE="apiNode",a.TOOL_NODE="toolNode",a.WORKER_NODE="workerNode",a.CRAWL_NODE="crawlNode",a))(g||{});var D=/^[a-zA-Z][a-zA-Z0-9_]*$/;function m(e){let t=e==null?void 0:e.inputs;if(!Array.isArray(t))return[];let n=[],r=new Set;for(let o of t){let s=typeof(o==null?void 0:o.name)=="string"?o.name.trim():"";if(!s||!D.test(s)||r.has(s))continue;r.add(s);let i=$.includes(o==null?void 0:o.type)?o.type:"string";n.push({name:s,type:i,required:(o==null?void 0:o.required)===!0,default:(o==null?void 0:o.default)??void 0})}return n}function P(e,t){let n=e.label||e.name;switch(e.type){case"number":{let r=typeof t=="number"?t:Number(String(t).trim());return Number.isFinite(r)?{value:r}:{error:`"${n}" must be a number`}}case"boolean":{if(typeof t=="boolean")return{value:t};let r=String(t).trim().toLowerCase();return["true","1","yes","si","s\xED"].includes(r)?{value:!0}:["false","0","no"].includes(r)?{value:!1}:{error:`"${n}" must be true or false`}}case"json":{if(typeof t=="object")return{value:t};try{return{value:JSON.parse(String(t))}}catch{return{error:`"${n}" must be valid JSON`}}}default:return{value:typeof t=="string"?t:String(t)}}}function S(e){return e==null||typeof e=="string"&&e.trim()===""}function Z(e,t){let n={},r=[],o=t??{};for(let s of e){let i=o[s.name],u=S(i)?s.default:i;if(S(u)){s.required&&r.push(`"${s.label||s.name}" is required`);continue}let{value:c,error:a}=P(s,u);a?r.push(a):n[s.name]=c}return{values:n,errors:r}}function k(e){return typeof e=="string"?e:e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function G(e,t,n){let r=t.user_input;if(typeof r=="string"&&r.trim())return r;let o=e.filter(i=>i.name!=="user_input"&&t[i.name]!==void 0).map(i=>`- ${i.label||i.name}: ${k(t[i.name])}`),s=(n==null?void 0:n.trim())||"Automated execution";return o.length>0?`${s}
2
+ ${o.join(`
3
+ `)}`:s}var $=["string","number","boolean","json"];var O=/^[A-Za-z][A-Za-z0-9_]*$/;function N(e){switch(e){case"startNode":return[{name:"user_input",path:"user_input",type:"string"},{name:"images",path:"images",type:"image"},{name:"files",path:"files",type:"file"},{name:"memory",path:"memory",type:"string"}];case"llmNode":return[{name:"output",path:"",type:"string"}];case"apiNode":return[{name:"ok",path:"ok",type:"boolean"},{name:"status",path:"status",type:"number"},{name:"data",path:"data",type:"object"}];case"toolNode":case"workerNode":case"crawlNode":return[{name:"ok",path:"ok",type:"boolean"},{name:"data",path:"data",type:"object"},{name:"error",path:"error",type:"string"}];case"classifierNode":return[{name:"classification",path:"classification",type:"string"},{name:"label",path:"label",type:"string"},{name:"confidence",path:"confidence",type:"number"},{name:"margin",path:"margin",type:"number"},{name:"probabilities",path:"probabilities",type:"object"},{name:"route",path:"route",type:"string"},{name:"checks",path:"checks",type:"object"}];case"memoNode":return[{name:"context",path:"",type:"string"}];default:return[]}}function T(e){return e.type!=="startNode"?[]:m(e.data).map(t=>({name:t.name,path:t.name,type:t.type==="json"?"object":t.type}))}function C(e){var o;let t=[...N(e.type),...T(e),...Array.isArray((o=e.data)==null?void 0:o.outVars)?e.data.outVars:[]],n=new Set,r=[];for(let s of t){let i=typeof(s==null?void 0:s.name)=="string"?s.name.trim():"";O.test(i)?n.has(i)?r.push(`Node ${e.id} has duplicate output name "${i}"`):n.add(i):r.push(`Node ${e.id} has an invalid output name`)}return r}function d(e){var r;let t=[...N(e.type),...T(e)];return[...(Array.isArray((r=e.data)==null?void 0:r.outVars)?e.data.outVars:[]).map(o=>({...o,name:typeof(o==null?void 0:o.name)=="string"?o.name.trim():""})).filter(o=>O.test(o.name)).map(o=>({...o,source:"user"})),...t.map(o=>({...o,source:"default"}))]}function x(e,t){let n=new Set,r=[t],o=new Set([t]);for(;r.length>0;){let s=r.shift();for(let i of e)i.target!==s||o.has(i.source)||(o.add(i.source),n.add(i.source),r.push(i.source))}return n}function L(e,t){var o,s;if(e.type!=="startNode")return t;let n=((o=e.data)==null?void 0:o.allow_images)===!0,r=((s=e.data)==null?void 0:s.allow_documents)===!0;return t.filter(i=>!(i.name==="images"&&!n||i.name==="files"&&!r))}function j(e,t,n){let r=x(t,n),o=[],s=new Set;for(let i of r){let u=e.find(c=>c.id===i);if(u)for(let c of L(u,d(u))){let a=u.type==="startNode"&&c.source==="default"?c.name:`${u.id}.${c.name}`;s.has(a)||(s.add(a),o.push({...c,ref:a,nodeId:u.id}))}}return o}function ae(e,t,n){return new Set(j(e,t,n).map(r=>r.ref))}function v(e,t){let n=x(t.edges,t.currentNodeId);return t.nodes.filter(r=>n.has(r.id)&&e.startsWith(`${r.id}.`)).sort((r,o)=>o.id.length-r.id.length)[0]}function I(e,t){return e.slice(t.length+1)}function ue(e){return e.type==="image"||e.type==="file"}function U(e){if(!e)return!1;let t=e.split(";")[0].trim().toLowerCase();return t==="application/json"||t.endsWith("+json")}function E(e,t){let n=e.trim();if(!n||!(U(t)||n.startsWith("{")||n.startsWith("[")))return e;try{return JSON.parse(n)}catch{return e}}async function le(e){let t=e.headers.get("content-type"),n=await e.text();return E(n,t)}var W=new Set(["__proto__","prototype","constructor"]),_="\0__ORA_OB__\0",h="\0__ORA_CB__\0",l=class extends Error{constructor(n,r){super(r);this.code=n;this.name="VariableResolutionError"}code};function M(e){for(let t of e.split("."))if(W.has(t))throw new l("UNSAFE_PATH",`Unsafe variable path segment "${t}"`)}function w(e,t){if(!t)return e;M(t);let n=e;for(let r of t.split(".")){if(n==null||!Object.prototype.hasOwnProperty.call(Object(n),r))return;n=n[r]}return n}var J=new Set(["apiNode","toolNode","workerNode"]);function X(e){if(e!==null&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"data")){let t=e.data;return typeof t=="string"?E(t):t}}function b(e,t,n){let r=t.path??"";if(t.source==="user"&&n&&J.has(n)){let o=w(X(e),r);if(o!==void 0)return o}return w(e,r)}function Ne(e,t){let n={};for(let r of d(e))n[r.name]=b(t,r,e.type);return n}function q(e,t){var r,o,s,i,u,c,a;if(Object.prototype.hasOwnProperty.call(t.refOverrides??{},e))return{value:t.refOverrides[e]};let n=t.nodes.find(f=>f.type==="startNode");if(e==="user_input")return{value:(r=t.context)==null?void 0:r.user_input};if(e==="memory")return{value:((o=t.context)==null?void 0:o.memory)??""};if(e==="images"&&((s=n==null?void 0:n.data)==null?void 0:s.allow_images)===!0)return{value:(i=t.context)==null?void 0:i.user_images};if(e==="files"&&((u=n==null?void 0:n.data)==null?void 0:u.allow_documents)===!0)return{value:(c=t.context)==null?void 0:c.files};if(n&&m(n.data).some(f=>f.name===e))return{value:(a=t.context)==null?void 0:a[e]}}function V(e,t){var R;let n=e.trim();if(!n)throw new l("INVALID_EXPRESSION","Variable reference is empty");let r=n.includes(".")?void 0:q(n,t);if(r)return r;if(!n.includes("."))throw new l("UNKNOWN_CONTEXT_REF",`Unknown run-context variable "${n}"`);let o=v(n,t);if(!o)throw new l("OUT_OF_SCOPE",`Variable "${n}" is not in this node's connection scope`);let s=I(n,o.id),[i,...u]=s.split("."),c=d(o).find(F=>F.name===i);if(!c)throw new l("UNKNOWN_OUTPUT",`Node "${o.id}" does not expose output "${i}"`);if(Object.prototype.hasOwnProperty.call(t.refOverrides??{},n))return{value:t.refOverrides[n]};let a=(R=t.results)==null?void 0:R[o.id];if(a==null)return{value:void 0,missing:"ancestor_not_executed"};let f=b(a,c,o.type),p=u.length>0?w(f,u.join(".")):f;return p==null?{value:void 0,missing:"path_not_found"}:{value:p}}function Ee(e,t){return V(e,t).value}function K(e){let t=null,n=!1;for(let r=0;r<e.length-1;r+=1){let o=e[r];if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(t){o===t&&(t=null);continue}if(o==='"'||o==="'"){t=o;continue}if(o==="?"&&e[r+1]==="?")return{ref:e.slice(0,r).trim(),rawDefault:e.slice(r+2).trim()}}return{ref:e.trim()}}function B(e){if(e.length<2||!['"',"'"].includes(e[0])||e.at(-1)!==e[0])throw new l("INVALID_EXPRESSION","Template defaults must be quoted string literals");if(e[0]==='"')try{return JSON.parse(e)}catch{throw new l("INVALID_EXPRESSION","Invalid double-quoted template default")}return e.slice(1,-1).replace(/\\'/g,"'").replace(/\\\\/g,"\\")}function A(e){let{ref:t,rawDefault:n}=K(e.trim());if(!t)throw new l("INVALID_EXPRESSION","Template expression is missing a variable reference");return{ref:t,...n===void 0?{}:{defaultValue:B(n)}}}function ye(e){let t=e.replace(/\\\{\{/g,_).replace(/\\\}\}/g,h),n=[],r=/\{\{\s*([^}]+?)\s*\}\}/g;for(let o of t.matchAll(r))n.push(A(o[1]).ref);return n}function z(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _e(e,t,n){let r=z(t);return e.replace(new RegExp(`(\\{\\{\\s*)${r}(?=\\.)`,"g"),`$1${n}`)}function y(e,t){return typeof e=="string"?t?JSON.stringify(e).slice(1,-1):e:typeof e=="object"&&e!==null?t?JSON.stringify(e):JSON.stringify(e,null,2):e!=null?t?JSON.stringify(e):String(e):""}function H(e,t){var n;throw(n=t==null?void 0:t.onError)==null||n.call(t,e.message),e}function he(e,t,n,r){if(!e)return e;let o=(r==null?void 0:r.serializeNonStrings)??!1,s=e.replace(/\\\{\{/g,_).replace(/\\\}\}/g,h),i=/\{\{\s*([^}]+?)\s*\}\}/g;return s=s.replace(i,(u,c)=>{try{let a=A(c);if(a.ref.startsWith("secrets.")){let p=a.ref.slice(8);if(!Object.prototype.hasOwnProperty.call(n.secrets??{},p))throw new l("MISSING_SECRET",`Secret "${p}" is not defined for this tenant`);return y(n.secrets[p],o)}let f=V(a.ref,n);if(f.missing){if(a.defaultValue!==void 0)return y(a.defaultValue,o);let p=f.missing==="ancestor_not_executed"?`Ancestor for variable "${a.ref}" did not execute in this branch`:`Variable path "${a.ref}" did not produce a value`;throw new l(f.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",p)}return y(f.value,o)}catch(a){if(a instanceof l)return H(a,r);throw a}}),s.split(_).join("{{").split(h).join("}}")}export{g as a,D as b,m as c,Z as d,G as e,O as f,N as g,C as h,d as i,x as j,j as k,ae as l,v as m,I as n,ue as o,U as p,E as q,le as r,l as s,w as t,b as u,Ne as v,V as w,Ee as x,A as y,ye as z,_e as A,he as B};
@@ -0,0 +1,10 @@
1
+ var Ne={USER_MESSAGE:"M",USER_CLEAR_HISTORY:"CH",USER_AUTH:"AUT",USER_IDENTITY:"UID",SERVER_EVENT:"SE",SERVER_HISTORY:"HIS",SERVER_ERROR:"ERR",SERVER_STEP:"STEP",SERVER_TEXT_STREAM:"TS",SERVER_TEXT_STREAM_COMPLETE:"TSC",SERVER_REASONING_STREAM:"RS",SERVER_REASONING_STREAM_COMPLETE:"RSC",SERVER_CONFIG:"CFG"};function Le(e){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t}catch{}return{text:e}}var fe=256;function Ue(e){if(typeof e!="string")return null;let t=e.trim();return t?t.slice(0,fe):null}function $e(e){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.name=="string"&&typeof t.value=="string"){let r=t.name.trim();return/^[A-Z][A-Z0-9_]*$/.test(r)?{name:r,value:t.value}:null}}catch{}return null}var v={"clef-omni":{id:"@cf/cloudflare/clef-omni",contextWindow:65529,pricePerMillionInputTokens:.15},clef:{id:"@cf/cloudflare/clef",contextWindow:65536,pricePerMillionInputTokens:.24},"clef-flash":{id:"@cf/cloudflare/clef-flash",contextWindow:24576,pricePerMillionInputTokens:.038}},De={model:"clef-omni",question:"",options:[{id:"option",label:"",criteria:""},{id:"option_2",label:"",criteria:""}],checks:[],input:{message:"user_input",historyTurns:3,vars:[]},confidence:{threshold:.6,margin:.15}},X={uncertain:"source-__uncertain",blocked:"source-__blocked",error:"source-__error"};function We(e,t){return e==="class"&&t!==void 0?`source-${t}`:Object.hasOwn(X,e)?X[e]:`source-${e}`}var M=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),O=e=>typeof e=="string"&&e.trim().length>0,K=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1;function Q(e){if(!M(e))return["Classifier data must be an object"];if(Object.hasOwn(e,"items")||Object.hasOwn(e,"classes")||Object.hasOwn(e,"instructions")||Object.hasOwn(e,"questions"))return["Classifier uses the old format: use question and options[].criteria"];let t=[];(typeof e.model!="string"||!Object.hasOwn(v,e.model))&&t.push("Classifier model is invalid"),(!O(e.question)||e.question.length>300)&&t.push("Classifier question is required and must be at most 300 characters"),(!M(e.input)||!O(e.input.message)||!Number.isInteger(e.input.historyTurns)||e.input.historyTurns<0||e.input.historyTurns>10||!Array.isArray(e.input.vars)||!e.input.vars.every(O))&&t.push("Classifier input requires message, historyTurns (0\u201310), and variable refs"),(!M(e.confidence)||!K(e.confidence.threshold)||!K(e.confidence.margin))&&t.push("Classifier confidence threshold and margin must be between 0 and 1"),(!Array.isArray(e.options)||e.options.length<2||e.options.length>255)&&t.push("Classifier requires 2\u2013255 options"),(!Array.isArray(e.checks)||e.checks.length>63)&&t.push("Classifier supports at most 63 checks");let r=new Set,i=(n,s)=>{typeof n!="string"||!/^[A-Za-z0-9_.-]{1,100}$/.test(n)||n.startsWith("__")?t.push("Classifier ids must use [A-Za-z0-9_.-], 1\u2013100 characters, without __ prefix"):r.has(n)||s&&n==="route"?t.push(`Classifier duplicate or reserved id: ${n}`):r.add(n)};for(let n of Array.isArray(e.options)?e.options:[]){if(!M(n)){t.push("Classifier option must be an object");continue}i(n.id,!1),Object.hasOwn(n,"description")&&t.push("Classifier option uses criteria instead of description"),(!O(n.label)||!O(n.criteria))&&t.push("Classifier option requires label and criteria")}for(let n of Array.isArray(e.checks)?e.checks:[]){if(!M(n)){t.push("Classifier check must be an object");continue}i(n.id,!0),O(n.instructions)||t.push("Classifier check instructions are required"),n.type==="noul"?(n.guard!==void 0&&(!M(n.guard)||!K(n.guard.threshold))&&t.push("Classifier guard threshold must be between 0 and 1"),n.criteria!==void 0&&(!M(n.criteria)||!Object.values(n.criteria).every(s=>typeof s=="string")||Object.keys(n.criteria).some(s=>s!=="true"&&s!=="false"))&&t.push("Classifier noul criteria are invalid")):n.type==="score"?((!Array.isArray(n.levels)||n.levels.length<2||n.levels.length>10||!n.levels.every(O))&&t.push("Classifier score requires 2\u201310 levels"),n.guard!==void 0&&t.push("Classifier guard is only supported for noul")):t.push("Classifier check type must be noul or score")}return t}var me={short:100,medium:250,long:1e3},pe={short:2e3,medium:5e3,long:2e4},H="medium",de="gpt_5_nano",ee=4;function ge(e){return e==="short"||e==="medium"||e==="long"?e:H}function ye(e=H){return pe[e]}function Be(e=H){return me[e]}function he(e){return e?Math.ceil(e.length/ee):0}function be(e,t){if(!e)return{content:"",truncated:!1};if(he(e)<=t)return{content:e,truncated:!1};let r=Math.max(0,t*ee);return{content:e.slice(0,r),truncated:!0}}function Je(e){let t=e==null?void 0:e.memory_enabled;return t===!0||t==="true"||t===1}function ze(e){let t=e==null?void 0:e.memory_model;return typeof t=="string"&&t.trim()?t.trim():de}function Ve(e){return ge(e==null?void 0:e.memory_length)}function qe(e,t){let r=ye(e);return t&&t!=="none"?r+2048:r}var te=/^(user|assistant|usuario|asistente|u|a)\s*:/i,xe=/^(hola|hello|hi|hey|buenas|buen[oa]s?\s+d[ií]as?|qu[eé]\s+tal|qu[eé]\s+haces)[\s,.!¡¿?]*$/i;function we(e){let t=e.split(`
2
+ `).map(i=>i.replace(/^[-*]\s*/,"").trim()).filter(Boolean);if(t.length<2)return!1;let r=t.filter(i=>te.test(i));return r.length>=2&&r.length>=Math.ceil(t.length/2)}function Ee(e){let t=e.split(`
3
+ `).map(r=>r.trim()).filter(Boolean).filter(r=>r!=="(empty)"&&r!=="(none)").filter(r=>!te.test(r.replace(/^[-*]\s*/,"")));return we(t.join(`
4
+ `))?"":t.join(`
5
+ `)}function Ye(e){let t=e.trim();if(!t||xe.test(t))return[];let r=[],i=t.match(/(?:me llamo|soy|i['’]m|i am|my name is)\s+([A-Za-zÁÉÍÓÚÜáéíóúüñÑ][\wÁÉÍÓÚÜáéíóúüñÑ'-]{1,40})/i);i&&r.push(`Name: ${i[1]}`);let n=t.match(/me gusta[n]?\s+([^,.!?]+)/i);if(n&&r.push(`Likes: ${n[1].trim()}`),/[?¿]/.test(t)||/^(pregunt|dime\b|cu[eé]nt)/i.test(t))return r;let l=t.replace(/^(hola|hey|hi)[,\s]+/i,"").replace(/(?:me llamo|soy)\s+[A-Za-zÁÉÍÓÚÜáéíóúüñÑ][\wÁÉÍÓÚÜáéíóúüñÑ'-]*/gi,"").replace(/me gusta[n]?\s+[^,.!?]+/gi,"").replace(/[,.\s]+/g," ").trim();return l.length>=16&&r.push(l.slice(0,140)),r}function Ze(e,t,r){let n=[...Ee(e).split(`
6
+ `).map(s=>s.replace(/^[-*]\s*/,"").trim()).filter(Boolean)];for(let s of t){let l=s.replace(/^[-*]\s*/,"").trim();l&&(n.some(a=>a.toLowerCase()===l.toLowerCase())||n.push(l))}return n.length===0?"":be(n.map(s=>`- ${s}`).join(`
7
+ `),r).content}var C={source:"all",limit:5,depth:2,render:!1,format:"markdown",includeSubdomains:!1,waitTimeoutMs:6e4,maxAgeS:86400,maxCharsPerPage:4e3},A={limit:50,depth:10,waitTimeoutMs:12e4,maxAgeS:604800,maxOutputBytes:256*1024};function U(e,t,r,i=0){return Math.min(r,Math.max(i,Math.floor(typeof e=="number"&&Number.isFinite(e)?e:t)))}function Ce(e,t,r){let i=new URL(t);if(i.protocol!=="http:"&&i.protocol!=="https:")throw new Error("Crawl URL must use http(s)");let n=e.format??C.format;return{url:i.href,source:e.source??C.source,limit:U(e.limit,C.limit,A.limit,1),depth:U(e.depth,C.depth,A.depth),render:e.render??C.render,formats:[n],...n==="json"?{jsonOptions:{...e.jsonPrompt!==void 0?{prompt:e.jsonPrompt}:{},...e.jsonSchema!==void 0?{response_format:e.jsonSchema}:{}}}:{},maxAge:U((r==null?void 0:r.maxAgeOverrideS)??e.maxAgeS,C.maxAgeS,A.maxAgeS),options:{includeExternalLinks:!1,includeSubdomains:e.includeSubdomains??C.includeSubdomains,includePatterns:e.includePatterns??[],excludePatterns:e.excludePatterns??[]}}}function B(e){return Array.isArray(e)?e.map(B):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,B(r)])):e}async function Qe(e){let t=new TextEncoder().encode(JSON.stringify(B(e))),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r),i=>i.toString(16).padStart(2,"0")).join("")}function Re(e,t){let r=t.split(/(\*\*|\*)/).map(i=>i==="**"?".*":i==="*"?"[^/]*":i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("");return new RegExp(`^${r}$`).test(e)}function ne(e,t,r){let i=(t==null?void 0:t.mode)??"pages",n=(t==null?void 0:t.fields)??["url","title",r],s=U(t==null?void 0:t.maxCharsPerPage,C.maxCharsPerPage,A.maxOutputBytes),l=e;if(i==="single"){let o=t==null?void 0:t.select,u=(o==null?void 0:o.url)!==void 0?e.find(m=>m.url===o.url):(o==null?void 0:o.pattern)!==void 0?e.find(m=>Re(m.url,o.pattern)):e[(o==null?void 0:o.index)??0];l=u?[u]:[]}let a=!1,c=l.map(o=>{let u={url:o.url,status:o.status};o.httpStatus!==void 0&&(u.httpStatus=o.httpStatus),n.includes("title")&&o.title!==void 0&&(u.title=o.title);let m=o.truncated??!1;if(n.includes("markdown")&&o.markdown!==void 0&&(u.markdown=o.markdown.slice(0,s),m||=u.markdown.length<o.markdown.length),n.includes("json")&&o.json!==void 0){let p=o.truncated&&typeof o.json=="string"?o.json:JSON.stringify(o.json);u.json=p.length>s?p.slice(0,s):o.json,m||=p.length>s}return m&&(u.truncated=!0),a||=m,u});if(i!=="concat")return{pages:c,truncated:a};let f=c.map(o=>n.map(u=>{let m=o[u];return m===void 0?"":typeof m=="string"?m:JSON.stringify(m)}).filter(Boolean).join(`
8
+ `)).join(`
9
+
10
+ `);return{pages:[],text:f,truncated:a}}var re=e=>new TextEncoder().encode(JSON.stringify(e)).byteLength;async function et(e,t,r){var R,S,q;let i=Date.now(),n=i+U(t.waitTimeoutMs,C.waitTimeoutMs,A.waitTimeoutMs),s=r.fetchImpl??fetch,l=r.sleep??(y=>new Promise(E=>setTimeout(E,y))),a=r.resumeJobId??null,c={status:"running"},f=[],o=!1,u=2,m=()=>Math.max(0,n-Date.now()),p=async y=>{if(!m())throw new Error("timeout");if(await l(Math.min(y,m())),!m())throw new Error("timeout")},w=async(y,E)=>{var P,x,d,T,h;for(let k=0;;k++){if(!m())throw new Error("timeout");let g=new AbortController,I,L=new Promise((b,N)=>{I=setTimeout(()=>{g.abort(),N(new Error("timeout"))},m())});try{let b=await Promise.race([s(y,{...E,signal:g.signal,headers:{Authorization:`Bearer ${e.apiToken}`,"Content-Type":"application/json"}}),L]);if(b.status===429&&k<2){let F=b.headers.get("Retry-After"),Y=F===null?NaN:Number(F),Z=Number.isFinite(Y)?Math.max(0,Y*1e3):F?Math.max(0,Date.parse(F)-Date.now()):2e3;await((P=b.body)==null?void 0:P.cancel()),clearTimeout(I),await p(Number.isFinite(Z)?Z:2e3);continue}let N=await Promise.race([b.json(),L]);if(N.success===!1)throw new Error(((d=(x=N.errors)==null?void 0:x[0])==null?void 0:d.message)??"Crawl API error");if(!b.ok)throw new Error(((h=(T=N.errors)==null?void 0:T[0])==null?void 0:h.message)??`Crawl API HTTP ${b.status}`);if(!m())throw new Error("timeout");return N}catch(b){throw g.signal.aborted||!m()?new Error("timeout"):b}finally{clearTimeout(I)}}},$=(y,E)=>{let P=()=>ne(f.filter(T=>T.status==="completed"),t.output,t.format??"markdown"),x=P(),d={ok:y,error:E,data:a?{jobId:a,status:E==="timeout"?"running":c.status,total:c.total??0,finished:c.finished??0,browserSeconds:c.browserSecondsUsed??0,elapsedMs:Date.now()-i,...x,truncated:o||x.truncated}:null};for(;re(d)>A.maxOutputBytes&&f.length;)f.pop(),x=P(),Object.assign(d.data,x,{truncated:!0});return{result:d,allPages:f}};try{if(!e.accountId||!e.apiToken)throw new Error("Crawl no configurado: faltan CF_ACCOUNT_ID / CF_BROWSER_RUN_TOKEN");let y=Ce(t,r.url,r),E=`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(e.accountId)}/browser-run/crawl`;if(!a){let h=await w(E,{method:"POST",body:JSON.stringify(y)});if(typeof h.result!="string"||!h.result)throw new Error("Crawl API returned no jobId");a=h.result}let P=`${E}/${encodeURIComponent(a)}`,x=2e3;do{let h=await w(`${P}?limit=1`);if(!h.result||typeof h.result!="object"||!h.result.status)throw new Error("Crawl API returned no status");if(c=h.result,c.status!=="running")break;await p(x),x=Math.min(5e3,x+1e3)}while(m());let d,T=new Set;do{let h=d===void 0?"":`?cursor=${encodeURIComponent(d)}`,k=await w(`${P}${h}`);if(!k.result||typeof k.result!="object")throw new Error("Crawl API returned invalid results");c={...c,...k.result};for(let g of k.result.records??[]){let I={url:g.url,status:g.status,...((R=g.metadata)==null?void 0:R.title)!==void 0?{title:g.metadata.title}:{},...((S=g.metadata)==null?void 0:S.status)!==void 0?{httpStatus:g.metadata.status}:{},...g.markdown!==void 0?{markdown:g.markdown}:{},...g.json!==void 0?{json:g.json}:{}},L=ne([I],{mode:"pages",maxCharsPerPage:(q=t.output)==null?void 0:q.maxCharsPerPage},t.format??"markdown").pages[0],b=re(L)+1;if(u+b>A.maxOutputBytes){o=!0;break}f.push(L),u+=b}if(o)break;if(d=k.result.cursor,d!=null&&d!==""){if(T.has(String(d)))throw new Error("Crawl API repeated pagination cursor");T.add(String(d))}else d=void 0}while(d!==void 0);return $(c.status==="completed",c.status==="completed"?null:c.status)}catch(y){return $(!1,y instanceof Error?y.message:String(y))}}function se(e,t){let r=JSON.stringify(e).slice(1,-1),i=new TextEncoder,n=[...r.matchAll(/([A-Za-z\u00C0-\u024F]+)(\s*)/g)].filter(f=>f[1].length>=3&&f[2].length>0).map(f=>({start:f.index,end:f.index+f[0].length,bytes:i.encode(f[0]).length})),s=[{end:0,encodedEnd:0,bytes:0}];for(let f of e){let o=s[s.length-1],u=JSON.stringify(f).slice(1,-1);s.push({end:o.end+f.length,encodedEnd:o.encodedEnd+u.length,bytes:o.bytes+i.encode(u).length})}let l=[],a=0,c=0;for(let f=0;f<s.length;f++){let o=s[f];for(;a<n.length&&n[a].end<=o.encodedEnd;)c+=n[a++].bytes;let u=n[a];u&&u.start<o.encodedEnd&&o.encodedEnd<u.end||l.push({index:f,hundredths:o.bytes*93-c*(93-(t==="clef-omni"?23:20))})}return{boundaries:s,cuts:l}}var J=Symbol("clefTruncationWarning");function it(e,t){let r=Q(e);if(r.length)throw new Error(r.join("; "));let i={model:e.model,state:{message:t.message,history:t.history.map(n=>({role:n.role,text:n.text})),vars:Object.fromEntries(Object.entries(t.vars))},questions:Object.fromEntries([["route",{type:"choice",instructions:e.question,criteria:Object.fromEntries(e.options.map(n=>[n.id,n.criteria]))}],...e.checks.map(n=>[n.id,n.type==="score"?{type:n.type,instructions:n.instructions,criteria:n.levels}:{type:n.type,instructions:n.instructions,...n.criteria?{criteria:n.criteria}:{}}])])};return ae(i,Math.floor(v[e.model].contextWindow*.9))}function ae(e,t){e.state={message:e.state.message,history:e.state.history.slice(),vars:Object.fromEntries(Object.entries(e.state.vars))};let r=_(e);if(r<=t)return e;let i={...e,state:{message:"",history:[],vars:{}}};if(_(i)>t)throw new Error("Classifier questions exceed the Clef context budget");let n=()=>_(e)<=t,s=0,l=0,a=!1,c=e.state.history;if(c.length){let u=0,m=c.length;for(;u<m;){let p=Math.floor((u+m)/2);e.state.history=c.slice(p),n()?m=p:u=p+1}s=u,e.state.history=c.slice(s)}let f=Object.entries(e.state.vars).sort((u,m)=>(JSON.stringify(m[1])??"").length-(JSON.stringify(u[1])??"").length);for(let[u,m]of f){if(n())break;l++,typeof m=="string"?(e.state.vars[u]="",n()?e.state.vars[u]=oe(m,e.model,t,_(e)):delete e.state.vars[u]):delete e.state.vars[u]}if(!n()){let u=e.state.message;e.state.message="",e.state.message=oe(u,e.model,t,_(e)),a=e.state.message!==u}if(!n())throw new Error("Classifier request exceeds the Clef context budget");let o=`Classifier: context trimmed for ${e.model} (${v[e.model].contextWindow} token limit, budget ${t}); history removed: ${s}; vars shortened/removed: ${l}; message tail shortened: ${a}; estimated tokens ${r} -> ${_(e)}`;return ue(e,o),e}function oe(e,t,r,i){let{boundaries:n,cuts:s}=se(e,t),l=u=>i+Math.ceil(u/100)<=r,a=0,c=s.length-1;for(;a<c;){let u=Math.ceil((a+c)/2);l(s[u].hundredths)?a=u:c=u-1}let f=s[a],o=f.index;if(a+1<s.length){let u=f.index,m=s[a+1].index-1;for(;u<m;){let p=Math.ceil((u+m)/2),w=f.hundredths+(n[p].bytes-n[f.index].bytes)*93;l(w)?u=p:m=p-1}o=u}return e.slice(0,n[o].end)}function _(e){let t=JSON.stringify({model:e.model,state:e.state,questions:e.questions}),r=new TextEncoder,i=r.encode(t).length,n=0;for(let a of t.matchAll(/([A-Za-z\u00C0-\u024F]+)(\s*)/g))a[1].length>=3&&a[2].length>0&&(n+=r.encode(a[0]).length);let s=Object.values(e.questions),l=0;for(let a of s)Array.isArray(a==null?void 0:a.criteria)?l+=a.criteria.length:a!=null&&a.criteria&&typeof a.criteria=="object"&&(l+=Object.keys(a.criteria).length);return Math.ceil(n*(e.model==="clef-omni"?.23:.2)+(i-n)*.93+s.length*45+l*11)+256}function ue(e,t){Object.defineProperty(e,J,{value:[e[J],t].filter(Boolean).join("; "),configurable:!0})}function Pe(e){var s;let t=e&&typeof e=="object"?e:void 0,r=typeof(t==null?void 0:t.message)=="string"?t.message:typeof e=="string"?e:"",i=Number((t==null?void 0:t.code)??((s=r.match(/code[\s:="']*(3030|5021)\b/i))==null?void 0:s[1])),n=r.match(/Request requires (\d+) tokens; the maximum is (\d+)/i)??r.match(/tokens\s*\((\d+)\).*context window limit\s*\((\d+)\)/i);if(!(i!==5021&&!(i===3030&&n))){if(n){let l=Number(n[1]),a=Number(n[2]);if(Number.isFinite(l)&&Number.isFinite(a)&&l>a&&a>0)return a/l}return i===5021?.5:void 0}}function at(e){return e[J]}async function ut(e,t,r,{timeoutMs:i=3e4}={}){if(!Number.isFinite(i)||i<=0)throw new Error("Invalid Clef timeout");let n,s=new AbortController,l=()=>e.run(v[t].id,{model:r.model,state:r.state,questions:r.questions},{signal:s.signal}),a=async()=>{try{return await l()}catch(c){let f=Pe(c);if(f===void 0||s.signal.aborted)throw c;let o=Math.floor(Math.min(v[t].contextWindow*.9,_(r)*f*.9));if(ue(r,`Classifier: context retry 1/1; scaled budget ${o}`),ae(r,o),s.signal.aborted)throw new Error("Clef timeout");return await l()}};try{return await Promise.race([a(),new Promise((c,f)=>{n=setTimeout(()=>{f(new Error("Clef timeout")),s.abort()},i)})])}finally{n!==void 0&&clearTimeout(n)}}function j(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Clef response object");return e}function D(e){if(typeof e!="number"||!Number.isFinite(e)||e<0||e>1)throw new Error("Invalid Clef probability");return e}function ie(e,t){let r=j(e);if(Object.keys(r).length!==t.length||t.some(s=>!Object.hasOwn(r,s)))throw new Error("Invalid Clef probability options");let i=Object.fromEntries(t.map(s=>[s,D(r[s])])),n=Object.values(i).reduce((s,l)=>s+l,0);if(Math.abs(n-1)>.02)throw new Error("Invalid Clef probability sum");return i}function ct(e,t){let r=j(e),i=j(r.answers),n=j(i.route);if(n.type!=="choice"||typeof n.choice!="string"||!t.options.some(o=>o.id===n.choice))throw new Error("Invalid Clef route choice");let s=ie(n.probabilities,t.options.map(o=>o.id)),l=Object.values(s).sort((o,u)=>u-o);if(s[n.choice]!==l[0])throw new Error("Clef choice is not the highest probability");let a={classification:n.choice,label:t.options.find(o=>o.id===n.choice).label,confidence:D(n.confidence),margin:l[0]-l[1],probabilities:s,route:"class",checks:Object.fromEntries(t.checks.map(o=>{if(!Object.hasOwn(i,o.id))throw new Error(`Missing Clef answer: ${o.id}`);let u=j(i[o.id]);if(u.type!==o.type)throw new Error(`Invalid Clef answer type: ${o.id}`);if(o.type==="noul")return[o.id,D(u.noul)];let m=j(u.legend),p=o.levels.map((R,S)=>String(S));if(p.some(R=>typeof m[R]!="string"))throw new Error("Invalid Clef score legend");let w=ie(u.probabilities,p);if(typeof u.score!="number"||!Number.isFinite(u.score)||u.score<0||u.score>o.levels.length-1)throw new Error("Invalid Clef score");let $=p.reduce((R,S)=>w[R]>=w[S]?R:S);return[o.id,{score:u.score,level:o.levels[Number($)],confidence:D(u.confidence),probabilities:w}]}))};t.checks.some(o=>o.type==="noul"&&o.guard&&Number(a.checks[o.id])>o.guard.threshold)?a.route="blocked":(a.confidence<t.confidence.threshold||a.margin<t.confidence.margin)&&(a.route="uncertain");let f=j(r.usage).input_tokens;if(typeof f!="number"||!Number.isInteger(f)||f<0)throw new Error("Invalid Clef input usage");return{result:a,usage:{promptTokens:f,completionTokens:0,totalTokens:f}}}function lt(){return{classification:"",label:"",confidence:0,margin:0,probabilities:{},route:"error",checks:{}}}function ft(e,t,r){var l,a;let i=e.filter(c=>c.type==="text"&&typeof c.content=="string"&&(c.role==="user"||c.role==="assistant"));((l=i.at(-1))==null?void 0:l.role)==="user"&&((a=i.at(-1))==null?void 0:a.content)===r&&i.pop();let n=i.length,s=0;for(let c=i.length-1;c>=0&&t>0&&!(i[c].role==="user"&&(n=c,++s===t));c--);return i.slice(n).map(c=>({role:c.role,text:c.content}))}var ke=[{id:"convertTempMessure",label:"Convert Temperature",description:"Convert temperature between Celsius, Fahrenheit, and Kelvin with optional static parameters"},{id:"tempTool",label:"Temp Tool",description:"Temporary demo tool"},{id:"twitter",label:"Twitter",description:"Twitter API for user info, tweets, mentions, replies, advanced search, and trends"},{id:"vectorize",label:"Vectorize",description:"Perform a semantic vector search. Returns relevant matches with scores and metadata."}],pt=ke.reduce((e,t)=>(e[t.id]=t,e),{});var V=["temperature","topP","topK","frequencyPenalty","presencePenalty","maxOutputTokens","seed","stopSequences","maxRetries"],ce=["temperature","topP","topK","frequencyPenalty","presencePenalty"],le={precise:{temperature:.3,topP:.9,topK:30},balanced:{temperature:.8,topP:1,topK:50},creative:{temperature:1.1,topP:.95,topK:80}},Se=1e-6,z={temperature:{min:0,max:2,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:{min:-2,max:2,step:.1},presencePenalty:{min:-2,max:2,step:.1},maxOutputTokens:{max:128e3},seed:!0,stopSequences:{max:4}};function Te(e){return/^gpt-5/i.test(e)}function W(e){let t=e.contextWindow??128e3;return e.provider==="openai"?Te(e.providerModel)?{temperature:!1,topP:!1,topK:{min:1,max:500,step:1},frequencyPenalty:{min:-2,max:2,step:.1},presencePenalty:{min:-2,max:2,step:.1},maxOutputTokens:{max:t},seed:!0,stopSequences:{max:4}}:{...z,maxOutputTokens:{max:t}}:e.provider==="xai"?{...z,maxOutputTokens:{max:t},seed:!0}:e.provider==="anthropic"?{temperature:{min:0,max:1,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:!1,presencePenalty:!1,maxOutputTokens:{max:t},seed:!1,stopSequences:{max:4}}:e.provider==="openrouter"?{temperature:{min:0,max:2,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:{min:-2,max:2,step:.1},presencePenalty:{min:-2,max:2,step:.1},maxOutputTokens:{max:t},seed:!0,stopSequences:{max:4}}:e.provider==="workersai"||e.provider==="cloudflare"?{temperature:{min:0,max:2,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:!1,presencePenalty:!1,maxOutputTokens:{max:t},seed:!1,stopSequences:{max:4}}:{...z,maxOutputTokens:{max:t}}}function G(e,t){if(e==="maxRetries")return!0;let r=t[e];return r===!1?!1:e==="seed"?r===!0:r!==void 0}function ve(e,t,r){return Math.min(r,Math.max(t,e))}function Me(e,t){return e===void 0&&t===void 0?!0:e===void 0||t===void 0?!1:Math.abs(e-t)<Se}function gt(e,t){for(let r of["precise","balanced","creative"]){let i=le[r],n=!0;for(let s of ce){if(t&&!G(s,t))continue;let l=i[s],a=e[s];if(l!==void 0){if(typeof l=="number"&&typeof a=="number"){if(!Me(a,l)){n=!1;break}}else if(a!==l){n=!1;break}}}if(n)return r}return"custom"}function yt(e,t){let r=le[e],i={};for(let n of ce){if(t&&!G(n,t))continue;let s=r[n];s!==void 0&&(i[n]=s)}return i}function ht(e){if(!e)return{};let t={};for(let r of V){let i=e[r];i!==void 0&&(r==="stopSequences"?Array.isArray(i)&&(t.stopSequences=i.filter(n=>typeof n=="string")):r==="maxRetries"?typeof i=="number"&&(t.maxRetries=i):typeof i=="number"&&(t[r]=i))}return t}function bt(e,t,r){var l;let i={...e,...t},n=[],s={};for(let a of V){let c=i[a];if(c===void 0)continue;if(a==="maxRetries"){s.maxRetries=c;continue}if(!G(a,r)){n.push({key:a,action:"stripped",detail:"unsupported by model"});continue}if(a==="stopSequences"){let o=c,u=((l=r.stopSequences)==null?void 0:l.max)??o.length;o.length>u?(s.stopSequences=o.slice(0,u),n.push({key:a,action:"clamped",detail:`truncated to ${u} sequences`})):s.stopSequences=o;continue}if(a==="seed"){s.seed=c;continue}let f=r[a];if(f&&typeof f=="object"&&"min"in f){let o=c,u=ve(o,f.min,f.max);s[a]=u,u!==o&&n.push({key:a,action:"clamped",detail:`clamped from ${o} to ${u}`})}else if(a==="maxOutputTokens"){let o=c,u=r.maxOutputTokens.max,m=Math.min(o,u);s.maxOutputTokens=m,m!==o&&n.push({key:a,action:"clamped",detail:`clamped from ${o} to ${m}`})}}return{effectiveParams:s,adjustments:n}}function xt(e){let t={};return e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.maxOutputTokens!==void 0&&(t.maxOutputTokens=e.maxOutputTokens),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.maxRetries!==void 0&&(t.maxRetries=e.maxRetries),t}function wt(e=128e3){return W({provider:"openai",providerModel:"gpt-4.1",contextWindow:e})}function Et(e=2e6){return W({provider:"openai",providerModel:"gpt-5-nano",contextWindow:e})}function Ct(e=256e3){return W({provider:"xai",providerModel:"grok-4-fast",contextWindow:e})}function Rt(e=128e3){return W({provider:"cloudflare",providerModel:"@cf/meta/llama-3.2-3b-instruct",contextWindow:e})}function Pt(e,t){let r={...e};for(let i of V)i==="maxRetries"||r[i]===void 0||G(i,t)||delete r[i];return r}var Oe=["none","minimal","low","medium","high","xhigh"],Ae=e=>typeof e=="string"&&Oe.includes(e);function St(e){var r;let t=(r=e.capabilities)==null?void 0:r.reasoning;return t&&typeof t=="object"?t:t?{kind:"effort"}:{kind:"none"}}function _e(e){return e.kind!=="effort"?[]:e.levels??[]}var je=e=>e===!0||e==="true";function Tt(e){return e.kind==="tag"?!0:e.kind==="effort"?je(e.exposesReasoning):!1}function vt(e,t){if(e.kind!=="effort")return;let r=_e(e);if(Ae(t)&&r.includes(t))return t;if(e.defaultLevel&&r.includes(e.defaultLevel))return e.defaultLevel}function Mt(e,t){let{effort:r,exposeReasoning:i,maxTokens:n}=t;if(e==="openai"){let s={};return r&&(s.reasoningEffort=r),i&&(s.reasoningSummary="auto"),Object.keys(s).length?{openai:s}:void 0}if(e==="xai")return r?{xai:{reasoningEffort:r}}:void 0;if(e==="openrouter"){if(!n&&!r)return;let s={};return i!==void 0&&(s.exclude=!i),n?{openrouter:{reasoning:{...s,max_tokens:n}}}:{openrouter:{reasoning:{...s,effort:r}}}}if(e==="anthropic"){let s={};return(r||i)&&(s.thinking={type:"adaptive",...i?{display:"summarized"}:{}}),r&&(s.effort=r),Object.keys(s).length?{anthropic:s}:void 0}}export{Ne as a,Le as b,fe as c,Ue as d,$e as e,v as f,De as g,X as h,We as i,Q as j,me as k,pe as l,H as m,de as n,ge as o,ye as p,Be as q,he as r,be as s,Je as t,ze as u,Ve as v,qe as w,we as x,Ee as y,Ye as z,Ze as A,C as B,A as C,Ce as D,Qe as E,ne as F,et as G,it as H,_ as I,at as J,ut as K,ct as L,lt as M,ft as N,pt as O,V as P,ce as Q,le as R,W as S,gt as T,yt as U,ht as V,bt as W,xt as X,wt as Y,Et as Z,Ct as _,Rt as $,Pt as aa,Oe as ba,St as ca,_e as da,Tt as ea,vt as fa,Mt as ga};
@@ -0,0 +1 @@
1
+ var p={};function n(o){}var t={};function d(o,r){let e=Object.hasOwn(t,o)?t[o]:void 0;return e===void 0||!!r&&e.includes(r)}export{p as a,n as b,t as c,d};
@@ -0,0 +1,12 @@
1
+ import{a as Jt}from"./chunk-V35SRZAO.js";import{a as K,b as G,c as Xt,d as ot}from"./chunk-Z4CYLB7J.js";import{a as ao}from"./chunk-6AZ7RATD.js";import{a as Vt,b as Lt,d as Wt,g as Ht,i as rt}from"./chunk-XXB57DMN.js";import{a as lo,b as co}from"./chunk-3K4IMMLP.js";import{D as qt,E as Kt,G as Bt,H as zt,I as Gt,J as st,K as Yt,L as Zt,M as Qt,N as Et,O as St,S as vt,V as to,W as oo,X as eo,a as B,b as It,ca as io,ea as ro,fa as so,ga as no,i as v,j as _t,p as kt,s as Dt,t as Ct,v as Mt}from"./chunk-P6YUTKRM.js";import{B as Ut,c as S,d as Ot,h as bt,i as Pt,k as Z,r as jt,s as P,v as Q,w as H}from"./chunk-KKJW6HJA.js";import{a as $t,b as At,d as Ft}from"./chunk-YLDLDEUP.js";import{a as tt}from"./chunk-YHXUBVN2.js";import{a as E}from"./chunk-3TXHFKDN.js";async function uo(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 r=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(!r.ok)return console.error(`extractDocuments: ${t.name} failed ${r.status}`),{name:t.name,text:""};let g=await r.json();return{name:t.name,text:g.text||""}}catch(r){return console.error(`extractDocuments: ${t.name} threw`,r),{name:t.name,text:""}}})):[]}function _o(e,o,i){var t,r,g,c;return Z(((r=(t=i.flowData)==null?void 0:t.state)==null?void 0:r.nodes)??[],((c=(g=i.flowData)==null?void 0:g.state)==null?void 0:c.edges)??[],o.id).some(n=>n.ref===e&&(n.type==="image"||n.type==="file"))}function ko(e,o){var c,n,m,d,u,y,a;let i=Array.isArray((c=e.data)==null?void 0:c.outputMapping)?e.data.outputMapping:[];if(i.length===0)return null;let t=((m=(n=o.flowData)==null?void 0:n.state)==null?void 0:m.nodes)||[],r={},g=new Set;for(let f of i){let s=(d=f.key)==null?void 0:d.trim(),h=(u=f.from)==null?void 0:u.trim();if(!s||!h)throw new Error(`Answer node ${e.id} has an incomplete variable mapping`);if(g.has(s))throw new Error(`Answer node ${e.id} has duplicate output key "${s}"`);if(_o(h,e,o))throw new Error(`Answer node ${e.id} cannot persist binary source "${h}"`);let p=H(h,{context:o.context||{},results:o.results||{},nodes:t,edges:((a=(y=o.flowData)==null?void 0:y.state)==null?void 0:a.edges)??[],currentNodeId:e.id}),l=p.value;if(p.missing||l===void 0||l===null){if(f.default===void 0)throw new P(p.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Answer node ${e.id} could not resolve output "${h}"`);l=f.default}r[s]=l,g.add(s)}try{JSON.stringify(r)}catch{throw new Error(`Answer node ${e.id} produced a value that is not JSON serializable`)}return r}async function nt(e,o,i,t,r,g,c){var m,d,u;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n;try{n=ko(o,i)}catch(y){throw t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(y)}}),y}n&&e.outputCollector&&e.outputCollector.add(o.id,n);try{let y=await((m=e.getMessages)==null?void 0:m.call(e))??[],a=((d=y[y.length-1])==null?void 0:d.type)==="text"?y[y.length-1].content:"NO-TEXT";c==null||c({type:"answer_node",payload:{userMessage:(u=i==null?void 0:i.context)==null?void 0:u.user_input,answer:a}})}catch(y){console.error("answerNodeRunner: failed to emit answer telemetry:",y),t==null||t({type:"debug",content:"Warning: failed to emit answer telemetry"})}r==null||r(o.id,{type:"answerNode",message:"Answer response for: "+o.data.response,saved:!0,persistenceRequested:!!n&&!!e.outputCollector,persisted:!1,...e.runId?{runId:e.runId}:{}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}function X(e,o,i,t,r){var n,m,d,u,y;let g=(r==null?void 0:r.callerTag)??"llmNodeRunner",c=(r==null?void 0:r.serializeNonStrings)??!1;return Ut(e,o,{context:i.context??{},results:i.results??{},nodes:((m=(n=i.flowData)==null?void 0:n.state)==null?void 0:m.nodes)??[],edges:((u=(d=i.flowData)==null?void 0:d.state)==null?void 0:u.edges)??[],currentNodeId:o.id,secrets:(y=r==null?void 0:r.sessionEnv)==null?void 0:y.secrets},{callerTag:g,serializeNonStrings:c,onError:a=>{t==null||t({type:`error:${g}`,content:a})}})}var at="[redacted]",fo=8*1024;function Do(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<=fo){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,fo);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function Co(e,o){return Q(e,o)}var dt=(e,o,i,t,r)=>X(e,o,i,r,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function lt(e,o,i,t,r,g,c){var d,u,y,a,f,s;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=null,m=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(i.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(i.results||{}));let h=((d=o.data)==null?void 0:d.url)||"",p=dt(h,o,i,e,t);if(console.log("[apiNodeRunner] resolved url:",K(h)?G(p):p),!p){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"}}),r==null||r(o.id,n);return}let l=(((u=o.data)==null?void 0:u.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",l);let w=((y=o.data)==null?void 0:y.headers)||{},N={},R={};for(let V in w)if(Object.prototype.hasOwnProperty.call(w,V)){let U=String(w[V]??"");R[V]=K(U),N[V]=dt(U,o,i,e,t)}let A,D=!1;if(l!=="GET"&&l!=="HEAD"&&((a=o.data)==null?void 0:a.body)!==void 0){let V=typeof o.data.body=="string"?o.data.body:JSON.stringify(o.data.body);D=K(V),A=dt(V,o,i,e,t),!N["Content-Type"]&&!N["content-type"]&&(N["Content-Type"]="application/json")}let F={};for(let V in N)F[V]=R[V]?at:N[V];console.log("[apiNodeRunner] headers:",JSON.stringify(F)),console.log("[apiNodeRunner] body:",D?at:A),t==null||t({type:"info:apiNodeRunner:request",content:{nodeId:o.id,method:l,url:K(h)?G(p):p,headers:F,body:D?at:A}});let M=Number((f=o.data)==null?void 0:f.timeoutMs),b=new AbortController,x=Number.isFinite(M)&&M>0?setTimeout(()=>b.abort(),M):null,T;try{console.log("[apiNodeRunner] fetching..."),T=await fetch(p,{method:l,headers:N,body:A,signal:b.signal}),console.log("[apiNodeRunner] fetch returned status:",T.status)}finally{x&&clearTimeout(x)}let _=T.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",_);let C=await jt(T);console.log("[apiNodeRunner] payload preview:",typeof C=="string"?C.slice(0,200):JSON.stringify(C).slice(0,200)),n={ok:T.ok,status:T.status,data:C};let j=Date.now()-m;c==null||c({type:"api_call",payload:{nodeId:o.id,url:p,method:l,status:T.status,latencyMs:j}});let{value:O,truncated:L}=Do(C);t==null||t({type:"info:apiNodeRunner:response",content:{nodeId:o.id,ok:T.ok,status:T.status,latencyMs:j,data:O,truncated:L,outVars:Co(o,n)}}),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:",(s=JSON.stringify(n))==null?void 0:s.slice(0,300)),r==null||r(o.id,n)}}var Mo="[redacted]",go=8*1024;function ct(e,o){if(typeof e=="string")return K(e)?typeof o=="string"&&/^https?:\/\//i.test(o)?G(o):Mo:o;if(e&&typeof e=="object"&&!Array.isArray(e)){let i={},t=o&&typeof o=="object"&&!Array.isArray(o)?o:{};for(let[r,g]of Object.entries(e))i[r]=ct(g,t[r]);return i}if(Array.isArray(e)){let i=Array.isArray(o)?o:[];return e.map((t,r)=>ct(t,i[r]))}return o}function bo(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<=go){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,go);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function Po(e,o){return Q(e,o)}var jo=(e,o,i,t,r)=>X(e,o,i,r,{callerTag:"toolNodeRunner",serializeNonStrings:!0,sessionEnv:t});function et(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Uo(e){let o=et(e);if(Array.isArray(o.enum)&&o.enum.length>0)return o.enum.every(r=>typeof r=="string"||typeof r=="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 Vo(e,o){var c,n;let i={},t={},r=((c=e.data)==null?void 0:c.inputSchema)??o;if(r&&typeof r=="object"&&!Array.isArray(r)){t=et(et(r).properties);for(let[m,d]of Object.entries(t))i[m]=Uo(d);return{types:i,properties:t}}let g=(n=e.data)==null?void 0:n.argTypes;if(g&&typeof g=="object"&&!Array.isArray(g))for(let[m,d]of Object.entries(g))typeof d=="string"&&(i[m]=d);return{types:i,properties:t}}function Lo(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=et(i).enum;if(Array.isArray(t)){let r=t.find(g=>String(g)===e);if(r!==void 0)return r}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 Wo(e){return e===void 0||typeof e=="string"&&e.trim()===""}function ut(e,o,i,t,r,g,c){if(typeof e=="string"){let n=e.includes("{{")?jo(e,o,i,t,r):e;return Lo(n,g,c)}if(e&&typeof e=="object"&&!Array.isArray(e)){let n={};for(let[m,d]of Object.entries(e))n[m]=ut(d,o,i,t,r);return n}return Array.isArray(e)?e.map(n=>ut(n,o,i,t,r)):e}function Ho(e,o,i,t,r,g){let c={};for(let[n,m]of Object.entries(e)){let d=ut(m,o,i,t,r,g.types[n],g.properties[n]);Wo(d)||(c[n]=d)}return c}async function Jo(e){if(e.toolDefs)return e.toolDefs;if(!e.env)return e.toolDefs={},e.toolDefs;let o=await tt(e.env),i={};for(let t of o)t!=null&&t.id&&(i[t.id]=t);return e.toolDefs=i,i}function Xo(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 qo(e,o,i){let t=rt(e.execution);if(t.authMode==="manual"){let r=Vt(t,e.id);if(!r)throw new Error(`Composio tool '${e.name}' is missing connection scope`);return Lt(r)}return Ht(o,i,{allowChatIdFallback:!0})}async function pt(e,o,i,t,r,g,c){var u,y,a,f,s,h;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n={ok:!1,data:null,error:null},m=Date.now(),d=Xo(o);try{if(d==="catalog")throw new Error("This Tool node still uses a curated catalog connector. Reconfigure it to a tenant HTTP or connector tool.");let p=(u=o.data)!=null&&u.args&&typeof o.data.args=="object"&&!Array.isArray(o.data.args)?o.data.args:{},l=typeof((y=o.data)==null?void 0:y.toolId)=="string"?o.data.toolId.trim():"";if(!l)throw new Error("Tool nodes require toolId");let N=(await Jo(e))[l];if(!N)throw new Error(`Tool ${l} not found`);let R="";if(d==="composio"){if(N.kind!=="composio")throw new Error(`Tool ${l} is not a connector tool`);if(R=typeof((a=o.data)==null?void 0:a.toolSlug)=="string"?o.data.toolSlug.trim():"",!R)throw new Error("Connector tool nodes require toolSlug");let x=rt(N.execution);if(!Wt(x.tools).includes(R))throw new Error(`Tool slug ${R} is not enabled on connector ${l}`)}else if(N.kind!=="http")throw new Error(`Tool ${l} is not an HTTP tool`);let A=Vo(o,d==="http"?N.inputSchema:void 0),D=Ho(p,o,i,e,t,A);if(t==null||t({type:"info:toolNodeRunner:request",content:{nodeId:o.id,source:d,toolSlug:(f=o.data)==null?void 0:f.toolSlug,toolId:(s=o.data)==null?void 0:s.toolId,args:ct(p,D)}}),d==="composio"){let x=typeof((h=o.data)==null?void 0:h.toolVersion)=="string"?o.data.toolVersion.trim():"",T=await Jt(e,{toolSlug:R,connectionScope:qo(N,e,i),toolVersion:x||null,arguments:D});n={ok:T.ok,data:T.ok?T.data:null,error:T.ok?null:T.error??"Tool execution failed"}}else{let x=ot(N,e,i,t);if(!x.execute)throw new Error(`Tool ${l} is missing an execute handler`);let T=await x.execute(D,{}),_=T&&typeof T=="object"&&"error"in T&&T.error?String(T.error):null;n={ok:!_,data:T,error:_}}let F=Date.now()-m;c==null||c({type:"tool_call",payload:{nodeId:o.id,url:d==="composio"?`composio:${R}`:`tool:${l}`,method:"EXECUTE",status:n.ok?200:502,latencyMs:F}});let{value:M,truncated:b}=bo(n.data);t==null||t({type:"info:toolNodeRunner:response",content:{nodeId:o.id,ok:n.ok,latencyMs:F,data:M,truncated:b,error:n.error,outVars:Po(o,n)}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:n.ok?"success":"error",error:n.error??void 0}})}catch(p){let l=p instanceof Error?p.message:String(p);n={ok:!1,data:null,error:l},t==null||t({type:"error:toolNodeRunner",content:`Tool node execution failed: ${l}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:l}})}finally{r==null||r(o.id,n)}}var Ko=1440*60*1e3,yo=8*1024;function wo(e){if(e==null)return{value:e,truncated:!1};let o=new TextEncoder().encode(JSON.stringify(e));return o.byteLength<=yo?{value:e,truncated:!1}:{value:new TextDecoder().decode(o.slice(0,yo)),truncated:!0}}async function ft(e,o,i,t,r,g,c){var y,a;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n={ok:!1,data:null,error:null},m=Date.now(),d="crawl:unknown",u=f=>{let s=JSON.stringify(f);for(let h of Object.values(e.secrets??{}))h&&(s=s.split(JSON.stringify(h).slice(1,-1)).join("[redacted]"),s=s.split(encodeURIComponent(h)).join("[redacted]"));return JSON.parse(s)};try{let f=e.env;if(!(f!=null&&f.CF_ACCOUNT_ID)||!(f!=null&&f.CF_BROWSER_RUN_TOKEN))throw new Error("Crawl no configurado: faltan CF_ACCOUNT_ID / CF_BROWSER_RUN_TOKEN");let s=X(o.data.url,o,i,t,{callerTag:"crawlNodeRunner",serializeNonStrings:!0,sessionEnv:e}),h=qt(o.data,s),p=K(o.data.url);d=`crawl:${u(new URL(s).host)}`;let l=`crawl:pending:${await Kt(h)}`,w=(y=e.ctx)==null?void 0:y.storage,N=await(w==null?void 0:w.get(l)),R=N&&typeof N.jobId=="string"&&N.jobId&&Number.isFinite(N.createdAt)&&Date.now()-N.createdAt>=0&&Date.now()-N.createdAt<Ko;N&&!R&&await(w==null?void 0:w.delete(l)),t==null||t({type:"info:crawlNodeRunner:request",content:{nodeId:o.id,url:p?u(G(s)):s,resumeJobId:R?N.jobId:void 0}}),{result:n}=await Bt({accountId:f.CF_ACCOUNT_ID,apiToken:f.CF_BROWSER_RUN_TOKEN},o.data,{url:s,...R?{resumeJobId:N.jobId}:{}}),n.error==="timeout"&&((a=n.data)!=null&&a.jobId)?await(w==null?void 0:w.put(l,{jobId:n.data.jobId,createdAt:R?N.createdAt:Date.now()})):n.data&&n.data.status!=="running"&&await(w==null?void 0:w.delete(l))}catch(f){n={ok:!1,data:null,error:f instanceof Error?f.message:String(f)},t==null||t({type:"error:crawlNodeRunner",content:u(`Crawl node execution failed: ${n.error}`)})}finally{let f=Date.now()-m;c==null||c({type:"tool_call",payload:{nodeId:o.id,url:d,method:"EXECUTE",status:n.ok?200:502,latencyMs:f}});let s=wo(u(n.data));t==null||t({type:"info:crawlNodeRunner:response",content:{nodeId:o.id,ok:n.ok,latencyMs:f,data:s.value,truncated:s.truncated,error:u(n.error),outVars:wo(u(Q(o,n))).value}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:n.ok?"success":"error",error:u(n.error)??void 0}}),r==null||r(o.id,n)}}function ho(){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 Bo(e){return!!(e!=null&&e.HX_ORA_URL)&&!!(e!=null&&e.HX_API_KEY)}async function Xe(e,o){if(!Bo(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 No=3,Ro=10,zo=new Set(["agent:start","agent:complete","agent:telemetry"]);function Go(e){let o=e.executedNodes||[];return o.length===0?"(none)":o.map(i=>i.label?`${i.id} (${i.label})`:i.id).join(" \u2192 ")}function Yo(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 Zo(e,o){var g,c,n,m,d,u,y;let i=Array.isArray((g=e.data)==null?void 0:g.inputs)?e.data.inputs:[],t=((n=(c=o.flowData)==null?void 0:c.state)==null?void 0:n.nodes)||[],r={};for(let a of i){let f=(m=a.key)==null?void 0:m.trim();if(!f)continue;let s=(d=a.from)==null?void 0:d.trim();if(!s){if(a.default===void 0)continue;r[f]=a.default;continue}let h=H(s,{context:o.context||{},results:o.results||{},nodes:t,edges:((y=(u=o.flowData)==null?void 0:u.state)==null?void 0:y.edges)??[],currentNodeId:e.id}),p=h.value;if(h.missing||p===void 0||p===null){if(a.default===void 0)throw new P(h.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Worker node ${e.id} could not resolve input "${s}"`);p=a.default}r[f]=p}return r}async function mt(e,o,i,t,r,g,c){var b,x,T,_,C,j;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=typeof((b=o.data)==null?void 0:b.flowId)=="string"?o.data.flowId.trim():"";n||q(t,o,new Error(`Worker node ${o.id} is missing flowId`));let m=(x=i.flowData)==null?void 0:x.flowId,d=e.workerStack??(m?[m]:[]);d.includes(n)&&q(t,o,new Error(`Worker node ${o.id} cannot call ${n}: cycle detected (${[...d,n].join(" \u2192 ")})`)),d.length>=No&&q(t,o,new Error(`Worker node ${o.id} exceeded max nesting depth (${No})`));let u=e.workerCalls??{count:0};e.workerCalls=u,u.count>=Ro&&q(t,o,new Error(`Worker node ${o.id} exceeded max worker calls per run (${Ro})`)),u.count+=1;let y;try{y=Zo(o,i)}catch(O){q(t,o,O instanceof Error?O:new Error(String(O)));return}let a=e.env;a||q(t,o,new Error(`Worker node ${o.id} is missing runtime env`));let f,s;try{let O=await $t(n,a);s=(T=O==null?void 0:O.metadata)==null?void 0:T.tenant,f=await At(n,a)}catch(O){q(t,o,new Error(`Worker node ${o.id} could not load worker ${n}: ${O instanceof Error?O.message:String(O)}`))}let h=(_=i.flowData)==null?void 0:_.tenant;(!s||s!==h)&&q(t,o,new Error(`Worker ${n} belongs to a different tenant`));let p=ho(),l={flowData:{...f,tenant:s,flowId:n,chatId:((C=i.flowData)==null?void 0:C.chatId)||""},executedNodes:[],context:{},results:{}},w={env:a,ctx:e.ctx,secrets:e.secrets,userAuth:e.userAuth,user:e.user,toolDefs:e.toolDefs,composioSessions:e.composioSessions,skillRefCache:e.skillRefCache,publicOrigin:e.publicOrigin,getOraModel:e.getOraModel,runId:e.runId,shouldStop:e.shouldStop,workerCalls:u,conn:void 0,getMessages:async()=>[],setMessages:async()=>{},agentMemory:"",outputCollector:p,workerStack:[...d,n]},N,R={onChangeState:()=>{},onServerEvent:O=>{var L;zo.has(O.type)||t==null||t({type:"worker:node",content:{workerNodeId:o.id,childNodeId:(L=O.content)==null?void 0:L.nodeId,event:O}})},onTelemetry:O=>c==null?void 0:c(O),onError:O=>{N=O},shouldStop:e.shouldStop},{startEngine:A,FlowExecutionStoppedError:D}=await import("./FlowEngine-ZK5GIEV6.js"),F=await A(w,l,R)({text:"",inputs:y});if((F.status==="stopped"||await((j=e.shouldStop)==null?void 0:j.call(e)))&&q(t,o,new D),F.status!=="completed"){let O=Yo(l),L=Go(l),V=F.error||N||"unknown error",U=O?` at node ${O.label?`${O.id} (${O.label})`:O.id}`:"";q(t,o,new Error(`Worker ${n} failed${U}: ${V}. Path: ${L}`))}p.hasOutputs()||q(t,o,new Error(`El worker ${n} complet\xF3 sin output estructurado. Agreg\xE1 un mapeo de salida en su nodo Answer.`));let M=(l.executedNodes||[]).map(O=>O.id);r==null||r(o.id,{ok:!0,data:p.snapshotData(),error:null,executed:M}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}async function gt(e,o,i,t,r,g,c){var d,u,y,a,f,s,h,p;let n=Date.now(),m=(l,w={})=>t==null?void 0:t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:l,...w}});m("start");try{let l=o.data,w={context:i.context??{},results:i.results??{},nodes:((u=(d=i.flowData)==null?void 0:d.state)==null?void 0:u.nodes)??[],edges:((a=(y=i.flowData)==null?void 0:y.state)==null?void 0:a.edges)??[],currentNodeId:o.id},N=_=>{let C=w.nodes.find(L=>_.startsWith(`${L.id}.`)),j=C&&Pt(C).find(L=>L.name===_.slice(C.id.length+1).split(".")[0]);if(_==="images"||(j==null?void 0:j.type)==="image")throw new Error("Classifier accepts text context only");let O=H(_,w);if(O.missing||O.value===void 0||O.value===null)throw new Error(`Classifier input "${_}" did not produce a value`);return O.value},R=N(l.input.message);if(typeof R!="string")throw new Error("Classifier message must be text");let A=l.input.historyTurns>0&&e.getMessages?Et(await e.getMessages(),l.input.historyTurns,(f=i.context)==null?void 0:f.user_input):[],D=Object.fromEntries(l.input.vars.map(_=>[_,N(_)])),F=zt(l,{message:R,history:A,vars:D});console.log(`[classifier] node ${o.id} model=${l.model} message=${R.length}ch history=${A.length} vars=${Object.keys(D).length} options=${l.options.length} checks=${l.checks.length} estTokens=${Gt(F)}`);let M=st(F);if(M&&console.warn(`[classifier] node ${o.id} ${M}`),M&&(t==null||t({type:"warning:classifier",content:{nodeId:o.id,message:M}})),!((s=e.env)!=null&&s.AI))throw new Error("Classifier requires AI binding");let b;try{b=await Yt(e.env.AI,l.model,F)}finally{let _=st(F);_&&_!==M&&console.warn(`[classifier] node ${o.id} ${_}`),_&&_!==M&&(t==null||t({type:"warning:classifier",content:{nodeId:o.id,message:_}}))}let{result:x,usage:T}=Zt(b,l);console.log(`[classifier] \u2713 node ${o.id} route=${x.route} class=${x.classification} confidence=${x.confidence} margin=${x.margin.toFixed(4)} tokens=${T.promptTokens} ${Date.now()-n}ms`),r==null||r(o.id,x),c==null||c({type:"decision_telemetry",payload:{nodeId:o.id,model:l.model,totalLatency:Date.now()-n,usage:T,route:x.route}}),m("success",{summary:{route:x.route,classification:x.classification,label:x.label,confidence:x.confidence,margin:x.margin,probabilities:Object.fromEntries(Object.entries(x.probabilities).sort((_,C)=>C[1]-_[1]).slice(0,5)),checks:x.checks}})}catch(l){console.error(`[classifier] \u2717 node ${o.id} model=${(h=o.data)==null?void 0:h.model} ${Date.now()-n}ms: ${l instanceof Error?`${l.name}: ${l.message}`:String(l)}`),r==null||r(o.id,Qt()),c==null||c({type:"decision_telemetry",payload:{nodeId:o.id,model:(p=o.data)==null?void 0:p.model,totalLatency:Date.now()-n,route:"error",usage:{promptTokens:0,completionTokens:0,totalTokens:0}}}),m("error",{error:l instanceof Error&&l.message==="Clef timeout"?"Clef timeout":"Classifier decision failed",route:"error"})}}import{stepCountIs as ae,streamText as de}from"ai";import{nanoid as le}from"nanoid";import"zod";function To(e,o){var n,m,d,u,y;let i=((n=e.data)==null?void 0:n.attachments)??[];if(!Array.isArray(i))throw new P("INVALID_EXPRESSION",`Node ${e.id} attachments must be an array`);let t=((d=(m=o.flowData)==null?void 0:m.state)==null?void 0:d.nodes)??[],r=((y=(u=o.flowData)==null?void 0:u.state)==null?void 0:y.edges)??[],g=Z(t,r,e.id),c="";for(let a of i){if(typeof a!="string")throw new P("INVALID_EXPRESSION",`Node ${e.id} has an invalid attachment reference`);let f=g.find(h=>h.ref===a);if(!f)throw new P("OUT_OF_SCOPE",`Attachment "${a}" is not in this node's connection scope`);if(f.type!=="file"&&f.type!=="image")throw new P("UNKNOWN_OUTPUT",`Attachment "${a}" is not an image or file output`);if(f.type!=="file")continue;let s=H(a,{context:o.context??{},results:o.results??{},nodes:t,edges:r,currentNodeId:e.id});if(s.missing)throw new P(s.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${a}" did not produce a value`);if(typeof s.value!="string")throw new P("PATH_NOT_FOUND",`Attachment "${a}" must resolve to file text`);s.value.trim()&&(c+=(c?`
2
+
3
+ `:"")+s.value)}return c}function Qo(e,o){var r,g,c,n,m;let i=((r=e.data)==null?void 0:r.attachments)??[];if(!Array.isArray(i))throw new P("INVALID_EXPRESSION",`Node ${e.id} attachments must be an array`);let t=Z(((c=(g=o.flowData)==null?void 0:g.state)==null?void 0:c.nodes)??[],((m=(n=o.flowData)==null?void 0:n.state)==null?void 0:m.edges)??[],e.id);return i.map(d=>{if(typeof d!="string")throw new P("INVALID_EXPRESSION",`Node ${e.id} has an invalid attachment reference`);let u=t.find(y=>y.ref===d);if(!u)throw new P("OUT_OF_SCOPE",`Attachment "${d}" is not in this node's connection scope`);if(u.type!=="image"&&u.type!=="file")throw new P("UNKNOWN_OUTPUT",`Attachment "${d}" is not a binary output`);return u.type==="image"?d:null}).filter(d=>d!==null)}function xo(e,o){var r,g,c,n;let i=[],t={context:o.context??{},results:o.results??{},nodes:((g=(r=o.flowData)==null?void 0:r.state)==null?void 0:g.nodes)??[],edges:((n=(c=o.flowData)==null?void 0:c.state)==null?void 0:n.edges)??[],currentNodeId:e.id};for(let m of Qo(e,o)){let d=H(m,t);if(d.missing)throw new P(d.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${m}" did not produce a value`);if(!Array.isArray(d.value))throw new P("PATH_NOT_FOUND",`Attachment "${m}" must resolve to an image array`);i.push(...d.value)}return i}var z=(e,o,i)=>{e.send(o+"::"+i)};import{openai as Eo}from"@ai-sdk/openai";import{extractReasoningMiddleware as So,wrapLanguageModel as vo}from"ai";import{createWorkersAI as te}from"workers-ai-provider";import{xai as oe}from"@ai-sdk/xai";import{anthropic as ee}from"@ai-sdk/anthropic";import{createOpenRouter as ie}from"@openrouter/ai-sdk-provider";var wt={};function yt(e){if(e!=null){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}}function re(e){return{...e,defaultParams:yt(e.defaultParams)??e.defaultParams,capabilities:yt(e.capabilities)??e.capabilities,price:yt(e.price)??e.price}}async function $o(e,o,i){var u,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 r=re(t),g=((u=r.capabilities)==null?void 0:u.params)??vt(r),{effectiveParams:c,adjustments:n}=oo(r.defaultParams,i,g),m;if(wt[r.provider])m=await wt[r.provider](r,o,i);else if(r.provider==="openai")m=Eo(r.providerModel);else if(r.provider==="xai")m=oe(r.providerModel);else if(r.provider==="anthropic")m=ee(r.providerModel);else if(r.provider==="openrouter")m=ie()(r.providerModel);else if(r.provider==="workersai"||r.provider==="cloudflare"){if(!((y=o==null?void 0:o.env)!=null&&y.AI))throw new Error("Workers AI provider requires sessionEnv.env.AI binding");m=te({binding:o.env.AI})(r.providerModel)}else m={provider:r.provider,providerModel:r.providerModel};let d=io(r);return d.kind==="tag"&&m&&typeof m=="object"&&"specificationVersion"in m&&(m=vo({model:m,middleware:So({tagName:d.tagName??"think",startWithReasoning:d.startWithReasoning??!1})})),{provider:r.provider,modelHandle:m,entry:r,effectiveParams:c,paramAdjustments:n.length>0?n:void 0,reasoning:d}}function gi(e,o){wt[e]=o}var se=E({"../tools/composioDirectTool.ts":()=>import("./composioDirectTool-XOKIM5FJ.js"),"../tools/composioTool.ts":()=>import("./composioTool-C4KZMI4Q.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-IW4W7CGE.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 ne=E({});async function ce(e,o,i,t){var y;let r=Array.isArray((y=i==null?void 0:i.data)==null?void 0:y.tools)?i.data.tools:[];if(r.length===0)return{};let g={},c=a=>{var N,R;let f=typeof(a==null?void 0:a.description)=="string"?a.description:"",s=a==null?void 0:a.inputSchema,h;try{let A=(s==null?void 0:s.shape)??(typeof((N=s==null?void 0:s._def)==null?void 0:N.shape)=="function"?s._def.shape():(R=s==null?void 0:s._def)==null?void 0:R.shape);A&&typeof A=="object"&&(h=A)}catch{}let p=h?Object.keys(h):[],l=f?`description="${f.length>120?f.slice(0,120)+"\u2026":f}"`:"description=(none)",w=p.length?`inputSchema={${p.join(", ")}}`:"inputSchema=(none)";return`${l} ${w}`},n=(()=>{let a=[],f=[],s=[],h=[];for(let l=0;l<r.length;l++){let w=r[l];!w||typeof w!="object"||typeof w.id!="string"?h.push(l):w.kind==="builtin"?a.push(w.id):w.kind==="skill"?s.push(w.id):w.kind==="http"||w.kind==="mcp"||w.kind==="composio"?f.push(w.id):h.push(l)}let p=[];return a.length&&p.push(`builtin[${a.join(", ")}]`),f.length&&p.push(`custom[${f.join(", ")}]`),s.length&&p.push(`skill[${s.join(", ")}]`),h.length&&p.push(`invalid@[${h.join(", ")}]`),p.join(" ")||"(none)"})();console.log(`[tools] node ${i.id} requested (${r.length}): ${n}`);let m=!1,d=async()=>{if(m&&e.toolDefs)return e.toolDefs;if(!e.env)return e.toolDefs=e.toolDefs||{},m=!0,e.toolDefs;try{let a=await tt(e.env),f={};for(let s of a)s&&s.id&&(f[s.id]=s);e.toolDefs=f}catch(a){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(a)}`}),e.toolDefs=e.toolDefs||{}}return m=!0,e.toolDefs},u=[];for(let a=0;a<r.length;a++){let f=r[a];if(!f||typeof f!="object"||typeof f.id!="string"||f.kind!=="builtin"&&f.kind!=="http"&&f.kind!=="mcp"&&f.kind!=="composio"&&f.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${a}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let s=f;if(s.kind!=="builtin"){let p=(await d())[s.id];if(!p){console.error(`[tools] \u2717 custom '${s.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${s.id}' not found for this tenant`});continue}if(s.kind==="composio"){try{let w=await ao(p,e,o,t),N=Object.keys(w);for(let[R,A]of Object.entries(w))g[R]=A;console.log(`[tools] \u2713 composio '${s.id}' \u2192 ${N.length} tool(s)`)}catch(w){console.error(`[tools] \u2717 composio '${s.id}': ${String(w)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${s.id}': ${String(w)}`})}continue}if(s.kind==="skill"){if(p.kind!=="skill"){console.error(`[tools] \u2717 skill '${s.id}': row is of kind '${p.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${s.id}' is not a skill`});continue}let w=p.name;if(g[w]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin/other already registered, skipping skill '${s.id}'`});continue}try{g[w]=lo(p,e,o,t),u.push(p);let N=typeof p.execution=="string"?JSON.parse(p.execution):p.execution||{},R=Array.isArray(N.references)?N.references.map(A=>A==null?void 0:A.name):[];console.log(`[tools] \u2713 skill '${s.id}' \u2192 '${w}' (refs: ${R.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:w,refCount:R.length,refs:R}})}catch(N){console.error(`[tools] \u2717 skill '${s.id}': ${String(N)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${s.id}': ${String(N)}`})}continue}let l=p.name;if(g[l]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${l}' \u2014 builtin already registered, skipping custom tool '${s.id}'`});continue}try{let w=ot(p,e,o,t);g[l]=w,console.log(`[tools] \u2713 custom '${s.id}' \u2192 '${l}'`),console.log(`[tools] ${c(g[l])}`)}catch(w){console.error(`[tools] \u2717 custom '${s.id}': ${String(w)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${s.id}': ${String(w)}`})}continue}if(!St[s.id]){console.error(`[tools] \u2717 builtin '${s.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${s.id}' not found in registry`});continue}try{let h;try{h=await se(`../tools/${s.id}.ts`)}catch{h=await ne(`../tools/${s.id}.js`)}let p;if(h[s.id])p=h[s.id];else if(h.default)p=h.default;else if(h.create)p=h.create;else{let F=Object.values(h);F.length>0&&(p=F[0])}if(!p){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${s.id}'`});continue}let l,w,N={};if(s.params&&typeof s.params=="object"){if(typeof s.params.description=="string"?l=s.params.description:s.params.description!==void 0&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${s.id}' \u2014 must be a string`})),s.params.inputSchema!==void 0){let F=s.params.inputSchema;typeof F=="object"&&(typeof F.safeParse=="function"||F._def)?w=F:typeof F=="object"&&F!==null&&F.type==="object"&&F.properties?(w=Xt(F),w||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${s.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${s.id}' \u2014 must be a Zod schema or JSON Schema object`})}s.params.defaults!==void 0?typeof s.params.defaults=="object"&&s.params.defaults!==null&&!Array.isArray(s.params.defaults)?N=s.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${s.id}' \u2014 must be an object`}),N={}):s.params.source!==void 0||s.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${s.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),N={}):N={}}let R=p(e,o,N,t);l&&R&&typeof R=="object"&&(R.description=l),w&&R&&typeof R=="object"&&(R.inputSchema=w),g[s.id]=R;let A=[];l&&A.push("description"),w&&A.push("inputSchema"),Object.keys(N).length&&A.push(`defaults(${Object.keys(N).join(",")})`);let D=A.length?` [overrides: ${A.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${s.id}'${D}`),console.log(`[tools] ${c(R)}`)}catch(h){console.error(`[tools] \u2717 builtin '${s.id}': ${String(h)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${s.id}': ${String(h)}`});continue}}if(u.length>0)if(g.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{g.readSkillRef=co(e,u,o,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${u.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:u.map(a=>a.name)}})}catch(a){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(a)}`)}return g}async function ht(e,o,i,t,r,g,c){var F,M,b,x;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=!1;try{let T=(F=i.flowData)==null?void 0:F.state;if(T&&T.edges&&T.nodes){let _=T.edges.filter(C=>C.source===o.id);if(_.length>0){let C=T.nodes.find(j=>j.id===_[0].target);C&&C.type==="answerNode"&&(n=!0)}}}catch(T){console.error("Error determining next node for streaming:",T)}let m=X(o.data.template,o,i,t,{sessionEnv:e});(!m||!m.trim())&&(m="Answer straight forward to the user, dont offer any other option to continue");let d=m,u=X(o.data.user_template||"",o,i,t,{sessionEnv:e}),y=T=>T&&Object.fromEntries(Object.keys(T).map(_=>[_,"[redacted]"])),a=e!=null&&e.secrets||e!=null&&e.userAuth?{...e,secrets:y(e.secrets),userAuth:y(e.userAuth)}:e,f=X(o.data.template,o,i,void 0,{sessionEnv:a})||d,s=X(o.data.user_template||"",o,i,void 0,{sessionEnv:a});t==null||t({type:`info:llmNodeRunner:${o.id}`,content:f}),t==null||t({type:`info:llmNodeRunner:${o.id}`,content:s});let h=(M=o==null?void 0:o.data)==null?void 0:M.window_size,p=Number(h);(!Number.isInteger(p)||p<=0)&&(p=5);let l=xo(o,i),w=To(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:l.length,documents:w?1:0}});let R=(await((x=e.getMessages)==null?void 0:x.call(e))??[]).slice(-p),A=R.filter(T=>T&&typeof T.role=="string"&&typeof T.content=="string");A.length!==R.length&&console.warn(`Filtered ${R.length-A.length} invalid messages from history`);let D=pe(A,u,l,w);await ue(m,D,e.conn,t,o,n,r,i,g,e,c)}async function ue(e,o,i,t,r,g,c,n,m,d,u){var a;let y=Date.now();if(!((a=d.env)!=null&&a.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(f,s)=>{var _,C,j,O,L,V;let h,p={},l,w="none",N=!1,R,A=!1,D=!1,F=0,M=0,b=(_=r==null?void 0:r.data)==null?void 0:_.sendReasoning,x=b!==!1;try{let U=(C=r==null?void 0:r.data)==null?void 0:C.model,Y=Array.isArray(U)?U[0]:U||"gpt_5_nano",$=to(r==null?void 0:r.data),k=await $o(Y,d,$);if(!k)throw new Error(`Model '${Y}' not found in registry`);h=k.modelHandle,p=k.effectiveParams||{},w=k.reasoning.kind;let I=so(k.reasoning,(j=r==null?void 0:r.data)==null?void 0:j.reasoningEffort);N=x&&ro(k.reasoning);let J=typeof((O=r==null?void 0:r.data)==null?void 0:O.reasoningMaxTokens)=="number"?r.data.reasoningMaxTokens:void 0;l=no(k.provider,{effort:I,exposeReasoning:N,maxTokens:J}),I&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:I})),console.log(`[reasoning] ${JSON.stringify({model:Y,provider:k.provider,capability:k.reasoning,requestedEffort:((L=r==null?void 0:r.data)==null?void 0:L.reasoningEffort)??null,resolvedEffort:I??null,sendReasoning:x,exposeReasoning:N,providerOptions:l??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:Y}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(V=r==null?void 0:r.data)!=null&&V.generationPreset?{preset:r.data.generationPreset}:{},...p,...w!=="none"?{reasoning:w,configuredSendReasoning:b,sendReasoning:x,exposeReasoning:N,...I?{effort:I}:{}}:{}}})}catch(U){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(U)}`}),U}let T=await ce(d,n,r,t);console.log(`[tools] node ${r.id} loaded ${Object.keys(T).length}: ${Object.keys(T).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:r.id,tools:Object.keys(T)}});try{let U=de({model:h,system:e,messages:o,stopWhen:(()=>{var W;let k=!!T.readSkillRef?10:5,I=Number(((W=r.data)==null?void 0:W.max_steps)??k),J=Number.isFinite(I)?Math.max(1,Math.min(30,I)):k;return ae(J)})(),...eo(p),...l?{providerOptions:l}:{},tools:T,onFinish:async $=>{var Tt,xt;let k=$.text||"",I=$.reasoningText??((Tt=$.reasoning)==null?void 0:Tt.text)??"";if(console.log(`[reasoning] done: deltas=${F} chars=${M} result.reasoningText=${I.length} finishReason=${$.finishReason??"n/a"} reasoningTokens=${((xt=$.usage)==null?void 0:xt.reasoningTokens)??"n/a"}`),x&&N&&!A&&I&&i){A=!0;try{z(i,B.SERVER_REASONING_STREAM,I)}catch(Io){console.warn("Failed to send finished reasoning over connection",Io)}}let J={id:le(),role:"assistant",type:"text",content:k,ts:Date.now()};g&&(d.setMessages?await d.setMessages(J):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),i&&x&&A&&!D&&(D=!0,z(i,B.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),g&&i&&z(i,B.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),c==null||c((r==null?void 0:r.id)||"llm_result",k),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify($)});let W=Date.now()-y,Oo=R?R-y:void 0;u==null||u({type:"llm_telemetry",payload:{nodeId:r.id,totalLatency:W,timeToFirstToken:Oo,model:$.response.modelId,usage:$.usage}}),u==null||u({type:"llm_result",payload:{result:$}})},onStepFinish:async $=>{let k=(I,J=200)=>{let W=typeof I=="string"?I:JSON.stringify(I);return W?W.length>J?`${W.slice(0,J)}\u2026(+${W.length-J})`:W:""};if($.toolCalls&&$.toolCalls.length>0){for(let I of $.toolCalls)console.log(`[tools] \u2192 ${I.toolName}(${k(I.args??I.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${r.id}`,content:JSON.stringify($.toolCalls)})}if($.toolResults&&$.toolResults.length>0){for(let I of $.toolResults)console.log(`[tools] \u2190 ${I.toolName} \u2192 ${k(I.result??I.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${r.id}`,content:JSON.stringify($.toolResults)})}},experimental_onToolCallStart:$=>{var k;t==null||t({type:"tool:execution",content:{nodeId:r.id,toolName:(k=$==null?void 0:$.toolCall)==null?void 0:k.toolName,status:"start"}})},experimental_onToolCallFinish:$=>{var k,I;t==null||t({type:"tool:execution",content:{nodeId:r.id,toolName:(k=$==null?void 0:$.toolCall)==null?void 0:k.toolName,status:((I=$==null?void 0:$.toolOutput)==null?void 0:I.type)==="tool-error"?"error":"success"}})},onError:$=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),s($)},onChunk:$=>{if($.chunk.type==="reasoning-delta"){let I=$.chunk.text??$.chunk.delta??"";if(I&&(A=!0,F+=1,M+=I.length,F===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),x&&i&&I)try{z(i,B.SERVER_REASONING_STREAM,I)}catch(J){console.warn("Failed to send reasoning chunk over connection",J)}return}if($.chunk.type==="text-delta"){if(R||(R=Date.now()),i&&x&&A&&!D){D=!0;try{z(i,B.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(I){console.warn("Failed to send reasoning complete over connection",I)}}return}u==null||u({type:$.chunk.type,payload:{nodeId:r.id,chunk:$.chunk}});let k=`llm_chunk:${$.chunk.type}`;t==null||t({type:k,content:{...$}})}}),Y=async()=>{let $="";for await(let k of U.fullStream)if(k.type==="text-delta"){if($+=k.text,g&&i)try{z(i,B.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(g&&i&&$.trim())try{z(i,B.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(I){console.warn("Failed to flush text segment over connection",I)}$=""}};await Promise.all([U,Y()]),f(),t==null||t({type:"node:execution",content:{nodeId:r.id,nodeType:r.type,status:"success"}})}catch(U){t==null||t({type:"node:execution",content:{nodeId:r.id,nodeType:r.type,status:"error",error:String(U)}}),s(U)}})}function pe(e,o,i,t){let r=!!(i&&i.length>0),g=!!t,c=r||g,m=e.length>0&&e[e.length-1].role==="user"?e[e.length-1]:void 0,d=u=>{let y=[],a="";if(g&&(a+=`[Attached files]
4
+ ${t}
5
+ [End of attached files]
6
+
7
+ `),u&&(a+=u),a&&y.push({type:"text",text:a}),r)for(let f of i)y.push({type:"image",image:f.data,mimeType:f.mimeType});return y};return o&&m&&m.content===o?[...e.slice(0,-1).map(y=>({role:y.role,content:y.content})),{role:"user",content:d(o)}]:o?[...e.map(u=>({role:u.role,content:u.content})),{role:"user",content:d(o)}]:c&&m?[...e.slice(0,-1).map(y=>({role:y.role,content:y.content})),{role:"user",content:d(m.content)}]:e.map(u=>({role:u.role,content:u.content}))}async function Nt(e,o,i,t,r,g,c){var u,y,a,f,s,h,p;console.log(`**** MEMO Node id: ${o.id} ****`),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n="",m=!1,d=Date.now();try{t==null||t({type:"info:memoNodeRunner",content:"Starting memo node execution"});let l=String(((u=o.data)==null?void 0:u.query_key)||"user_input"),w=H(l,{context:i.context??{},results:i.results??{},nodes:((a=(y=i.flowData)==null?void 0:y.state)==null?void 0:a.nodes)??[],edges:((s=(f=i.flowData)==null?void 0:f.state)==null?void 0:s.edges)??[],currentNodeId:o.id});if(w.missing)throw new Error(`Memo query "${l}" did not produce a value`);if(!e.env||!e.ctx){t==null||t({type:"error:memoNodeRunner",content:"Missing env or ctx"}),r==null||r(o.id,n);return}if(!o.data.rag_id){t==null||t({type:"error:memoNodeRunner",content:"Missing rag_id"}),r==null||r(o.id,n);return}let N=String(w.value??"");t==null||t({type:"info:memoNodeRunner",content:`Query text: ${N}`}),t==null||t({type:"info:memoNodeRunner",content:"Generating embedding for query"});let R=await Ft(e,N,!0);t==null||t({type:"info:memoNodeRunner",content:`Embedding generated successfully, length: ${R.data[0].length}`});let A=Array.isArray(o.data.rag_id)?o.data.rag_id:[o.data.rag_id],D=[];for(let x of A){t==null||t({type:"info:memoNodeRunner",content:`Executing RAG query with namespace: ${x}`});let T=await e.env[`VDB_${(h=i.flowData)==null?void 0:h.tenant}_1024`].query(R.data[0],{namespace:x,topK:o.data.topk,returnMetadata:"all"});t==null||t({type:"info:memoNodeRunner",content:`RAG query completed for namespace ${x}, matches: ${((p=T.matches)==null?void 0:p.length)||0}`}),Array.isArray(T.matches)&&D.push(...T.matches)}let F=Date.now()-d;n=D.map(x=>{var T;return(T=x.metadata)==null?void 0:T.value}).filter(x=>typeof x=="string").join(`
8
+
9
+ `),c==null||c({type:"memo_search",payload:{nodeId:o.id,searchLatencyMs:F,retrievedContext:n}}),t==null||t({type:"info:memoNodeRunner",content:`Context retrieval complete, length: ${n.length}, preview: ${n.substring(0,200)}...`}),t==null||t({type:"info:memoNodeRunner",content:"Memo node execution completed successfully"}),m=!0}catch(l){throw console.error("Error processing MemoNode:",l),t==null||t({type:"error:memoNodeRunner",content:`Memo node execution failed: ${l}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(l)}}),l}finally{m&&(r==null||r(o.id,n),t==null||t({type:"info:memoNodeRunner",content:`onResult called with context length: ${n.length}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}}))}}async function Rt(e,o,i,t,r,g,c){var u,y,a,f,s,h,p,l;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}),c==null||c({type:"start_node",payload:{userMessage:(u=i==null?void 0:i.context)==null?void 0:u.user_input}});let n=((y=o.data)==null?void 0:y.allow_images)!==!1,m=((a=o.data)==null?void 0:a.allow_documents)!==!1;!n&&(i!=null&&i.context)&&(i.context.user_images=[],g==null||g({...i})),!m&&(i!=null&&i.context)&&(i.context.files="",g==null||g({...i}));let d={};for(let w of S(o.data))d[w.name]=(f=i==null?void 0:i.context)==null?void 0:f[w.name];r==null||r(o.id,{...d,user_input:(s=i==null?void 0:i.context)==null?void 0:s.user_input,images:n?(h=i==null?void 0:i.context)==null?void 0:h.user_images:[],files:m?(p=i==null?void 0:i.context)==null?void 0:p.files:"",memory:((l=i==null?void 0:i.context)==null?void 0:l.memory)??""}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}function pr(e,o,i){let t=o;async function r(){var d;if(await((d=i==null?void 0:i.shouldStop)==null?void 0:d.call(i)))throw new it}async function g(d){let u=d;for(t.executedNodes=t.executedNodes||[],t.context=t.context||{},t.results=t.results||{};u&&u.id;)await r(),await c(u),await r(),u=me(u,t.flowData,t)}async function c(d){var s,h;let u=m[d.type];if(!u){(s=i==null?void 0:i.onError)==null||s.call(i,`Unknown node type: ${d.type}`);return}t.executedNodes=t.executedNodes||[],t.executedNodes.push({id:d.id,type:d.type,label:typeof((h=d.data)==null?void 0:h.label)=="string"?d.data.label:void 0}),t.lastNodeId=d.id;let y=p=>{var l;return(l=i==null?void 0:i.onServerEvent)==null?void 0:l.call(i,{...p,ts:Date.now()})},a=p=>{var l,w;if((l=i==null?void 0:i.onTelemetry)==null||l.call(i,p),p.type==="llm_telemetry"||p.type==="decision_telemetry"||p.type==="memory_update"){let N=(w=p.payload)==null?void 0:w.usage;N&&(t.tokenUsage=t.tokenUsage||{promptTokens:0,completionTokens:0,totalTokens:0},t.tokenUsage.promptTokens+=N.promptTokens||0,t.tokenUsage.completionTokens+=N.completionTokens||0,t.tokenUsage.totalTokens+=N.totalTokens||0)}};return await u(e,d,t,y,(p,l)=>{t.results[p]=l},i==null?void 0:i.onChangeState,a)}let n=async d=>{var f,s,h,p,l,w,N;let u=Date.now(),y="completed",a;try{await r();let R=typeof d=="string"?It(d):d,A=(R==null?void 0:R.text)||"",D=(R==null?void 0:R.images)||[],F=(R==null?void 0:R.documents)||[],M=await uo(F,e.env),b=M.length>0?M.map(_=>`--- file: ${_.name} ---
10
+ ${_.text}`).join(`
11
+
12
+ `):"";t.context={user_input:A,user_images:D,files:b},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},t.executedNodes=[],(f=i==null?void 0:i.onServerEvent)==null||f.call(i,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:x,error:T}=fe(t.flowData);if(!x)y="failed",a=T||"Flow Format Error",(s=i==null?void 0:i.onError)==null||s.call(i,a);else{let _=S(x.data),{values:C,errors:j}=Ot(_,R==null?void 0:R.inputs);if(j.length>0)return y="failed",a=`Invalid flow inputs: ${j.join("; ")}`,(h=i==null?void 0:i.onError)==null||h.call(i,a),{status:y,error:a};if(t.context={...t.context,inputs:C,...C},t.context.user_input||(t.context.user_input=A),Ct(x.data)){let O=kt(Mt(x.data));t.context.memory=Dt(e.agentMemory||"",O).content}else t.context.memory="";await g(x),(p=i==null?void 0:i.onServerEvent)==null||p.call(i,{type:"agent:telemetry",content:{durationMs:Date.now()-u,tokenUsage:t.tokenUsage},timestamp:Date.now()})}}catch(R){R instanceof it?(y="stopped",a=R.message,(l=i==null?void 0:i.onServerEvent)==null||l.call(i,{type:"agent:stopped",content:a,timestamp:Date.now()})):(y="failed",a=R instanceof Error?R.message:"Agent execution failed",(w=i==null?void 0:i.onError)==null||w.call(i,a))}finally{(N=i==null?void 0:i.onServerEvent)==null||N.call(i,{type:"agent:complete",content:{status:y,durationMs:Date.now()-u},timestamp:Date.now()})}return{status:y,error:a}},m={startNode:Rt,classifierNode:gt,llmNode:ht,memoNode:Nt,answerNode:nt,apiNode:lt,toolNode:pt,workerNode:mt,crawlNode:ft};return n}var it=class extends Error{constructor(){super("Stopped by user"),this.name="FlowExecutionStoppedError"}};function fe(e){var u,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 a of o.nodes){if(((u=a.data)==null?void 0:u.varMapping)!==void 0)return{error:`Flow uses removed varMapping on node ${a.id}.`};if(a.type==="classifierNode"){let s=_t(a.data);if(s.length)return{error:s.join("; ")};for(let h of a.data.options){let p=o.edges.find(l=>l.source===a.id&&l.sourceHandle===v("class",h.id));if(!p||!o.nodes.some(l=>l.id===p.target))return{error:`Classifier ${a.id}: class ${h.id} has no connected edge`}}}let f=bt(a);if(f.length>0)return{error:f[0]}}let i=o.nodes.filter(a=>a.type==="startNode");if(i.length!==1)return{error:`Flow must include exactly one START node, found ${i.length}.`};let t=i[0],r=o.nodes.filter(a=>a.type==="answerNode");if(r.length===0)return{error:"Flow must include at least one ANSWER node."};let g=new Map;for(let a of o.edges)g.has(a.source)||g.set(a.source,[]),g.get(a.source).push(a.target);let c=new Map;for(let a of o.edges)c.has(a.target)||c.set(a.target,[]),c.get(a.target).push(a.source);let n=Ao(t.id,g),m=new Set;for(let a of r){let f=Ao(a.id,c);for(let s of f)m.add(s)}let d=[];for(let a of n)if(!m.has(a)){let f=o.nodes.find(s=>s.id===a);if(f){let s=((y=f.data)==null?void 0:y.label)||"";d.push(`${a}(${s},${f.type})`)}}return d.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${d.join(", ")}`}:{startNode:t}}function Ao(e,o){let i=new Set,t=[e];for(i.add(e);t.length>0;){let r=t.shift(),g=o.get(r)||[];for(let c of g)i.has(c)||(i.add(c),t.push(c))}return i}function Fo(e,o){var i;return((i=e.state)==null?void 0:i.nodes.find(t=>t.id===o))||null}function me(e,o,i){var g;let t=o==null?void 0:o.state;if(!t)return null;let r=t.edges.filter(c=>c.source===e.id);if(e.type==="classifierNode"){let c=(g=i==null?void 0:i.results)==null?void 0:g[e.id];if(!c||!["class","uncertain","blocked","error"].includes(c.route))throw new Error(`Classifier ${e.id}: missing decision result`);let n=c.route,m=y=>r.find(a=>a.sourceHandle===v(y,c.classification)),d=m(n);if(!d&&n==="blocked"&&(n=c.confidence<e.data.confidence.threshold||c.margin<e.data.confidence.margin?"uncertain":"class",d=m(n)),!d&&n==="uncertain"&&(n="class",d=m(n)),!d)throw new Error(`Classifier ${e.id}: no connected edge for ${v(n,c.classification)}`);let u=Fo(o,d.target);if(!u)throw new Error(`Classifier ${e.id}: edge target ${d.target} does not exist`);return u}return r.length===0?null:Fo(o,r[0].target)}export{z as a,ko as b,ho as c,Xe as d,re as e,$o as f,gi as g,pr as h,it as i};
@@ -1 +1 @@
1
- import{t as N}from"./chunk-QEZQZG6Z.js";import{a as J}from"./chunk-V6JSMX5A.js";import{tool as ot}from"ai";import{z as M}from"zod";import{z as p}from"zod";function j(t){if(t&&typeof t=="object"&&!t.type)return p.object({});if(t.type==="object")if(t.properties){let e={},o=t.required||[];for(let[r,n]of Object.entries(t.properties)){let a=j(n),c=n!=null&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,"default");e[r]=c?a.default(n.default):o.includes(r)?a:a.optional()}return p.object(e)}else return p.object({});else if(t.type==="array"&&t.items){let e=j(t.items);return p.array(e)}else{if(t.type==="string")return p.string();if(t.type==="number"||t.type==="integer")return p.number();if(t.type==="boolean")return p.boolean()}return p.any()}var W=/\{\{\s*secrets\.[A-Z][A-Z0-9_]*\s*\}\}/,xt=t=>W.test(t),rt=/\{\{\s*auth\.[A-Z][A-Z0-9_]*\s*\}\}/;var E=t=>W.test(t)||rt.test(t),w=t=>{let e=t.indexOf("?");return e===-1?t:`${t.slice(0,e)}?[redacted-query]`};var st=256*1024,it=3e4,ct=/\{\{\s*([^}]+?)\s*\}\}/g,at=t=>{let e=t.toLowerCase();return e.includes("token")||e.includes("secret")||e.includes("key")||e.includes("password")||e.includes("access")||e==="authorization"},ut=t=>{let e={};for(let o in t)e[o]=at(o)?"[REDACTED]":t[o];return e},I=(t,e)=>{let o=t.indexOf(".");if(o===-1)return e[t];let r=t.slice(0,o),n=t.slice(o+1);if(r in e)return N(e[r],n)},H=(t,e,o)=>t&&t.replace(ct,(r,n)=>{let a=String(n).trim();if(a.startsWith("secrets.")){let f=a.slice(8);return Object.prototype.hasOwnProperty.call(o.secrets,f)?o.secrets[f]:r}if(a.startsWith("auth.")){let f=a.slice(5);return Object.prototype.hasOwnProperty.call(o.auth,f)?o.auth[f]:r}let c=I(a,e);return c==null?"":typeof c=="string"?c:JSON.stringify(c)}),dt=/\{\{\s*((?:secrets|auth)\.[^}\s]+)\s*\}\}/g,lt=(...t)=>{let e=new Set;for(let o of t){if(o==null)continue;let r=typeof o=="string"?o:JSON.stringify(o);for(let n of r.matchAll(dt))e.add(n[1])}return[...e]},T=(t,e,o)=>{if(t==null)return t;if(typeof t=="string"){let r=t.match(/^\s*\{\{\s*([^}]+?)\s*\}\}\s*$/);if(r){let n=r[1].trim();if(n.startsWith("secrets.")){let c=n.slice(8);return Object.prototype.hasOwnProperty.call(o.secrets,c)?o.secrets[c]:t}if(n.startsWith("auth.")){let c=n.slice(5);return Object.prototype.hasOwnProperty.call(o.auth,c)?o.auth[c]:t}return I(n,e)}return H(t,e,o)}if(Array.isArray(t))return t.map(r=>T(r,e,o));if(typeof t=="object"){let r={};for(let n in t)r[n]=T(t[n],e,o);return r}return t},ft=(t,e)=>t?e?/^https?:\/\//i.test(e)?e:t.endsWith("/")&&e.startsWith("/")?t+e.slice(1):!t.endsWith("/")&&!e.startsWith("/")?`${t}/${e}`:t+e:t:e||"",pt=(t,e)=>{if(!e)return t;let o=new URL(t);for(let r in e){let n=e[r];n!==void 0&&(Array.isArray(n)?o.searchParams.set(r,n.join(",")):o.searchParams.set(r,String(n)))}return o.toString()},K=t=>{if(!t)return{};let e={};for(let o in t)t[o]!==void 0&&(e[o]=t[o]);return e},yt=t=>{let e={};for(let o in t){let r=t[o];r!=null&&(e[o]=typeof r=="string"?r:String(r))}return e},gt=(t,e,o)=>{if(!(!t||t.type==="none"||!t.value)){if(t.type==="bearer"){e.Authorization=`Bearer ${t.value}`;return}if(t.type==="apiKey"){let r=t.in||"header",n=t.param||t.header||"X-API-Key";r==="query"?o[n]=t.value:e[n]=t.value}}},mt=(t,e)=>{let o=new TextEncoder().encode(t);if(o.byteLength<=e)return{text:t,truncated:!1};let r=o.slice(0,e);return{text:new TextDecoder("utf-8",{fatal:!1}).decode(r),truncated:!0}};function ht(t,e,o,r){var Z;if(t.kind!=="http")throw new Error(`customHttpTool: unsupported kind '${t.kind}' for tool '${t.name}'`);let n=t.execution||{},a=n.actions&&typeof n.actions=="object"?Object.keys(n.actions):[],c=((Z=n.router)==null?void 0:Z.field)||"action",f=t.inputSchema&&typeof t.inputSchema=="object"&&Object.keys(t.inputSchema).length>0?j(t.inputSchema):M.object({});if(a.length>0&&f instanceof M.ZodObject){let m=M.enum(a);f=f.extend({[c]:m})}let G=t.description||t.label||t.name,y=t.output||{},Q=Number.isFinite(y.maxBytes)&&y.maxBytes>0?y.maxBytes:st;return ot({description:G,inputSchema:f,execute:async m=>{var z;let h={secrets:e.secrets??{},auth:e.userAuth??{}},b={input:m??{},...o.context||{}},u=n,i;if(n.actions&&typeof n.actions=="object"){let s=((z=n.router)==null?void 0:z.field)||"action";if(i=m==null?void 0:m[s],!i||!n.actions[i])return{type:"error",error:`unknown action '${i}' for tool '${t.name}'`,natural:`Tool ${t.name} could not run: missing or unknown action.`};u=n.actions[i]}let C=u.url||ft(n.baseUrl,u.path);if(!C)return{type:"error",error:"missing url",natural:`Tool ${t.name} has no URL configured.`};let V=E(C),F=H(C,b,h),X={...n.headers||{},...u.headers||{}},g=yt(K(T(X,b,h))),Y={...n.query||{},...u.query||{}},P=K(T(Y,b,h)),$=(u.method||n.method||"GET").toUpperCase(),k,v=u.body!==void 0||n.body!==void 0;if($!=="GET"&&$!=="HEAD"&&v){let s=u.body!==void 0?u.body:n.body,d=typeof s=="string"?H(s,b,h):T(s,b,h);k=typeof d=="string"?d:JSON.stringify(d),!g["Content-Type"]&&!g["content-type"]&&(g["Content-Type"]="application/json")}let R=u.auth||n.auth,A=R?{...R,value:R.value?H(String(R.value),b,h):R.value}:void 0;gt(A,g,P);let S=pt(F,P),tt=V?w(S):S,U=lt(F,g,P,k,A==null?void 0:A.value);if(U.length>0){let s=U.map(d=>`{{ ${d} }}`).join(", ");return r==null||r({type:`error:tool:${t.name}:credentials`,content:{tool:t.name,action:i,missing:U}}),{type:"error",error:`unresolved credentials: ${s}`,natural:`Tool ${t.name} could not run because ${s} has no value in this execution. Connect the credential or use a tenant secret so unattended runs can resolve it.`}}let et=Math.min(Number.isFinite(u.timeoutMs)&&u.timeoutMs>0?u.timeoutMs:Number.isFinite(n.timeoutMs)&&n.timeoutMs>0?n.timeoutMs:15e3,it),D={tool:t.name,action:i,stage:"request",url:tt,method:$,headers:ut(g)};JSON.stringify(D),r==null||r({type:`info:tool:${t.name}:request`,content:D});let q=new AbortController,nt=setTimeout(()=>q.abort(),et);try{let s=await fetch(S,{method:$,headers:g,body:k,signal:q.signal}),d=s.headers.get("content-type")||"",O=await s.text(),{text:x,truncated:_}=mt(O,Q),l;if(y.contentType==="text"?l=x:d.includes("application/json")||y.contentType==="json"?(l=J(x),l===null&&x&&(l=x)):l=x,y.jsonPath&&l!==null&&typeof l=="object"&&(l=N(l,y.jsonPath)),!s.ok){let B={tool:t.name,action:i,stage:"http_error",status:s.status};return JSON.stringify(B),r==null||r({type:`error:tool:${t.name}:http`,content:B}),{type:"error",status:s.status,error:`HTTP ${s.status}: ${s.statusText}`,result:l,truncated:_,natural:`${t.name}${i?`:${i}`:""} failed with HTTP ${s.status}.`}}let L={tool:t.name,action:i,stage:"finish",status:s.status,truncated:_};return JSON.stringify(L),r==null||r({type:`info:tool:${t.name}:finish`,content:L}),{type:i||t.name,status:s.status,result:l,truncated:_,natural:`${t.name}${i?`:${i}`:""} completed (HTTP ${s.status}).`}}catch(s){let d=String((s==null?void 0:s.message)??s),O={tool:t.name,action:i,stage:"error",error:d};return JSON.stringify(O),r==null||r({type:`error:tool:${t.name}:execution`,content:O}),{type:"error",error:d,natural:`${t.name}${i?`:${i}`:""} failed: ${d}`}}finally{clearTimeout(nt)}}})}var St=ht;export{xt as a,w as b,j as c,ht as d,St as e};
1
+ import{t as N}from"./chunk-KKJW6HJA.js";import{a as J}from"./chunk-V6JSMX5A.js";import{tool as ot}from"ai";import{z as M}from"zod";import{z as p}from"zod";function j(t){if(t&&typeof t=="object"&&!t.type)return p.object({});if(t.type==="object")if(t.properties){let e={},o=t.required||[];for(let[r,n]of Object.entries(t.properties)){let a=j(n),c=n!=null&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,"default");e[r]=c?a.default(n.default):o.includes(r)?a:a.optional()}return p.object(e)}else return p.object({});else if(t.type==="array"&&t.items){let e=j(t.items);return p.array(e)}else{if(t.type==="string")return p.string();if(t.type==="number"||t.type==="integer")return p.number();if(t.type==="boolean")return p.boolean()}return p.any()}var W=/\{\{\s*secrets\.[A-Z][A-Z0-9_]*\s*\}\}/,xt=t=>W.test(t),rt=/\{\{\s*auth\.[A-Z][A-Z0-9_]*\s*\}\}/;var E=t=>W.test(t)||rt.test(t),w=t=>{let e=t.indexOf("?");return e===-1?t:`${t.slice(0,e)}?[redacted-query]`};var st=256*1024,it=3e4,ct=/\{\{\s*([^}]+?)\s*\}\}/g,at=t=>{let e=t.toLowerCase();return e.includes("token")||e.includes("secret")||e.includes("key")||e.includes("password")||e.includes("access")||e==="authorization"},ut=t=>{let e={};for(let o in t)e[o]=at(o)?"[REDACTED]":t[o];return e},I=(t,e)=>{let o=t.indexOf(".");if(o===-1)return e[t];let r=t.slice(0,o),n=t.slice(o+1);if(r in e)return N(e[r],n)},H=(t,e,o)=>t&&t.replace(ct,(r,n)=>{let a=String(n).trim();if(a.startsWith("secrets.")){let f=a.slice(8);return Object.prototype.hasOwnProperty.call(o.secrets,f)?o.secrets[f]:r}if(a.startsWith("auth.")){let f=a.slice(5);return Object.prototype.hasOwnProperty.call(o.auth,f)?o.auth[f]:r}let c=I(a,e);return c==null?"":typeof c=="string"?c:JSON.stringify(c)}),dt=/\{\{\s*((?:secrets|auth)\.[^}\s]+)\s*\}\}/g,lt=(...t)=>{let e=new Set;for(let o of t){if(o==null)continue;let r=typeof o=="string"?o:JSON.stringify(o);for(let n of r.matchAll(dt))e.add(n[1])}return[...e]},T=(t,e,o)=>{if(t==null)return t;if(typeof t=="string"){let r=t.match(/^\s*\{\{\s*([^}]+?)\s*\}\}\s*$/);if(r){let n=r[1].trim();if(n.startsWith("secrets.")){let c=n.slice(8);return Object.prototype.hasOwnProperty.call(o.secrets,c)?o.secrets[c]:t}if(n.startsWith("auth.")){let c=n.slice(5);return Object.prototype.hasOwnProperty.call(o.auth,c)?o.auth[c]:t}return I(n,e)}return H(t,e,o)}if(Array.isArray(t))return t.map(r=>T(r,e,o));if(typeof t=="object"){let r={};for(let n in t)r[n]=T(t[n],e,o);return r}return t},ft=(t,e)=>t?e?/^https?:\/\//i.test(e)?e:t.endsWith("/")&&e.startsWith("/")?t+e.slice(1):!t.endsWith("/")&&!e.startsWith("/")?`${t}/${e}`:t+e:t:e||"",pt=(t,e)=>{if(!e)return t;let o=new URL(t);for(let r in e){let n=e[r];n!==void 0&&(Array.isArray(n)?o.searchParams.set(r,n.join(",")):o.searchParams.set(r,String(n)))}return o.toString()},K=t=>{if(!t)return{};let e={};for(let o in t)t[o]!==void 0&&(e[o]=t[o]);return e},yt=t=>{let e={};for(let o in t){let r=t[o];r!=null&&(e[o]=typeof r=="string"?r:String(r))}return e},gt=(t,e,o)=>{if(!(!t||t.type==="none"||!t.value)){if(t.type==="bearer"){e.Authorization=`Bearer ${t.value}`;return}if(t.type==="apiKey"){let r=t.in||"header",n=t.param||t.header||"X-API-Key";r==="query"?o[n]=t.value:e[n]=t.value}}},mt=(t,e)=>{let o=new TextEncoder().encode(t);if(o.byteLength<=e)return{text:t,truncated:!1};let r=o.slice(0,e);return{text:new TextDecoder("utf-8",{fatal:!1}).decode(r),truncated:!0}};function ht(t,e,o,r){var Z;if(t.kind!=="http")throw new Error(`customHttpTool: unsupported kind '${t.kind}' for tool '${t.name}'`);let n=t.execution||{},a=n.actions&&typeof n.actions=="object"?Object.keys(n.actions):[],c=((Z=n.router)==null?void 0:Z.field)||"action",f=t.inputSchema&&typeof t.inputSchema=="object"&&Object.keys(t.inputSchema).length>0?j(t.inputSchema):M.object({});if(a.length>0&&f instanceof M.ZodObject){let m=M.enum(a);f=f.extend({[c]:m})}let G=t.description||t.label||t.name,y=t.output||{},Q=Number.isFinite(y.maxBytes)&&y.maxBytes>0?y.maxBytes:st;return ot({description:G,inputSchema:f,execute:async m=>{var z;let h={secrets:e.secrets??{},auth:e.userAuth??{}},b={input:m??{},...o.context||{}},u=n,i;if(n.actions&&typeof n.actions=="object"){let s=((z=n.router)==null?void 0:z.field)||"action";if(i=m==null?void 0:m[s],!i||!n.actions[i])return{type:"error",error:`unknown action '${i}' for tool '${t.name}'`,natural:`Tool ${t.name} could not run: missing or unknown action.`};u=n.actions[i]}let C=u.url||ft(n.baseUrl,u.path);if(!C)return{type:"error",error:"missing url",natural:`Tool ${t.name} has no URL configured.`};let V=E(C),F=H(C,b,h),X={...n.headers||{},...u.headers||{}},g=yt(K(T(X,b,h))),Y={...n.query||{},...u.query||{}},P=K(T(Y,b,h)),$=(u.method||n.method||"GET").toUpperCase(),k,v=u.body!==void 0||n.body!==void 0;if($!=="GET"&&$!=="HEAD"&&v){let s=u.body!==void 0?u.body:n.body,d=typeof s=="string"?H(s,b,h):T(s,b,h);k=typeof d=="string"?d:JSON.stringify(d),!g["Content-Type"]&&!g["content-type"]&&(g["Content-Type"]="application/json")}let R=u.auth||n.auth,A=R?{...R,value:R.value?H(String(R.value),b,h):R.value}:void 0;gt(A,g,P);let S=pt(F,P),tt=V?w(S):S,U=lt(F,g,P,k,A==null?void 0:A.value);if(U.length>0){let s=U.map(d=>`{{ ${d} }}`).join(", ");return r==null||r({type:`error:tool:${t.name}:credentials`,content:{tool:t.name,action:i,missing:U}}),{type:"error",error:`unresolved credentials: ${s}`,natural:`Tool ${t.name} could not run because ${s} has no value in this execution. Connect the credential or use a tenant secret so unattended runs can resolve it.`}}let et=Math.min(Number.isFinite(u.timeoutMs)&&u.timeoutMs>0?u.timeoutMs:Number.isFinite(n.timeoutMs)&&n.timeoutMs>0?n.timeoutMs:15e3,it),D={tool:t.name,action:i,stage:"request",url:tt,method:$,headers:ut(g)};JSON.stringify(D),r==null||r({type:`info:tool:${t.name}:request`,content:D});let q=new AbortController,nt=setTimeout(()=>q.abort(),et);try{let s=await fetch(S,{method:$,headers:g,body:k,signal:q.signal}),d=s.headers.get("content-type")||"",O=await s.text(),{text:x,truncated:_}=mt(O,Q),l;if(y.contentType==="text"?l=x:d.includes("application/json")||y.contentType==="json"?(l=J(x),l===null&&x&&(l=x)):l=x,y.jsonPath&&l!==null&&typeof l=="object"&&(l=N(l,y.jsonPath)),!s.ok){let B={tool:t.name,action:i,stage:"http_error",status:s.status};return JSON.stringify(B),r==null||r({type:`error:tool:${t.name}:http`,content:B}),{type:"error",status:s.status,error:`HTTP ${s.status}: ${s.statusText}`,result:l,truncated:_,natural:`${t.name}${i?`:${i}`:""} failed with HTTP ${s.status}.`}}let L={tool:t.name,action:i,stage:"finish",status:s.status,truncated:_};return JSON.stringify(L),r==null||r({type:`info:tool:${t.name}:finish`,content:L}),{type:i||t.name,status:s.status,result:l,truncated:_,natural:`${t.name}${i?`:${i}`:""} completed (HTTP ${s.status}).`}}catch(s){let d=String((s==null?void 0:s.message)??s),O={tool:t.name,action:i,stage:"error",error:d};return JSON.stringify(O),r==null||r({type:`error:tool:${t.name}:execution`,content:O}),{type:"error",error:d,natural:`${t.name}${i?`:${i}`:""} failed: ${d}`}}finally{clearTimeout(nt)}}})}var St=ht;export{xt as a,w as b,j as c,ht as d,St as e};
package/dist/client.js CHANGED
@@ -1 +1 @@
1
- import{a as ut,b as dt}from"./chunk-RFWFJGER.js";import{A as Je,B as Ge,C as $e,D as Le,E as Ye,F as ke,G as Ke,H as Qe,I as Xe,J as ze,K as Be,L as We,M as Ze,N as et,O as tt,P as nt,Q as st,R as ot,S as rt,T as at,U as it,V as gt,W as lt,X as pt,Y as ct,a as u,b as Q,c as T,d as X,e as z,f as B,g as W,h as Z,i as ee,j as te,k as ne,l as se,m as oe,n as re,o as ae,p as ie,q as ge,r as le,s as pe,t as ce,u as ue,v as de,w as He,x as je,y as Ue,z as Pe}from"./chunk-6JUKM6LT.js";import{A as Fe,B as De,a as $,b as L,c as Y,d as k,e as K,f as ve,g as ye,h as me,i as Se,j as fe,k as Ae,l as Re,m as Me,n as Ee,o as Te,p as Ie,q as Ce,r as he,s as we,t as xe,u as _e,v as be,w as Ne,x as Oe,y as qe,z as Ve}from"./chunk-QEZQZG6Z.js";import{a as G}from"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";import{useAgent as U}from"agents/react";import{useCallback as d,useEffect as P,useMemo as J,useRef as m}from"react";import{create as F}from"zustand";import{devtools as D}from"zustand/middleware";var H={messages:[],events:[],eventsVisible:!1,status:"connecting",typingMessage:null,reasoningMessage:null,reasoningMessages:[],isReasoning:!1,stepInfo:null,approvals:[],error:null,flowConfig:null,composioAuth:null};function C(n){return F()(D((t,y)=>({...H,initHistory:e=>t({messages:e}),addEvent:e=>t(o=>({events:[...o.events,{...e,ts:Date.now()}]})),clearEvents:()=>t({events:[]}),setMessages:e=>{t({messages:e})},addMessage:e=>{t(o=>({messages:[...o.messages,e]}))},setTyping:e=>t({typingMessage:e}),appendTyping:(e,o)=>{let r=y().typingMessage;r&&r.id===e?t({typingMessage:{id:e,text:r.text+o}}):t({typingMessage:{id:e,text:o}})},clearTyping:()=>t({typingMessage:null}),setReasoning:e=>t({reasoningMessage:e}),appendReasoning:(e,o)=>{let r=y().reasoningMessage;r&&r.id===e?t({reasoningMessage:{id:e,text:r.text+o}}):t({reasoningMessage:{id:e,text:o}})},commitReasoning:e=>{t(o=>{var r;return(r=o.reasoningMessage)!=null&&r.text?{reasoningMessages:[...o.reasoningMessages,{...o.reasoningMessage,ts:e??Date.now()}],reasoningMessage:null,isReasoning:!1}:{reasoningMessage:null,isReasoning:!1}})},clearReasoning:()=>t({reasoningMessage:null,isReasoning:!1}),setReasoningMessages:e=>t({reasoningMessages:e}),setReasoningActive:e=>t({isReasoning:e}),setStep:e=>t({stepInfo:e}),clearStep:()=>t({stepInfo:null}),setStatus:e=>t({status:e}),toggleEvents:()=>t(e=>({eventsVisible:!e.eventsVisible})),clearHistory:()=>t({messages:[],typingMessage:null,reasoningMessage:null,reasoningMessages:[],isReasoning:!1,stepInfo:null}),addApprovalRequest:e=>{let o={id:`approval-${Date.now()}-${Math.random()}`,toolCallId:e.toolCallId,toolName:e.toolName,args:e.args??{},description:e.description,ts:Date.now(),status:"pending"};t(r=>({approvals:[...r.approvals,o]}))},updateApprovalStatus:({toolCallId:e,status:o})=>{t(r=>({approvals:r.approvals.map(v=>v.toolCallId===e?{...v,status:o}:v)}))},removeApproval:e=>{t(o=>({approvals:o.approvals.filter(r=>r.toolCallId!==e)}))},setError:e=>t({error:e}),setFlowConfig:e=>t({flowConfig:e}),setComposioAuth:e=>t({composioAuth:e}),clearComposioAuth:()=>t({composioAuth:null})}),{name:n,enabled:!0}))}var j=C("agent-store"),I=new Map;function h(n){if(!n)return j;let t=I.get(n);return t||(t=C(`agent-store:${n}`),I.set(n,t)),t}function Et(n){let t=J(()=>h(n==null?void 0:n.storeKey),[n==null?void 0:n.storeKey]),y=t(s=>s.typingMessage),e=m(null),o=m(null),r=m(null),v=m(0),S=m(null),f=()=>(v.current=Math.max(Date.now(),v.current+1),v.current);P(()=>{e.current=y},[y]);let A=d(s=>{var g;let i=s.trim().slice(0,T);!i||typeof((g=S.current)==null?void 0:g.send)!="function"||S.current.send(u.USER_IDENTITY+":"+i)},[]),l=U({host:n==null?void 0:n.host,basePath:(n==null?void 0:n.basePath)??"/api/agents/base",agent:n==null?void 0:n.agent,name:n==null?void 0:n.name,query:n==null?void 0:n.query,protocol:n==null?void 0:n.protocol,onMessage:s=>{if(typeof s.data!="string")return;let[i,g]=s.data.split("::");if(!i||!g)return;let a=t.getState(),R={[u.SERVER_HISTORY]:p=>{let c=JSON.parse(p);a.setMessages(c.messages),a.setReasoningMessages([])},[u.SERVER_EVENT]:p=>{var E;let c=JSON.parse(p);if((c==null?void 0:c.type)==="info:composio:auth_required"&&((E=c==null?void 0:c.content)!=null&&E.redirectUrl)){let M=c.content;a.setComposioAuth({toolkit:M.toolkit,redirectUrl:M.redirectUrl,toolRowId:M.toolRowId})}a.addEvent({type:"server",...c})},[u.SERVER_ERROR]:p=>{a.setError(p),a.addEvent({type:"error",content:p})},[u.SERVER_TEXT_STREAM]:p=>{o.current?a.appendTyping(o.current,p):(o.current=String(Date.now()),a.setTyping({id:o.current,text:p}))},[u.SERVER_TEXT_STREAM_COMPLETE]:p=>{if(a.setReasoningActive(!1),o.current&&a.typingMessage){let c=a.typingMessage.text;a.addMessage({role:"assistant",type:"text",content:c,id:o.current,ts:f()}),a.clearTyping(),o.current=null}},[u.SERVER_REASONING_STREAM]:p=>{a.setReasoningActive(!0),r.current?a.appendReasoning(r.current,p):(r.current=String(Date.now()),a.setReasoning({id:r.current,text:p}))},[u.SERVER_REASONING_STREAM_COMPLETE]:()=>{a.commitReasoning(f()),r.current=null},[u.SERVER_CONFIG]:p=>{a.setFlowConfig(JSON.parse(p))}};R[i]&&R[i](g)},onOpen:()=>{let s=t.getState();s.setStatus("connected"),s.clearTyping(),o.current=null,s.clearReasoning(),r.current=null,s.clearStep(),s.addEvent({type:"connection",content:"Connected to Agent Server"}),n!=null&&n.user&&A(n.user)},onClose:()=>{let s=t.getState();s.setStatus("disconnected"),s.setFlowConfig(null),s.addEvent({type:"connection",content:"Connection closed"})}});S.current=l;let w=d((s,i,g)=>{let a=s.trim();if(!a&&(!i||i.length===0)&&(!g||g.length===0))return;let p=((i==null?void 0:i.length)??0)>0||((g==null?void 0:g.length)??0)>0?JSON.stringify({text:a,images:i,documents:g}):a;l.send(u.USER_MESSAGE+":"+p);let c=t.getState();r.current=null,c.clearReasoning(),c.addMessage({id:String(Date.now())+Math.random(),role:"user",type:"text",content:a,images:i,ts:f()})},[l]),x=d(()=>{t.getState().clearHistory(),l.send(u.USER_CLEAR_HISTORY+":1")},[l]),_=d((s,i)=>{let g=s.trim();g&&l.send(u.USER_AUTH+":"+JSON.stringify({name:g,value:i}))},[l]),b=d(s=>{A(s)},[A]),N=d(()=>t.getState().toggleEvents(),[]),O=d(()=>t.getState().clearEvents(),[]),q=d(s=>{let i=t.getState();i.updateApprovalStatus({toolCallId:s,status:"approved"});let g=JSON.stringify({type:"tool_approval",toolCallId:s,approved:!0});typeof(l==null?void 0:l.send)=="function"&&l.send(g),i.addEvent({type:"approval",content:`Approved tool call ${s}`,ts:Date.now()})},[l]),V=d(s=>{let i=t.getState();i.updateApprovalStatus({toolCallId:s,status:"rejected"});let g=JSON.stringify({type:"tool_approval",toolCallId:s,approved:!1});typeof(l==null?void 0:l.send)=="function"&&l.send(g),i.addEvent({type:"approval",content:`Rejected tool call ${s}`,ts:Date.now()})},[l]);return{connection:l,store:t,send:w,clearHistory:x,sendAuth:_,setIdentity:b,toggleEventsVisible:N,clearEvents:O,approve:q,reject:V}}export{Ue as CRAWL_DEFAULTS,Pe as CRAWL_LIMITS,Z as DEFAULT_MEMORY_LENGTH,ee as DEFAULT_MEMORY_MODEL,L as FLOW_INPUT_NAME_RE,Ye as GENERATION_PARAM_KEYS,Ke as GENERATION_PRESETS,T as MAX_USER_IDENTITY_LENGTH,B as MEMORY_LENGTH_MD_LINES,W as MEMORY_LENGTH_TOKENS,ut as MODEL_REGISTRY_SNAPSHOT,$ as NodeType,ve as OUT_VAR_NAME_RE,ke as PRESET_PARAM_KEYS,rt as REASONING_EFFORT_LEVELS,He as TENANT_ONLY_NODES,ct as TOOL_REGISTRY_SNAPSHOT,we as VariableResolutionError,ze as applyPresetToOverrides,Je as buildCrawlRequestBody,pt as buildReasoningProviderOptions,Re as buildScope,K as buildTriggerMessageText,re as capMemoryContent,Ge as crawlRequestKey,Qe as deriveParamSupport,oe as estimateTokens,be as extractOutVarValues,Ve as extractTemplateReferences,ue as extractUserKeypoints,Me as findScopedSourceNode,h as getAgentStore,fe as getAncestorNodeIds,ye as getDefaultOutVars,Se as getEffectiveOutVars,Y as getFlowInputDefs,dt as getModelEntry,Ee as getRefTail,Ae as getUpstreamOutVars,Te as isBinaryOutVar,Ie as isJsonContentType,je as isNodeTypeAllowedForTenant,ae as isStartMemoryEnabled,G as logc,pe as looksLikeTranscript,le as memoryGenerationMaxTokens,se as memoryMdLineLimit,ne as memoryTokenLimit,de as mergeKeypointMemory,u as messageTypes,We as normalizeEffectiveParams,k as normalizeFlowInputs,at as normalizeReasoning,tt as openAiReasoningParamSupport,et as openAiStandardParamSupport,te as parseMemoryLength,Ce as parsePayloadText,qe as parseTemplateExpression,z as parseUserAuth,Q as parseUserMessage,Be as pickNodeOverrides,he as readFetchPayload,it as reasoningEffortLevels,gt as reasoningExposable,Oe as resolveOutVarRef,_e as resolveOutVarValue,Xe as resolvePreset,lt as resolveReasoningEffort,Ne as resolveReference,De as resolveTemplate,Fe as rewriteTemplateNodeRefs,Le as runCrawl,ce as sanitizeMemoryDocument,X as sanitizeUserIdentity,$e as shapeCrawlOutput,ge as startMemoryLength,ie as startMemoryModel,ot as stripUnsupportedFromNodeData,Ze as toStreamTextSettings,Et as useAgent,j as useAgentStore,me as validateOutVars,xe as walkPath,st as workersAiParamSupport,nt as xaiParamSupport};
1
+ import{a as Et,b as Tt,c as It,d as Ct}from"./chunk-S2CXL35V.js";import{$ as vt,A as fe,B as Ge,C as $e,D as Le,E as Ye,F as ke,G as Ke,H as Qe,I as Xe,J as ze,K as Be,L as We,M as Ze,N as et,O as tt,P as nt,Q as st,R as ot,S as rt,T as at,U as it,V as gt,W as lt,X as pt,Y as ct,Z as ut,_ as dt,a as u,aa as yt,b as Q,ba as mt,c as T,ca as St,d as X,da as ft,e as z,ea as At,f as B,fa as Rt,g as W,ga as Mt,h as Z,i as ee,j as te,k as ne,l as se,m as oe,n as re,o as ae,p as ie,q as ge,r as le,s as pe,t as ce,u as ue,v as de,w as ve,x as ye,y as me,z as Se}from"./chunk-P6YUTKRM.js";import{A as Pe,B as Je,a as $,b as L,c as Y,d as k,e as K,f as Ae,g as Re,h as Me,i as Ee,j as Te,k as Ie,l as Ce,m as he,n as we,o as xe,p as _e,q as be,r as Ne,s as Oe,t as qe,u as Ve,v as Fe,w as De,x as He,y as je,z as Ue}from"./chunk-KKJW6HJA.js";import{a as G}from"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";import{useAgent as U}from"agents/react";import{useCallback as d,useEffect as P,useMemo as J,useRef as m}from"react";import{create as F}from"zustand";import{devtools as D}from"zustand/middleware";var H={messages:[],events:[],eventsVisible:!1,status:"connecting",typingMessage:null,reasoningMessage:null,reasoningMessages:[],isReasoning:!1,stepInfo:null,approvals:[],error:null,flowConfig:null,composioAuth:null};function C(n){return F()(D((t,y)=>({...H,initHistory:e=>t({messages:e}),addEvent:e=>t(o=>({events:[...o.events,{...e,ts:Date.now()}]})),clearEvents:()=>t({events:[]}),setMessages:e=>{t({messages:e})},addMessage:e=>{t(o=>({messages:[...o.messages,e]}))},setTyping:e=>t({typingMessage:e}),appendTyping:(e,o)=>{let r=y().typingMessage;r&&r.id===e?t({typingMessage:{id:e,text:r.text+o}}):t({typingMessage:{id:e,text:o}})},clearTyping:()=>t({typingMessage:null}),setReasoning:e=>t({reasoningMessage:e}),appendReasoning:(e,o)=>{let r=y().reasoningMessage;r&&r.id===e?t({reasoningMessage:{id:e,text:r.text+o}}):t({reasoningMessage:{id:e,text:o}})},commitReasoning:e=>{t(o=>{var r;return(r=o.reasoningMessage)!=null&&r.text?{reasoningMessages:[...o.reasoningMessages,{...o.reasoningMessage,ts:e??Date.now()}],reasoningMessage:null,isReasoning:!1}:{reasoningMessage:null,isReasoning:!1}})},clearReasoning:()=>t({reasoningMessage:null,isReasoning:!1}),setReasoningMessages:e=>t({reasoningMessages:e}),setReasoningActive:e=>t({isReasoning:e}),setStep:e=>t({stepInfo:e}),clearStep:()=>t({stepInfo:null}),setStatus:e=>t({status:e}),toggleEvents:()=>t(e=>({eventsVisible:!e.eventsVisible})),clearHistory:()=>t({messages:[],typingMessage:null,reasoningMessage:null,reasoningMessages:[],isReasoning:!1,stepInfo:null}),addApprovalRequest:e=>{let o={id:`approval-${Date.now()}-${Math.random()}`,toolCallId:e.toolCallId,toolName:e.toolName,args:e.args??{},description:e.description,ts:Date.now(),status:"pending"};t(r=>({approvals:[...r.approvals,o]}))},updateApprovalStatus:({toolCallId:e,status:o})=>{t(r=>({approvals:r.approvals.map(v=>v.toolCallId===e?{...v,status:o}:v)}))},removeApproval:e=>{t(o=>({approvals:o.approvals.filter(r=>r.toolCallId!==e)}))},setError:e=>t({error:e}),setFlowConfig:e=>t({flowConfig:e}),setComposioAuth:e=>t({composioAuth:e}),clearComposioAuth:()=>t({composioAuth:null})}),{name:n,enabled:!0}))}var j=C("agent-store"),I=new Map;function h(n){if(!n)return j;let t=I.get(n);return t||(t=C(`agent-store:${n}`),I.set(n,t)),t}function Vt(n){let t=J(()=>h(n==null?void 0:n.storeKey),[n==null?void 0:n.storeKey]),y=t(s=>s.typingMessage),e=m(null),o=m(null),r=m(null),v=m(0),S=m(null),f=()=>(v.current=Math.max(Date.now(),v.current+1),v.current);P(()=>{e.current=y},[y]);let A=d(s=>{var g;let i=s.trim().slice(0,T);!i||typeof((g=S.current)==null?void 0:g.send)!="function"||S.current.send(u.USER_IDENTITY+":"+i)},[]),l=U({host:n==null?void 0:n.host,basePath:(n==null?void 0:n.basePath)??"/api/agents/base",agent:n==null?void 0:n.agent,name:n==null?void 0:n.name,query:n==null?void 0:n.query,protocol:n==null?void 0:n.protocol,onMessage:s=>{if(typeof s.data!="string")return;let[i,g]=s.data.split("::");if(!i||!g)return;let a=t.getState(),R={[u.SERVER_HISTORY]:p=>{let c=JSON.parse(p);a.setMessages(c.messages),a.setReasoningMessages([])},[u.SERVER_EVENT]:p=>{var E;let c=JSON.parse(p);if((c==null?void 0:c.type)==="info:composio:auth_required"&&((E=c==null?void 0:c.content)!=null&&E.redirectUrl)){let M=c.content;a.setComposioAuth({toolkit:M.toolkit,redirectUrl:M.redirectUrl,toolRowId:M.toolRowId})}a.addEvent({type:"server",...c})},[u.SERVER_ERROR]:p=>{a.setError(p),a.addEvent({type:"error",content:p})},[u.SERVER_TEXT_STREAM]:p=>{o.current?a.appendTyping(o.current,p):(o.current=String(Date.now()),a.setTyping({id:o.current,text:p}))},[u.SERVER_TEXT_STREAM_COMPLETE]:p=>{if(a.setReasoningActive(!1),o.current&&a.typingMessage){let c=a.typingMessage.text;a.addMessage({role:"assistant",type:"text",content:c,id:o.current,ts:f()}),a.clearTyping(),o.current=null}},[u.SERVER_REASONING_STREAM]:p=>{a.setReasoningActive(!0),r.current?a.appendReasoning(r.current,p):(r.current=String(Date.now()),a.setReasoning({id:r.current,text:p}))},[u.SERVER_REASONING_STREAM_COMPLETE]:()=>{a.commitReasoning(f()),r.current=null},[u.SERVER_CONFIG]:p=>{a.setFlowConfig(JSON.parse(p))}};R[i]&&R[i](g)},onOpen:()=>{let s=t.getState();s.setStatus("connected"),s.clearTyping(),o.current=null,s.clearReasoning(),r.current=null,s.clearStep(),s.addEvent({type:"connection",content:"Connected to Agent Server"}),n!=null&&n.user&&A(n.user)},onClose:()=>{let s=t.getState();s.setStatus("disconnected"),s.setFlowConfig(null),s.addEvent({type:"connection",content:"Connection closed"})}});S.current=l;let w=d((s,i,g)=>{let a=s.trim();if(!a&&(!i||i.length===0)&&(!g||g.length===0))return;let p=((i==null?void 0:i.length)??0)>0||((g==null?void 0:g.length)??0)>0?JSON.stringify({text:a,images:i,documents:g}):a;l.send(u.USER_MESSAGE+":"+p);let c=t.getState();r.current=null,c.clearReasoning(),c.addMessage({id:String(Date.now())+Math.random(),role:"user",type:"text",content:a,images:i,ts:f()})},[l]),x=d(()=>{t.getState().clearHistory(),l.send(u.USER_CLEAR_HISTORY+":1")},[l]),_=d((s,i)=>{let g=s.trim();g&&l.send(u.USER_AUTH+":"+JSON.stringify({name:g,value:i}))},[l]),b=d(s=>{A(s)},[A]),N=d(()=>t.getState().toggleEvents(),[]),O=d(()=>t.getState().clearEvents(),[]),q=d(s=>{let i=t.getState();i.updateApprovalStatus({toolCallId:s,status:"approved"});let g=JSON.stringify({type:"tool_approval",toolCallId:s,approved:!0});typeof(l==null?void 0:l.send)=="function"&&l.send(g),i.addEvent({type:"approval",content:`Approved tool call ${s}`,ts:Date.now()})},[l]),V=d(s=>{let i=t.getState();i.updateApprovalStatus({toolCallId:s,status:"rejected"});let g=JSON.stringify({type:"tool_approval",toolCallId:s,approved:!1});typeof(l==null?void 0:l.send)=="function"&&l.send(g),i.addEvent({type:"approval",content:`Rejected tool call ${s}`,ts:Date.now()})},[l]);return{connection:l,store:t,send:w,clearHistory:x,sendAuth:_,setIdentity:b,toggleEventsVisible:N,clearEvents:O,approve:q,reject:V}}export{W as CLASSIFIER_DEFAULTS,Z as CLASSIFIER_RESERVED_HANDLES,B as CLEF_MODELS,Ge as CRAWL_DEFAULTS,$e as CRAWL_LIMITS,oe as DEFAULT_MEMORY_LENGTH,re as DEFAULT_MEMORY_MODEL,L as FLOW_INPUT_NAME_RE,nt as GENERATION_PARAM_KEYS,ot as GENERATION_PRESETS,T as MAX_USER_IDENTITY_LENGTH,ne as MEMORY_LENGTH_MD_LINES,se as MEMORY_LENGTH_TOKENS,Et as MODEL_REGISTRY_SNAPSHOT,$ as NodeType,Ae as OUT_VAR_NAME_RE,st as PRESET_PARAM_KEYS,mt as REASONING_EFFORT_LEVELS,It as TENANT_ONLY_NODES,tt as TOOL_REGISTRY_SNAPSHOT,Oe as VariableResolutionError,it as applyPresetToOverrides,Qe as buildClefRequest,Le as buildCrawlRequestBody,Mt as buildReasoningProviderOptions,Ce as buildScope,K as buildTriggerMessageText,pe as capMemoryContent,Ze as classifierErrorResult,ee as classifierHandle,ze as clefTruncationWarning,Ye as crawlRequestKey,rt as deriveParamSupport,Xe as estimateClefTokens,le as estimateTokens,Fe as extractOutVarValues,Ue as extractTemplateReferences,Se as extractUserKeypoints,he as findScopedSourceNode,h as getAgentStore,Te as getAncestorNodeIds,Re as getDefaultOutVars,Ee as getEffectiveOutVars,Y as getFlowInputDefs,Tt as getModelEntry,we as getRefTail,Ie as getUpstreamOutVars,xe as isBinaryOutVar,_e as isJsonContentType,Ct as isNodeTypeAllowedForTenant,ce as isStartMemoryEnabled,G as logc,ye as looksLikeTranscript,ve as memoryGenerationMaxTokens,ge as memoryMdLineLimit,ie as memoryTokenLimit,fe as mergeKeypointMemory,u as messageTypes,lt as normalizeEffectiveParams,k as normalizeFlowInputs,St as normalizeReasoning,ut as openAiReasoningParamSupport,ct as openAiStandardParamSupport,We as parseClefResponse,ae as parseMemoryLength,be as parsePayloadText,je as parseTemplateExpression,z as parseUserAuth,Q as parseUserMessage,gt as pickNodeOverrides,Ne as readFetchPayload,ft as reasoningEffortLevels,At as reasoningExposable,He as resolveOutVarRef,Ve as resolveOutVarValue,at as resolvePreset,Rt as resolveReasoningEffort,De as resolveReference,Je as resolveTemplate,Pe as rewriteTemplateNodeRefs,Be as runClef,Ke as runCrawl,me as sanitizeMemoryDocument,X as sanitizeUserIdentity,et as selectClefHistory,ke as shapeCrawlOutput,de as startMemoryLength,ue as startMemoryModel,yt as stripUnsupportedFromNodeData,pt as toStreamTextSettings,Vt as useAgent,j as useAgentStore,te as validateClassifierData,Me as validateOutVars,qe as walkPath,vt as workersAiParamSupport,dt as xaiParamSupport};
@@ -0,0 +1,48 @@
1
+ import type { ClassifierRoute } from '../types/classifier-types';
2
+ export declare const CLEF_MODELS: {
3
+ readonly 'clef-omni': {
4
+ readonly id: '@cf/cloudflare/clef-omni';
5
+ readonly contextWindow: 65529;
6
+ readonly pricePerMillionInputTokens: 0.15;
7
+ };
8
+ readonly clef: {
9
+ readonly id: '@cf/cloudflare/clef';
10
+ readonly contextWindow: 65536;
11
+ readonly pricePerMillionInputTokens: 0.24;
12
+ };
13
+ readonly 'clef-flash': {
14
+ readonly id: '@cf/cloudflare/clef-flash';
15
+ readonly contextWindow: 24576;
16
+ readonly pricePerMillionInputTokens: 0.038;
17
+ };
18
+ };
19
+ export declare const CLASSIFIER_DEFAULTS: {
20
+ readonly model: 'clef-omni';
21
+ readonly question: '';
22
+ readonly options: readonly [{
23
+ readonly id: 'option';
24
+ readonly label: '';
25
+ readonly criteria: '';
26
+ }, {
27
+ readonly id: 'option_2';
28
+ readonly label: '';
29
+ readonly criteria: '';
30
+ }];
31
+ readonly checks: readonly [];
32
+ readonly input: {
33
+ readonly message: 'user_input';
34
+ readonly historyTurns: 3;
35
+ readonly vars: string[];
36
+ };
37
+ readonly confidence: {
38
+ readonly threshold: 0.6;
39
+ readonly margin: 0.15;
40
+ };
41
+ };
42
+ export declare const CLASSIFIER_RESERVED_HANDLES: {
43
+ readonly uncertain: 'source-__uncertain';
44
+ readonly blocked: 'source-__blocked';
45
+ readonly error: 'source-__error';
46
+ };
47
+ /** Pass ('class', id) for class ids that also happen to be route names. */
48
+ export declare function classifierHandle(routeOrClassId: ClassifierRoute | string, classId?: string): string;
@@ -1,4 +1,4 @@
1
1
  import { NodeType } from '../types/node-types';
2
- /** Node types only available to specific tenants (designer palette + runtime where applicable). */
2
+ /** Node types are available across environments. Retained for existing consumers. */
3
3
  export declare const TENANT_ONLY_NODES: Partial<Record<NodeType, readonly string[]>>;
4
4
  export declare function isNodeTypeAllowedForTenant(type: string, tenant: string | null | undefined): boolean;
@@ -0,0 +1,57 @@
1
+ import type { OutVar } from './var-scope';
2
+ export type ClefModel = 'clef-omni' | 'clef' | 'clef-flash';
3
+ export type ClassifierRoute = 'class' | 'uncertain' | 'blocked' | 'error';
4
+ export type ClassifierCheck = {
5
+ id: string;
6
+ type: 'noul';
7
+ instructions: string;
8
+ criteria?: {
9
+ true?: string;
10
+ false?: string;
11
+ };
12
+ guard?: {
13
+ threshold: number;
14
+ };
15
+ } | {
16
+ id: string;
17
+ type: 'score';
18
+ instructions: string;
19
+ levels: string[];
20
+ };
21
+ export interface ClassifierData {
22
+ label?: string;
23
+ model: ClefModel;
24
+ question: string;
25
+ input: {
26
+ message: string;
27
+ historyTurns: number;
28
+ vars: string[];
29
+ };
30
+ options: Array<{
31
+ id: string;
32
+ label: string;
33
+ criteria: string;
34
+ }>;
35
+ checks: ClassifierCheck[];
36
+ confidence: {
37
+ threshold: number;
38
+ margin: number;
39
+ };
40
+ outVars?: OutVar[];
41
+ }
42
+ export interface ClassifierScore {
43
+ score: number;
44
+ /** Description of the highest probability level (levels are zero indexed). */
45
+ level: string;
46
+ confidence: number;
47
+ probabilities: Record<string, number>;
48
+ }
49
+ export interface ClassifierResult {
50
+ classification: string;
51
+ label: string;
52
+ confidence: number;
53
+ margin: number;
54
+ probabilities: Record<string, number>;
55
+ route: ClassifierRoute;
56
+ checks: Record<string, number | ClassifierScore>;
57
+ }
@@ -0,0 +1,2 @@
1
+ /** Runtime-safe shared validation; returns all authoring errors without throwing. */
2
+ export declare function validateClassifierData(data: unknown): string[];
@@ -0,0 +1,16 @@
1
+ import type { ClefModel } from '../types/classifier-types';
2
+ /** Prefixes inside a prose run are excluded: completing the run would lower B.
3
+ * Costs at the remaining boundaries are monotone and exact before rounding.
4
+ * Offsets refer to the original string and never split a surrogate pair.
5
+ */
6
+ export declare function clefPrefixCosts(value: string, model: ClefModel): {
7
+ boundaries: {
8
+ end: number;
9
+ encodedEnd: number;
10
+ bytes: number;
11
+ }[];
12
+ cuts: {
13
+ index: number;
14
+ hundredths: number;
15
+ }[];
16
+ };
@@ -0,0 +1,49 @@
1
+ import type { ClassifierData, ClassifierResult, ClefModel } from '../types/classifier-types';
2
+ /** Minimal Workers AI contract; independent of generated Env and server modules. */
3
+ export interface ClefAiBinding {
4
+ run(model: string, input: unknown, opts?: unknown): Promise<unknown>;
5
+ }
6
+ export interface ClefHistoryMessage {
7
+ role: 'user' | 'assistant';
8
+ type: string;
9
+ content: unknown;
10
+ }
11
+ export interface ClefState {
12
+ message: string;
13
+ history: Array<{
14
+ role: 'user' | 'assistant';
15
+ text: string;
16
+ }>;
17
+ vars: Record<string, unknown>;
18
+ }
19
+ declare const TRUNCATION_WARNING: unique symbol;
20
+ export interface ClefRequest extends Record<string, unknown> {
21
+ readonly [TRUNCATION_WARNING]?: string;
22
+ model: ClefModel;
23
+ state: ClefState;
24
+ questions: Record<string, unknown>;
25
+ }
26
+ export interface ClefUsage {
27
+ promptTokens: number;
28
+ completionTokens: 0;
29
+ totalTokens: number;
30
+ }
31
+ export interface ParsedClefResponse {
32
+ result: ClassifierResult;
33
+ usage: ClefUsage;
34
+ }
35
+ export declare function buildClefRequest(data: ClassifierData, state: ClefState): ClefRequest;
36
+ /** Lab Formula B: prose/dense UTF-8 bytes plus question/option template overhead.
37
+ * Calibrated against real usage; not a universal tokenizer bound.
38
+ */
39
+ export declare function estimateClefTokens(request: ClefRequest): number;
40
+ export declare function clefTruncationWarning(request: ClefRequest): string | undefined;
41
+ export declare function runClef(ai: ClefAiBinding, model: ClefModel, request: ClefRequest, { timeoutMs }?: {
42
+ timeoutMs?: number;
43
+ }): Promise<unknown>;
44
+ /** Official schema: answers.route.choice, noul.noul, score.score/legend/probabilities. */
45
+ export declare function parseClefResponse(response: unknown, data: ClassifierData): ParsedClefResponse;
46
+ export declare function classifierErrorResult(): ClassifierResult;
47
+ /** A turn starts at a user message. Excludes the current persisted user message when provided. */
48
+ export declare function selectClefHistory(messages: ClefHistoryMessage[], turns: number, currentMessage?: unknown): ClefState['history'];
49
+ export {};
package/dist/common.d.ts CHANGED
@@ -19,3 +19,7 @@ export * from './common/utils/agentMemory';
19
19
  export * from './common/types/crawl-types';
20
20
  export * from './common/utils/crawlClient';
21
21
  export * from './common/constants/tenant-only-nodes';
22
+ export * from './common/types/classifier-types';
23
+ export * from './common/types/classifier-validation';
24
+ export * from './common/constants/clef-models';
25
+ export * from './common/utils/clef';
package/dist/common.js CHANGED
@@ -1 +1 @@
1
- import{a as Aa,b as Ba}from"./chunk-RFWFJGER.js";import{A as ba,B as ca,C as da,D as ea,E as fa,F as ga,G as ha,H as ia,I as ja,J as ka,K as la,L as ma,M as na,N as oa,O as pa,P as qa,Q as ra,R as sa,S as ta,T as ua,U as va,V as wa,W as xa,X as ya,Y as za,a as b,b as h,c as i,d as j,e as k,f as l,g as m,h as n,i as o,j as p,k as q,l as r,m as s,n as t,o as u,p as v,q as w,r as x,s as y,t as z,u as A,v as B,w as Z,x as _,y as $,z as aa}from"./chunk-6JUKM6LT.js";import{A as X,B as Y,a as c,b as d,c as e,d as f,e as g,f as C,g as D,h as E,i as F,j as G,k as H,l as I,m as J,n as K,o as L,p as M,q as N,r as O,s as P,t as Q,u as R,v as S,w as T,x as U,y as V,z as W}from"./chunk-QEZQZG6Z.js";import{a}from"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{$ as CRAWL_DEFAULTS,aa as CRAWL_LIMITS,n as DEFAULT_MEMORY_LENGTH,o as DEFAULT_MEMORY_MODEL,d as FLOW_INPUT_NAME_RE,fa as GENERATION_PARAM_KEYS,ha as GENERATION_PRESETS,i as MAX_USER_IDENTITY_LENGTH,l as MEMORY_LENGTH_MD_LINES,m as MEMORY_LENGTH_TOKENS,Aa as MODEL_REGISTRY_SNAPSHOT,c as NodeType,C as OUT_VAR_NAME_RE,ga as PRESET_PARAM_KEYS,ta as REASONING_EFFORT_LEVELS,Z as TENANT_ONLY_NODES,za as TOOL_REGISTRY_SNAPSHOT,P as VariableResolutionError,ka as applyPresetToOverrides,ba as buildCrawlRequestBody,ya as buildReasoningProviderOptions,I as buildScope,g as buildTriggerMessageText,t as capMemoryContent,ca as crawlRequestKey,ia as deriveParamSupport,s as estimateTokens,S as extractOutVarValues,W as extractTemplateReferences,A as extractUserKeypoints,J as findScopedSourceNode,G as getAncestorNodeIds,D as getDefaultOutVars,F as getEffectiveOutVars,e as getFlowInputDefs,Ba as getModelEntry,K as getRefTail,H as getUpstreamOutVars,L as isBinaryOutVar,M as isJsonContentType,_ as isNodeTypeAllowedForTenant,u as isStartMemoryEnabled,a as logc,y as looksLikeTranscript,x as memoryGenerationMaxTokens,r as memoryMdLineLimit,q as memoryTokenLimit,B as mergeKeypointMemory,b as messageTypes,ma as normalizeEffectiveParams,f as normalizeFlowInputs,ua as normalizeReasoning,pa as openAiReasoningParamSupport,oa as openAiStandardParamSupport,p as parseMemoryLength,N as parsePayloadText,V as parseTemplateExpression,k as parseUserAuth,h as parseUserMessage,la as pickNodeOverrides,O as readFetchPayload,va as reasoningEffortLevels,wa as reasoningExposable,U as resolveOutVarRef,R as resolveOutVarValue,ja as resolvePreset,xa as resolveReasoningEffort,T as resolveReference,Y as resolveTemplate,X as rewriteTemplateNodeRefs,ea as runCrawl,z as sanitizeMemoryDocument,j as sanitizeUserIdentity,da as shapeCrawlOutput,w as startMemoryLength,v as startMemoryModel,sa as stripUnsupportedFromNodeData,na as toStreamTextSettings,E as validateOutVars,Q as walkPath,ra as workersAiParamSupport,qa as xaiParamSupport};
1
+ import{a as Ka,b as La,c as Ma,d as Na}from"./chunk-S2CXL35V.js";import{$ as Ca,A as G,B as ca,C as da,D as ea,E as fa,F as ga,G as ha,H as ia,I as ja,J as ka,K as la,L as ma,M as na,N as oa,O as pa,P as qa,Q as ra,R as sa,S as ta,T as ua,U as va,V as wa,W as xa,X as ya,Y as za,Z as Aa,_ as Ba,a as b,aa as Da,b as h,ba as Ea,c as i,ca as Fa,d as j,da as Ga,e as k,ea as Ha,f as l,fa as Ia,g as m,ga as Ja,h as n,i as o,j as p,k as q,l as r,m as s,n as t,o as u,p as v,q as w,r as x,s as y,t as z,u as A,v as B,w as C,x as D,y as E,z as F}from"./chunk-P6YUTKRM.js";import{A as aa,B as ba,a as c,b as d,c as e,d as f,e as g,f as H,g as I,h as J,i as K,j as L,k as M,l as N,m as O,n as P,o as Q,p as R,q as S,r as T,s as U,t as V,u as W,v as X,w as Y,x as Z,y as _,z as $}from"./chunk-KKJW6HJA.js";import{a}from"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{m as CLASSIFIER_DEFAULTS,n as CLASSIFIER_RESERVED_HANDLES,l as CLEF_MODELS,ca as CRAWL_DEFAULTS,da as CRAWL_LIMITS,s as DEFAULT_MEMORY_LENGTH,t as DEFAULT_MEMORY_MODEL,d as FLOW_INPUT_NAME_RE,qa as GENERATION_PARAM_KEYS,sa as GENERATION_PRESETS,i as MAX_USER_IDENTITY_LENGTH,q as MEMORY_LENGTH_MD_LINES,r as MEMORY_LENGTH_TOKENS,Ka as MODEL_REGISTRY_SNAPSHOT,c as NodeType,H as OUT_VAR_NAME_RE,ra as PRESET_PARAM_KEYS,Ea as REASONING_EFFORT_LEVELS,Ma as TENANT_ONLY_NODES,pa as TOOL_REGISTRY_SNAPSHOT,U as VariableResolutionError,va as applyPresetToOverrides,ia as buildClefRequest,ea as buildCrawlRequestBody,Ja as buildReasoningProviderOptions,N as buildScope,g as buildTriggerMessageText,y as capMemoryContent,na as classifierErrorResult,o as classifierHandle,ka as clefTruncationWarning,fa as crawlRequestKey,ta as deriveParamSupport,ja as estimateClefTokens,x as estimateTokens,X as extractOutVarValues,$ as extractTemplateReferences,F as extractUserKeypoints,O as findScopedSourceNode,L as getAncestorNodeIds,I as getDefaultOutVars,K as getEffectiveOutVars,e as getFlowInputDefs,La as getModelEntry,P as getRefTail,M as getUpstreamOutVars,Q as isBinaryOutVar,R as isJsonContentType,Na as isNodeTypeAllowedForTenant,z as isStartMemoryEnabled,a as logc,D as looksLikeTranscript,C as memoryGenerationMaxTokens,w as memoryMdLineLimit,v as memoryTokenLimit,G as mergeKeypointMemory,b as messageTypes,xa as normalizeEffectiveParams,f as normalizeFlowInputs,Fa as normalizeReasoning,Aa as openAiReasoningParamSupport,za as openAiStandardParamSupport,ma as parseClefResponse,u as parseMemoryLength,S as parsePayloadText,_ as parseTemplateExpression,k as parseUserAuth,h as parseUserMessage,wa as pickNodeOverrides,T as readFetchPayload,Ga as reasoningEffortLevels,Ha as reasoningExposable,Z as resolveOutVarRef,W as resolveOutVarValue,ua as resolvePreset,Ia as resolveReasoningEffort,Y as resolveReference,ba as resolveTemplate,aa as rewriteTemplateNodeRefs,la as runClef,ha as runCrawl,E as sanitizeMemoryDocument,j as sanitizeUserIdentity,oa as selectClefHistory,ga as shapeCrawlOutput,B as startMemoryLength,A as startMemoryModel,Da as stripUnsupportedFromNodeData,ya as toStreamTextSettings,p as validateClassifierData,J as validateOutVars,V as walkPath,Ca as workersAiParamSupport,Ba as xaiParamSupport};
@@ -0,0 +1 @@
1
+ import{d as a,e as b}from"./chunk-Z4CYLB7J.js";import"./chunk-KKJW6HJA.js";import"./chunk-V6JSMX5A.js";import"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{a as customHttpTool,b as default};
package/dist/index.d.ts CHANGED
@@ -32,3 +32,4 @@ export * from './server/core/ArtifactWorkerGateway';
32
32
  export type * from './server/types/artifact';
33
33
  export * from './common';
34
34
  export * from './common/utils/logc';
35
+ export * from './server/utils/clef';
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import{a as k,b as jn,c as Pe,d as Ne,e as mr,f as Fe,g as gr,h as Le,i as hr}from"./chunk-DEW7U7V7.js";import"./chunk-V35SRZAO.js";import{c as Kn}from"./chunk-ZYIULB2P.js";import"./chunk-6AZ7RATD.js";import"./chunk-XXB57DMN.js";import"./chunk-3K4IMMLP.js";import{a as wr,b as Rr}from"./chunk-RFWFJGER.js";import{A as zn,B as Vn,C as Jn,D as Yn,E as Bn,F as Zn,G as Qn,H as er,I as tr,J as nr,K as rr,L as sr,M as Me,N as or,O as ar,P as ir,Q as cr,R as lr,S as ur,T as dr,U as pr,V as fr,W as De,X as $e,Y as yr,a as I,b as Ie,c as dn,d as P,e as xe,f as pn,g as fn,h as mn,i as gn,j as yn,k as Te,l as L,m as hn,n as ke,o as Ae,p as Ue,q as _e,r as be,s as Oe,t as J,u as ve,v as Ce,w as qn,x as Gn,y as Wn,z as Xn}from"./chunk-6JUKM6LT.js";import{A as Ln,B as Hn,a as F,b as ln,c as Se,d as un,e as Ee,f as wn,g as Rn,h as Sn,i as En,j as In,k as xn,l as Tn,m as kn,n as An,o as Un,p as _n,q as bn,r as On,s as vn,t as Cn,u as Pn,v as Nn,w as Mn,x as Dn,y as $n,z as Fn}from"./chunk-QEZQZG6Z.js";import{a as en}from"./chunk-RYHQGPX5.js";import{a as tn}from"./chunk-R6EKV3WR.js";import{a as sn}from"./chunk-6HY7QUMP.js";import{a as nn,b as rn}from"./chunk-V6JSMX5A.js";import{a as cn}from"./chunk-Q7QHJJGR.js";import{a as b,b as C,c as on,d as an}from"./chunk-YLDLDEUP.js";import{a as Re}from"./chunk-U56YWPSI.js";import"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";import{Agent as Ze}from"agents";import{nanoid as Dt}from"nanoid";async function mt(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 He(t,e){t.sql`INSERT INTO messages (id, role, type, content, ts) VALUES (${e.id}, ${e.role}, ${e.type}, ${e.content}, ${e.ts})`}async function O(t){return t.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function H(t){t.sql`DELETE FROM messages`}async function je(t){await mt(t)}function Y(t){return{"Content-Type":"application/json",Authorization:t.HX_API_KEY}}function j(t){return!!(t!=null&&t.HX_ORA_URL)&&!!(t!=null&&t.HX_API_KEY)}var gt="anonymous:";function Ke(t,e){return(t==null?void 0:t.trim())||`${gt}${e}`}async function B(t,e){if(!j(t))return null;let r=await fetch(`${t.HX_ORA_URL}/internal/runs`,{method:"POST",headers:Y(t),body:JSON.stringify(e)});return r.ok?await r.json():(console.error("[oraTriggers] createRun failed",r.status,await r.text().catch(()=>"")),null)}async function N(t,e){if(!j(t))return{claimed:!0};let r=await fetch(`${t.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/claim`,{method:"POST",headers:Y(t)});if(!r.ok){let n=await r.text().catch(()=>"");throw new Error(`claimRun ${e} failed with ${r.status}: ${n}`)}return await r.json()}async function K(t,e,r,n=3){if(!j(t))return!0;for(let s=1;s<=n;s++){try{let a=await fetch(`${t.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/complete`,{method:"POST",headers:Y(t),body:JSON.stringify(r)});if(a.ok||a.status===409)return!0;if(a.status===404)return console.error(`[oraTriggers] completeRun ${e} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${e} attempt ${s} failed with ${a.status}`)}catch(a){console.warn(`[oraTriggers] completeRun ${e} attempt ${s} threw`,a)}s<n&&await new Promise(a=>setTimeout(a,250*s))}return console.error(`[oraTriggers] completeRun ${e} exhausted ${n} attempts; hx-ora will time the run out`),!1}async function qe(t,e){if(!j(t))return Promise.resolve();try{return await B(t,e)}catch(r){return console.error("[oraTriggers] recordRun failed",r),null}}var Z=Object.freeze({}),yt="__SYSTEM_";function Q(t){return t.startsWith(yt)}function ht(t){let e={};for(let[r,n]of Object.entries(t))Q(r)||(e[r]=n);return Object.freeze(e)}function q(t){return(typeof t=="string"?t.trim():"")||"default"}async function Ge(t,e,r){if(!e)return Z;let n=q(r);if(t.HX_ORA_URL&&t.HX_API_KEY)try{let a=new URL(`${t.HX_ORA_URL.replace(/\/$/,"")}/internal/secrets`);a.searchParams.set("org",n);let o=await fetch(a,{headers:{Authorization:t.HX_API_KEY}});if(o.ok){let i=await o.json();if(i.secrets)return ht(i.secrets)}else console.warn(`[secrets] API failed with status ${o.status}, falling back to KV`)}catch(a){console.error("[secrets] API request failed, falling back to KV",a)}let s=t.ORA_SECRETS;if(!s)return Z;try{let a={};return await wt(s,`${e}:${n}:`,a),n==="default"&&await Rt(s,e,a),Object.freeze(a)}catch(a){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,org:n,err:a}),Z}}async function wt(t,e,r){let n=await t.list({prefix:e,limit:1e3});n.list_complete===!1&&console.warn(`[secrets] prefix=${e} exceeded list page; truncating to first 1000 keys`);let s=n.keys.filter(o=>{let i=o.name.slice(e.length);return i.length>0&&!i.includes(":")&&!Q(i)}),a=await Promise.all(s.map(async o=>{let i=await t.get(o.name);return i!==null?[o.name.slice(e.length),i]:null}));for(let o of a){if(!o)continue;let[i,c]=o;i&&(r[i]=c)}}async function Rt(t,e,r){let n=`${e}:`,s=await t.list({prefix:n,limit:1e3});s.list_complete===!1&&console.warn(`[secrets] tenant=${e} legacy secrets exceeded list page; truncating to first 1000 keys`);let a=s.keys.filter(i=>{let c=i.name.slice(n.length);return c.length>0&&!c.includes(":")&&!Q(c)}),o=await Promise.all(a.map(async i=>{let c=i.name.slice(n.length);if(c in r)return null;let l=await t.get(i.name);return l!==null?[c,l]:null}));for(let i of o){if(!i)continue;let[c,l]=i;c&&(r[c]=l)}}function G(t){var s;let e=((s=t==null?void 0:t.flowData)==null?void 0:s.state)??(t==null?void 0:t.flowData),n=((e==null?void 0:e.nodes)??[]).find(a=>a.type==="startNode");return n==null?void 0:n.data}import{nanoid as Ct}from"nanoid";import{streamText as St}from"ai";var Et={short:`Up to ${L("short")} markdown lines (one fact or bullet per line). Keep constraints, working agreements, and the outline of anything already settled.`,medium:`Up to ${L("medium")} markdown lines. Group bullets by whatever this session is about (actors, constraints, decisions, current plan/state, open work). Under-remembering is worse than a few extra lines.`,long:`Up to ${L("long")} markdown lines. Same as medium, with one-line context on a decision or plan block when later turns will need it.`},It=12,xt=400,We=700;function Tt(t,e=It){let r=t.filter(s=>s.role==="user"||s.role==="assistant").slice(-e),n=[];for(let s of r){let a=typeof s.content=="string"?s.content:JSON.stringify(s.content??""),o=s.role==="assistant"?We:xt,i=a.trim().replace(/\s+/g," ").slice(0,o);i&&n.push(`${s.role==="user"?"U":"A"}: ${i}`)}return n.join(`
1
+ import{a as k,b as Xn,c as Pe,d as Ne,e as kr,f as Fe,g as Ar,h as Le,i as Ur}from"./chunk-WOY6GG37.js";import"./chunk-V35SRZAO.js";import{c as zn}from"./chunk-Z4CYLB7J.js";import"./chunk-6AZ7RATD.js";import"./chunk-XXB57DMN.js";import"./chunk-3K4IMMLP.js";import{a as _r,b as br,c as Or,d as vr}from"./chunk-S2CXL35V.js";import{$ as Rr,A as Ce,B as Vn,C as Jn,D as Yn,E as Bn,F as Zn,G as Qn,H as er,I as tr,J as nr,K as rr,L as sr,M as or,N as ar,O as ir,P as cr,Q as lr,R as ur,S as dr,T as pr,U as fr,V as mr,W as gr,X as Me,Y as yr,Z as hr,_ as wr,a as I,aa as Sr,b as Ie,ba as Er,c as dn,ca as Ir,d as P,da as xr,e as xe,ea as Tr,f as pn,fa as De,g as fn,ga as $e,h as mn,i as gn,j as yn,k as hn,l as wn,m as Rn,n as Sn,o as En,p as Te,q as L,r as In,s as ke,t as Ae,u as Ue,v as _e,w as be,x as Oe,y as J,z as ve}from"./chunk-P6YUTKRM.js";import{A as Gn,B as Wn,a as F,b as ln,c as Se,d as un,e as Ee,f as xn,g as Tn,h as kn,i as An,j as Un,k as _n,l as bn,m as On,n as vn,o as Cn,p as Pn,q as Nn,r as Mn,s as Dn,t as $n,u as Fn,v as Ln,w as Hn,x as jn,y as Kn,z as qn}from"./chunk-KKJW6HJA.js";import{a as en}from"./chunk-RYHQGPX5.js";import{a as tn}from"./chunk-R6EKV3WR.js";import{a as sn}from"./chunk-6HY7QUMP.js";import{a as nn,b as rn}from"./chunk-V6JSMX5A.js";import{a as cn}from"./chunk-Q7QHJJGR.js";import{a as b,b as C,c as on,d as an}from"./chunk-YLDLDEUP.js";import{a as Re}from"./chunk-U56YWPSI.js";import"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";import{Agent as Ze}from"agents";import{nanoid as Dt}from"nanoid";async function mt(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 He(t,e){t.sql`INSERT INTO messages (id, role, type, content, ts) VALUES (${e.id}, ${e.role}, ${e.type}, ${e.content}, ${e.ts})`}async function O(t){return t.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function H(t){t.sql`DELETE FROM messages`}async function je(t){await mt(t)}function Y(t){return{"Content-Type":"application/json",Authorization:t.HX_API_KEY}}function j(t){return!!(t!=null&&t.HX_ORA_URL)&&!!(t!=null&&t.HX_API_KEY)}var gt="anonymous:";function Ke(t,e){return(t==null?void 0:t.trim())||`${gt}${e}`}async function B(t,e){if(!j(t))return null;let r=await fetch(`${t.HX_ORA_URL}/internal/runs`,{method:"POST",headers:Y(t),body:JSON.stringify(e)});return r.ok?await r.json():(console.error("[oraTriggers] createRun failed",r.status,await r.text().catch(()=>"")),null)}async function N(t,e){if(!j(t))return{claimed:!0};let r=await fetch(`${t.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/claim`,{method:"POST",headers:Y(t)});if(!r.ok){let n=await r.text().catch(()=>"");throw new Error(`claimRun ${e} failed with ${r.status}: ${n}`)}return await r.json()}async function K(t,e,r,n=3){if(!j(t))return!0;for(let s=1;s<=n;s++){try{let a=await fetch(`${t.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/complete`,{method:"POST",headers:Y(t),body:JSON.stringify(r)});if(a.ok||a.status===409)return!0;if(a.status===404)return console.error(`[oraTriggers] completeRun ${e} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${e} attempt ${s} failed with ${a.status}`)}catch(a){console.warn(`[oraTriggers] completeRun ${e} attempt ${s} threw`,a)}s<n&&await new Promise(a=>setTimeout(a,250*s))}return console.error(`[oraTriggers] completeRun ${e} exhausted ${n} attempts; hx-ora will time the run out`),!1}async function qe(t,e){if(!j(t))return Promise.resolve();try{return await B(t,e)}catch(r){return console.error("[oraTriggers] recordRun failed",r),null}}var Z=Object.freeze({}),yt="__SYSTEM_";function Q(t){return t.startsWith(yt)}function ht(t){let e={};for(let[r,n]of Object.entries(t))Q(r)||(e[r]=n);return Object.freeze(e)}function q(t){return(typeof t=="string"?t.trim():"")||"default"}async function Ge(t,e,r){if(!e)return Z;let n=q(r);if(t.HX_ORA_URL&&t.HX_API_KEY)try{let a=new URL(`${t.HX_ORA_URL.replace(/\/$/,"")}/internal/secrets`);a.searchParams.set("org",n);let o=await fetch(a,{headers:{Authorization:t.HX_API_KEY}});if(o.ok){let i=await o.json();if(i.secrets)return ht(i.secrets)}else console.warn(`[secrets] API failed with status ${o.status}, falling back to KV`)}catch(a){console.error("[secrets] API request failed, falling back to KV",a)}let s=t.ORA_SECRETS;if(!s)return Z;try{let a={};return await wt(s,`${e}:${n}:`,a),n==="default"&&await Rt(s,e,a),Object.freeze(a)}catch(a){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,org:n,err:a}),Z}}async function wt(t,e,r){let n=await t.list({prefix:e,limit:1e3});n.list_complete===!1&&console.warn(`[secrets] prefix=${e} exceeded list page; truncating to first 1000 keys`);let s=n.keys.filter(o=>{let i=o.name.slice(e.length);return i.length>0&&!i.includes(":")&&!Q(i)}),a=await Promise.all(s.map(async o=>{let i=await t.get(o.name);return i!==null?[o.name.slice(e.length),i]:null}));for(let o of a){if(!o)continue;let[i,c]=o;i&&(r[i]=c)}}async function Rt(t,e,r){let n=`${e}:`,s=await t.list({prefix:n,limit:1e3});s.list_complete===!1&&console.warn(`[secrets] tenant=${e} legacy secrets exceeded list page; truncating to first 1000 keys`);let a=s.keys.filter(i=>{let c=i.name.slice(n.length);return c.length>0&&!c.includes(":")&&!Q(c)}),o=await Promise.all(a.map(async i=>{let c=i.name.slice(n.length);if(c in r)return null;let l=await t.get(i.name);return l!==null?[c,l]:null}));for(let i of o){if(!i)continue;let[c,l]=i;c&&(r[c]=l)}}function G(t){var s;let e=((s=t==null?void 0:t.flowData)==null?void 0:s.state)??(t==null?void 0:t.flowData),n=((e==null?void 0:e.nodes)??[]).find(a=>a.type==="startNode");return n==null?void 0:n.data}import{nanoid as Ct}from"nanoid";import{streamText as St}from"ai";var Et={short:`Up to ${L("short")} markdown lines (one fact or bullet per line). Keep constraints, working agreements, and the outline of anything already settled.`,medium:`Up to ${L("medium")} markdown lines. Group bullets by whatever this session is about (actors, constraints, decisions, current plan/state, open work). Under-remembering is worse than a few extra lines.`,long:`Up to ${L("long")} markdown lines. Same as medium, with one-line context on a decision or plan block when later turns will need it.`},It=12,xt=400,We=700;function Tt(t,e=It){let r=t.filter(s=>s.role==="user"||s.role==="assistant").slice(-e),n=[];for(let s of r){let a=typeof s.content=="string"?s.content:JSON.stringify(s.content??""),o=s.role==="assistant"?We:xt,i=a.trim().replace(/\s+/g," ").slice(0,o);i&&n.push(`${s.role==="user"?"U":"A"}: ${i}`)}return n.join(`
2
2
  `)}function kt(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 At(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 Ut(t){var s,a;let e=((s=t.flowData)==null?void 0:s.state)??t.flowData,r=(e==null?void 0:e.nodes)??[],n=[];for(let o of r){if(o.type!=="answerNode")continue;let i=(a=t.results)==null?void 0:a[o.id];i!=null&&n.push(typeof i=="string"?i:JSON.stringify(i))}return n.join(`
3
3
  `)}function _t(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.`,Et[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,We)}`:"",t.answers.trim()?`Answer outputs:
4
4
  ${t.answers.trim()}`:""].filter(Boolean).join(`
5
- `);return{system:e,user:r}}function bt(t){return Ce(t.previous,ve(t.userText),t.maxTokens)}async function Ot(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 vt(t){if(t.fullStream&&typeof t.fullStream[Symbol.asyncIterator]=="function")return Ot({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 Xe(t){var l;let e=G(t.engineState);if(!e)return{status:"skipped",reason:"start_node_missing"};if(!Ae(e))return{status:"skipped",reason:"memory_disabled"};let r=_e(e),n=Te(r),s=Ue(e),a=J(t.previousContent||""),o=At(t.messages),i=Ut(t.engineState),c=u=>{let m=bt({previous:a,userText:t.userText,maxTokens:n});return{status:"written",content:m,truncated:!1,modelId:s,fallback:!0,error:m?void 0:u}};try{let u=await Fe(s,t.sessionEnv,{maxOutputTokens:n});if(!u)throw new Error(`Memory model '${s}' not found in registry`);let m=be(r,(l=u.reasoning)==null?void 0:l.kind),{system:f,user:p}=_t({previous:a,userText:t.userText,assistantText:o,answers:i,length:r,maxTokens:n,recentTurns:Tt(t.messages)}),g=De(u.reasoning),y=$e(u.provider,{effort:g,exposeReasoning:!1,maxTokens:m}),w=St({model:u.modelHandle,system:f,messages:[{role:"user",content:p}],...Me({...u.effectiveParams??{},maxOutputTokens:m}),...y?{providerOptions:y}:{}}),R=await vt(w),S=kt(await w.usage),U=J(R.text);if(Oe(U)&&(U=""),!U)return{...c(R.error||"Memory model returned empty text"),usage:S};let T=ke(U,n);return{status:"written",content:T.content,truncated:T.truncated,usage:S,modelId:s}}catch(u){let m=u instanceof Error?u.message:"Memory update failed";return console.error("Memory update failed:",u),c(m)}}async function ze(t,e){var n,s;let r=(n=e==null?void 0:e.flowData)==null?void 0:n.flowId;if(!(t!=null&&t.HX_CORE_URL)||!r)return{engineState:e,refreshed:!1};try{let a=await C(r,t),o={...e,flowData:{...a,tenant:e.flowData.tenant,flowId:r,chatId:e.flowData.chatId}},i=a==null?void 0:a.stateVersion,c=typeof i=="number"&&i!==((s=e.flowData)==null?void 0:s.stateVersion);return{engineState:o,refreshed:c}}catch(a){return console.error(`[flowRefresh] fetch failed for flow ${r}:`,a),{engineState:e,refreshed:!1}}}function Ve(t,e){return!t||!t.HX_ORA_URL||!t.HX_API_KEY?Promise.resolve():fetch(`${t.HX_ORA_URL}/internal/sessions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t.HX_API_KEY},body:JSON.stringify(e)}).catch(r=>{console.error("[sessionIndex] failed to index session",r)})}var Je=async(t,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),`${JSON.stringify(t)}`};async function M(t,e){var a;let r=t.id||t.name||"",[n,s]=String(r).split("::");if(!n||!s)return null;try{let i=(a=(await b(n,e)).metadata)==null?void 0:a.tenant,l={flowData:{...await C(n,e),tenant:i,flowId:n,chatId:s},executedNodes:[],context:{}};return t.setState({...t.state,engineState:l}),l}catch(o){return console.error("Failed to initialize engine state:",o),null}}async function Pt(t,e,r){var n;if(e&&t.HX_CORE_URL&&t.HX_API_KEY)try{let s=await b(e,t),a=(n=s==null?void 0:s.metadata)==null?void 0:n.org;if(typeof a=="string"&&a.trim())return q(a)}catch(s){console.warn(`[secrets] could not read org for flow ${e}`,s)}return q(r)}async function D(t){var re,se,oe,ae,ie,ce,le,ue,de,pe,fe;let{agent:e,env:r,ctx:n,payload:s,connection:a}=t,o=Date.now(),i=[],c=t.runId?Pe():void 0,l=async()=>await O(e),u=async d=>{await He(e,d)},m=async d=>{if(e.state.modelsCache&&e.state.modelsCache[d])return e.state.modelsCache[d];try{let{fetchOraModel:h}=await import("./oraApi-YIJGMXX7.js"),x=await h(d,r);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[d]:x}}),x}catch(h){throw console.error(`Error fetching model ${d}:`,h),h}},f={id:Ct(),role:"user",type:"text",content:s.text,images:s.images,ts:Date.now()};await u(f);let p={onChangeState:d=>{e.setState({...e.state,engineState:d})},onServerEvent:async d=>{var h;await((h=t.onServerEvent)==null?void 0:h.call(t,d)),i.push(d)},onTelemetry:async d=>{var _,me,ge,ye,he,we;let h=t.user,x=typeof(h==null?void 0:h.org)=="string"&&h.org.trim()?h.org.trim():"default";await Je({...d,userId:t.resolveUserId(),tenant:((me=(_=e.state.engineState)==null?void 0:_.flowData)==null?void 0:me.tenant)||"",org:x,flowId:((ye=(ge=e.state.engineState)==null?void 0:ge.flowData)==null?void 0:ye.flowId)||"",sessionId:((we=(he=e.state.engineState)==null?void 0:he.flowData)==null?void 0:we.chatId)||""},r)},onError:d=>{var h;(h=t.onError)==null||h.call(t,d),e.setState({...e.state,error:d})},shouldStop:t.shouldStop},g=e.state.engineState?{...e.state.engineState}:null;if(g){let{engineState:d,refreshed:h}=await ze(r,g);g=d,h&&e.setState({...e.state,engineState:g,modelsCache:{}})}else if(g=await M(e,r),!g){let d="Failed to initialize agent";return p.onError(d),{status:"failed",error:d}}let y=t.user??void 0,w=(re=g.flowData)==null?void 0:re.tenant,R=await Pt(r,(se=g.flowData)==null?void 0:se.flowId,y==null?void 0:y.org),S=w?await Ge(r,w,R):{};(oe=t.onSecretsLoaded)==null||oe.call(t,S),g={...g,context:{...g.context||{},user:y}},e.setState({...e.state,user:y,engineState:g});let U={env:r,ctx:n,conn:a,getMessages:l,setMessages:u,getOraModel:m,secrets:S,userAuth:t.userAuth,user:y,composioSessions:t.composioSessions,publicOrigin:t.publicOrigin,skillRefCache:t.skillRefCache,runId:t.runId,outputCollector:c,agentMemory:typeof((ae=e.state.memory)==null?void 0:ae.content)=="string"?e.state.memory.content:"",shouldStop:t.shouldStop,workerStack:(ie=g.flowData)!=null&&ie.flowId?[g.flowData.flowId]:[],workerCalls:{count:0}},T=await Le(U,g,p)(s),E=e.state.engineState??g;if(T.status==="completed")try{let d=await Xe({sessionEnv:U,engineState:E,previousContent:typeof((ce=e.state.memory)==null?void 0:ce.content)=="string"?e.state.memory.content:"",userText:s.text||"",messages:await l()});if(d.status==="skipped")await p.onServerEvent({type:"agent:memory",content:{skipped:!0,reason:d.reason},timestamp:Date.now()});else if(!d.content.trim())await p.onServerEvent({type:"agent:memory",content:{updated:!1,empty:!0,error:d.error,fallback:d.fallback},timestamp:Date.now()});else{let h={promptTokens:((le=E.tokenUsage)==null?void 0:le.promptTokens)??0,completionTokens:((ue=E.tokenUsage)==null?void 0:ue.completionTokens)??0,totalTokens:((de=E.tokenUsage)==null?void 0:de.totalTokens)??0};d.usage&&(h.promptTokens+=d.usage.promptTokens,h.completionTokens+=d.usage.completionTokens,h.totalTokens+=d.usage.totalTokens),E={...E,tokenUsage:h},e.setState({...e.state,engineState:E,memory:{content:d.content,updatedTs:Date.now(),...d.error?{lastError:d.error}:{},...d.fallback?{fallback:!0}:{}}}),await p.onTelemetry({type:"memory_update",payload:{model:d.modelId,truncated:d.truncated,usage:d.usage,fallback:d.fallback,error:d.error}}),await p.onServerEvent({type:"agent:memory",content:{updated:!0,truncated:d.truncated,fallback:d.fallback,error:d.error},timestamp:Date.now()})}}catch(d){let h=d instanceof Error?d.message:"Memory update failed";console.error("Memory update failed:",d),await p.onServerEvent({type:"agent:memory",content:{error:h},timestamp:Date.now()})}if(T.status==="completed"&&t.runId&&(c!=null&&c.hasOutputs())){let{flowId:d,chatId:h}=E.flowData??{};if(!d||!h)T={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await Ne(r,{flowId:d,sessionId:h,runId:t.runId,createdAt:new Date(o).toISOString(),data:c.snapshotData(),answerNodeIds:c.answerNodeIds()});let x={...E.results||{}};for(let _ of c.answerNodeIds())x[_]={...x[_]||{},persisted:!0,runId:t.runId};E={...E,results:x},e.setState({...e.state,engineState:E})}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()}),T={status:"failed",error:_}}}let{tenant:$,flowId:z,chatId:V}=E.flowData??{},ft=(pe=E.flowData)==null?void 0:pe.org;return $&&z&&V&&n.waitUntil(Ve(r,{id:`${z}::${V}`,tenant:$,org:ft,flowId:z,sessionId:V,userId:t.resolveUserId(),title:(fe=s.text)==null?void 0:fe.slice(0,120),turnTs:o,events:i})),e.setState({...e.state,lastUpdated:new Date}),{status:T.status,error:T.error,engineState:E}}import{nanoid as Nt}from"nanoid";function Mt(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 Ye(t,e,r,n){var s;try{let a=await e.json(),o=a.message;if(!o||typeof o!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let i=typeof a.userId=="string"?P(a.userId):null,c=Mt(e),l=c==null?void 0:c.email;c?t.setState({...t.state,user:c,injectedUserId:l}):i&&!((s=t.state.user)!=null&&s.email)&&t.setState({...t.state,injectedUserId:i});let u=()=>l??i??t.state.injectedUserId??void 0;t.skillRefCache||(t.skillRefCache=new Map);let m=a.inputs&&typeof a.inputs=="object"?a.inputs:void 0;if(!t.state.engineState&&!await M(t,r))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let f=`run-${Nt(12)}`;await t.registerManualRun(f,o,u()),await N(r,f).catch(w=>{console.warn(`[AgentHTTP] could not mark manual run ${f} as running`,w)});let p;try{p=await D({agent:t,env:r,ctx:n,payload:{text:o,inputs:m},skillRefCache:t.skillRefCache,user:c??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 y=(await O(t)).reverse().find(w=>w.role==="assistant");return new Response(JSON.stringify({answer:(y==null?void 0:y.content)||""}),{headers:{"content-type":"application/json"}})}catch(a){return new Response(JSON.stringify({error:a.message}),{status:500,headers:{"content-type":"application/json"}})}}async function Be(t){try{return await H(t),t.skillRefCache&&t.skillRefCache.clear(),t.setState({...t.state,error:"",engineState:void 0,modelsCache:{},lastUpdated:new Date}),new Response(JSON.stringify({success:!0,messages:[]}),{headers:{"content-type":"application/json"}})}catch(e){return new Response(JSON.stringify({error:e.message}),{status:500,headers:{"content-type":"application/json"}})}}var Qe="trigger:nonce:",$t=900*1e3,ee="run:stop:",et=class extends Ze{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{},memory:void 0};constructor(e,r){super(e,r),this.requireStateValidation()}validateStateChange(e,r){if(r!=="server")throw new Error("Client state updates are forbidden")}requireStateValidation(){if(typeof Ze.prototype.validateStateChange!="function")throw new Error("AgentDO requires agents >= 0.8.7 with validateStateChange; upgrade the tenant SDK")}resolveSessionUserId(){return this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async inspectPersistedSession(e){return e==="state"?{state:this.state}:e==="memory"?{memory:this.state.memory??null}:{messages:await O(this)}}async requestRunStop(e){return e!=null&&e.trim()?(await this.ctx.storage.put(`${ee}${e}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(e){return!!await this.ctx.storage.get(`${ee}${e}`)}async clearRunStopRequest(e){await this.ctx.storage.delete(`${ee}${e}`)}async onRequest(e){this.requireStateValidation();let r=new URL(e.url);if(r.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(r.pathname.endsWith("/history")){let n=await O(this);return new Response(JSON.stringify(n),{headers:{"content-type":"application/json"}})}return e.method==="POST"&&r.pathname.endsWith("/message")?Ye(this,e,this.env,this.ctx):e.method==="DELETE"&&r.pathname.endsWith("/clear")?Be(this):new Response("Ready to assist.")}async onConnect(e,r){var f,p,g,y,w;this.requireStateValidation();let[n,s]=e.server.split("::"),o=(f=(await b(n,this.env)).metadata)==null?void 0:f.tenant;this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let i=null;if(r.request){try{this.publicOrigin=new URL(r.request.url).origin}catch{}let R=r.request.headers.get("X-User-Payload");if(R)try{i=JSON.parse(R)}catch(S){console.warn("Failed to parse X-User-Payload",S)}}e.setState({...e.state,authorizedUser:i});let c=await C(n,this.env);this.setState({...this.state,user:i||null,sessionId:s,engineState:{flowData:{...c,tenant:o,flowId:n,chatId:s},executedNodes:[],context:i?{user:i}:{}}}),i||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let l=await O(this);k(e,I.SERVER_HISTORY,JSON.stringify({messages:l}));let m=(((p=c==null?void 0:c.state)==null?void 0:p.nodes)??(c==null?void 0:c.nodes)??[]).find(R=>R.type==="startNode");if(m){let R={allow_images:((g=m.data)==null?void 0:g.allow_images)??!1,allow_documents:((y=m.data)==null?void 0:y.allow_documents)??!1,greeting:(w=m.data)==null?void 0:w.greeting};k(e,I.SERVER_CONFIG,JSON.stringify(R))}}async onMessage(e,r){if(typeof r!="string")return;let n=r.indexOf(":");if(n===-1)return;let s=r.substring(0,n),a=r.substring(n+1);if(!s||!a)return;let i={[I.USER_MESSAGE]:c=>this.onUserMessage(e,c),[I.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[I.USER_AUTH]:c=>this.onUserAuth(e,c),[I.USER_IDENTITY]:c=>this.onUserIdentity(e,c)}[s];i&&await i(a)}async onUserMessage(e,r){var i;let n=Ie(r),s=((i=e.state)==null?void 0:i.authorizedUser)??void 0,a=()=>(s==null?void 0:s.email)??this.resolveSessionUserId(),o=`run-${Dt(12)}`;await this.registerManualRun(o,n.text,a()),await N(this.env,o).catch(c=>{console.warn(`[AgentDO] could not mark manual run ${o} as running`,c)});try{let c=await D({agent:this,env:this.env,ctx:this.ctx,payload:n,connection:e,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:s,resolveUserId:a,runId:o,shouldStop:()=>this.isRunStopRequested(o),onServerEvent:l=>{k(e,I.SERVER_EVENT,JSON.stringify(l))},onError:l=>{k(e,I.SERVER_ERROR,l)},onSecretsLoaded:l=>{this.secrets=l}});this.ctx.waitUntil(this.completeManualRun(o,c.status==="completed"?"succeeded":c.status==="stopped"?"skipped":"failed",c.error))}finally{await this.clearRunStopRequest(o)}}registerManualRun(e,r,n){var c;let{tenant:s,flowId:a,chatId:o}=((c=this.state.engineState)==null?void 0:c.flowData)??{};if(!s||!a||!o)return Promise.resolve();let i=Ke(n||this.resolveSessionUserId(),o);return qe(this.env,{id:e,tenant:s,flowId:a,userId:i,sessionId:o,label:r==null?void 0:r.slice(0,120)})}completeManualRun(e,r,n){return K(this.env,e,{status:r,error:n})}async enqueueTrigger(e){var s;if(!(e!=null&&e.runId)||!(e!=null&&e.flowId))return{queued:!1};if(e.nonce&&!await this.claimTriggerNonce(e.nonce))return console.warn(`[AgentDO] rejected replayed trigger nonce ${e.nonce}`),{queued:!1,duplicate:!0};let r=e.runAsUserId;return r&&!((s=this.state.user)!=null&&s.email)&&this.state.injectedUserId!==r&&this.setState({...this.state,injectedUserId:r}),{queued:!0,taskId:await this.queue("processTrigger",e)}}async claimTriggerNonce(e){let r=`${Qe}${e}`;if(await this.ctx.storage.get(r))return!1;let n=Date.now();await this.ctx.storage.put(r,n);let a=[...(await this.ctx.storage.list({prefix:Qe})).entries()].filter(([,o])=>n-o>$t).map(([o])=>o);return a.length>0&&await this.ctx.storage.delete(a),!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 M(this,this.env);let n=Se(G(this.state.engineState)),s=Ee(n,e.inputs||{},e.label),a=await D({agent:this,env:this.env,ctx:this.ctx,payload:{text:s,inputs:e.inputs||{}},composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>e.runAsUserId||this.resolveSessionUserId(),runId:e.runId,shouldStop:()=>this.isRunStopRequested(e.runId),onSecretsLoaded:o=>{this.secrets=o}});await K(this.env,e.runId,{status:a.status==="completed"?"succeeded":a.status==="stopped"?"skipped":"failed",error:a.error})}catch(n){let s=n instanceof Error?n.message:"Trigger execution failed";throw await K(this.env,e.runId,{status:"failed",error:s}),n}finally{await this.clearRunStopRequest(e.runId)}}async onUserIdentity(e,r){let n=P(r);if(!n){k(e,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=xe(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 H(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear(),this.setState({...this.state,error:"",engineState:this.state.engineState,memory:this.state.memory,modelsCache:{},lastUpdated:new Date}),e&&k(e,I.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await je(this);let e=await O(this);`${JSON.stringify(e)}`}async onClose(e,r,n,s){console.log(`Session closed: ${this.state.sessionId} ${r} - ${n}`)}async onError(e){console.error("AgentDO encountered an error:",e)}};function ws(t){let e=t.state;if(!e)return null;let r=["startNode","answerNode"];for(let n of r)if(!e.nodes.some(a=>a.type===n))return!1;return e.nodes.find(n=>n.type==="startNode")}import{importSPKI as Ft,jwtVerify as Lt}from"jose";function W(t){let e={};if(!t)return e;let r=t.split(";");for(let n of r){let s=n.indexOf("=");if(s>-1){let a=n.slice(0,s).trim(),o=n.slice(s+1).trim();a&&(e[a]=decodeURIComponent(o))}}return e}function Ht(t){return(typeof t.email=="string"?t.email.trim():"")||null}async function v(t,e,r){let n=W(t.headers.get("cookie")),s=new URL(t.url),a=n.access_token||s.searchParams.get("access_token"),o=await jt(e,a);if(o.ok){let i=o.payload,c=Ht(i);return c?{id:i.sub,email:c,name:i.name,first_name:i.given_name,last_name:i.family_name,tenant:i.tenant,org:typeof i.org=="string"?i.org:null,roles:i["ora-roles"],db_name:i.db_name||null,user_id:i.user_id||null}:null}return null}async function jt(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 bt(t){return Ce(t.previous,ve(t.userText),t.maxTokens)}async function Ot(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 vt(t){if(t.fullStream&&typeof t.fullStream[Symbol.asyncIterator]=="function")return Ot({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 Xe(t){var l;let e=G(t.engineState);if(!e)return{status:"skipped",reason:"start_node_missing"};if(!Ae(e))return{status:"skipped",reason:"memory_disabled"};let r=_e(e),n=Te(r),s=Ue(e),a=J(t.previousContent||""),o=At(t.messages),i=Ut(t.engineState),c=u=>{let m=bt({previous:a,userText:t.userText,maxTokens:n});return{status:"written",content:m,truncated:!1,modelId:s,fallback:!0,error:m?void 0:u}};try{let u=await Fe(s,t.sessionEnv,{maxOutputTokens:n});if(!u)throw new Error(`Memory model '${s}' not found in registry`);let m=be(r,(l=u.reasoning)==null?void 0:l.kind),{system:f,user:p}=_t({previous:a,userText:t.userText,assistantText:o,answers:i,length:r,maxTokens:n,recentTurns:Tt(t.messages)}),g=De(u.reasoning),y=$e(u.provider,{effort:g,exposeReasoning:!1,maxTokens:m}),w=St({model:u.modelHandle,system:f,messages:[{role:"user",content:p}],...Me({...u.effectiveParams??{},maxOutputTokens:m}),...y?{providerOptions:y}:{}}),R=await vt(w),S=kt(await w.usage),U=J(R.text);if(Oe(U)&&(U=""),!U)return{...c(R.error||"Memory model returned empty text"),usage:S};let T=ke(U,n);return{status:"written",content:T.content,truncated:T.truncated,usage:S,modelId:s}}catch(u){let m=u instanceof Error?u.message:"Memory update failed";return console.error("Memory update failed:",u),c(m)}}async function ze(t,e){var n,s;let r=(n=e==null?void 0:e.flowData)==null?void 0:n.flowId;if(!(t!=null&&t.HX_CORE_URL)||!r)return{engineState:e,refreshed:!1};try{let a=await C(r,t),o={...e,flowData:{...a,tenant:e.flowData.tenant,flowId:r,chatId:e.flowData.chatId}},i=a==null?void 0:a.stateVersion,c=typeof i=="number"&&i!==((s=e.flowData)==null?void 0:s.stateVersion);return{engineState:o,refreshed:c}}catch(a){return console.error(`[flowRefresh] fetch failed for flow ${r}:`,a),{engineState:e,refreshed:!1}}}function Ve(t,e){return!t||!t.HX_ORA_URL||!t.HX_API_KEY?Promise.resolve():fetch(`${t.HX_ORA_URL}/internal/sessions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t.HX_API_KEY},body:JSON.stringify(e)}).catch(r=>{console.error("[sessionIndex] failed to index session",r)})}var Je=async(t,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),`${JSON.stringify(t)}`};async function M(t,e){var a;let r=t.id||t.name||"",[n,s]=String(r).split("::");if(!n||!s)return null;try{let i=(a=(await b(n,e)).metadata)==null?void 0:a.tenant,l={flowData:{...await C(n,e),tenant:i,flowId:n,chatId:s},executedNodes:[],context:{}};return t.setState({...t.state,engineState:l}),l}catch(o){return console.error("Failed to initialize engine state:",o),null}}async function Pt(t,e,r){var n;if(e&&t.HX_CORE_URL&&t.HX_API_KEY)try{let s=await b(e,t),a=(n=s==null?void 0:s.metadata)==null?void 0:n.org;if(typeof a=="string"&&a.trim())return q(a)}catch(s){console.warn(`[secrets] could not read org for flow ${e}`,s)}return q(r)}async function D(t){var re,se,oe,ae,ie,ce,le,ue,de,pe,fe;let{agent:e,env:r,ctx:n,payload:s,connection:a}=t,o=Date.now(),i=[],c=t.runId?Pe():void 0,l=async()=>await O(e),u=async d=>{await He(e,d)},m=async d=>{if(e.state.modelsCache&&e.state.modelsCache[d])return e.state.modelsCache[d];try{let{fetchOraModel:h}=await import("./oraApi-YIJGMXX7.js"),x=await h(d,r);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[d]:x}}),x}catch(h){throw console.error(`Error fetching model ${d}:`,h),h}},f={id:Ct(),role:"user",type:"text",content:s.text,images:s.images,ts:Date.now()};await u(f);let p={onChangeState:d=>{e.setState({...e.state,engineState:d})},onServerEvent:async d=>{var h;await((h=t.onServerEvent)==null?void 0:h.call(t,d)),i.push(d)},onTelemetry:async d=>{var _,me,ge,ye,he,we;let h=t.user,x=typeof(h==null?void 0:h.org)=="string"&&h.org.trim()?h.org.trim():"default";await Je({...d,userId:t.resolveUserId(),tenant:((me=(_=e.state.engineState)==null?void 0:_.flowData)==null?void 0:me.tenant)||"",org:x,flowId:((ye=(ge=e.state.engineState)==null?void 0:ge.flowData)==null?void 0:ye.flowId)||"",sessionId:((we=(he=e.state.engineState)==null?void 0:he.flowData)==null?void 0:we.chatId)||""},r)},onError:d=>{var h;(h=t.onError)==null||h.call(t,d),e.setState({...e.state,error:d})},shouldStop:t.shouldStop},g=e.state.engineState?{...e.state.engineState}:null;if(g){let{engineState:d,refreshed:h}=await ze(r,g);g=d,h&&e.setState({...e.state,engineState:g,modelsCache:{}})}else if(g=await M(e,r),!g){let d="Failed to initialize agent";return p.onError(d),{status:"failed",error:d}}let y=t.user??void 0,w=(re=g.flowData)==null?void 0:re.tenant,R=await Pt(r,(se=g.flowData)==null?void 0:se.flowId,y==null?void 0:y.org),S=w?await Ge(r,w,R):{};(oe=t.onSecretsLoaded)==null||oe.call(t,S),g={...g,context:{...g.context||{},user:y}},e.setState({...e.state,user:y,engineState:g});let U={env:r,ctx:n,conn:a,getMessages:l,setMessages:u,getOraModel:m,secrets:S,userAuth:t.userAuth,user:y,composioSessions:t.composioSessions,publicOrigin:t.publicOrigin,skillRefCache:t.skillRefCache,runId:t.runId,outputCollector:c,agentMemory:typeof((ae=e.state.memory)==null?void 0:ae.content)=="string"?e.state.memory.content:"",shouldStop:t.shouldStop,workerStack:(ie=g.flowData)!=null&&ie.flowId?[g.flowData.flowId]:[],workerCalls:{count:0}},T=await Le(U,g,p)(s),E=e.state.engineState??g;if(T.status==="completed")try{let d=await Xe({sessionEnv:U,engineState:E,previousContent:typeof((ce=e.state.memory)==null?void 0:ce.content)=="string"?e.state.memory.content:"",userText:s.text||"",messages:await l()});if(d.status==="skipped")await p.onServerEvent({type:"agent:memory",content:{skipped:!0,reason:d.reason},timestamp:Date.now()});else if(!d.content.trim())await p.onServerEvent({type:"agent:memory",content:{updated:!1,empty:!0,error:d.error,fallback:d.fallback},timestamp:Date.now()});else{let h={promptTokens:((le=E.tokenUsage)==null?void 0:le.promptTokens)??0,completionTokens:((ue=E.tokenUsage)==null?void 0:ue.completionTokens)??0,totalTokens:((de=E.tokenUsage)==null?void 0:de.totalTokens)??0};d.usage&&(h.promptTokens+=d.usage.promptTokens,h.completionTokens+=d.usage.completionTokens,h.totalTokens+=d.usage.totalTokens),E={...E,tokenUsage:h},e.setState({...e.state,engineState:E,memory:{content:d.content,updatedTs:Date.now(),...d.error?{lastError:d.error}:{},...d.fallback?{fallback:!0}:{}}}),await p.onTelemetry({type:"memory_update",payload:{model:d.modelId,truncated:d.truncated,usage:d.usage,fallback:d.fallback,error:d.error}}),await p.onServerEvent({type:"agent:memory",content:{updated:!0,truncated:d.truncated,fallback:d.fallback,error:d.error},timestamp:Date.now()})}}catch(d){let h=d instanceof Error?d.message:"Memory update failed";console.error("Memory update failed:",d),await p.onServerEvent({type:"agent:memory",content:{error:h},timestamp:Date.now()})}if(T.status==="completed"&&t.runId&&(c!=null&&c.hasOutputs())){let{flowId:d,chatId:h}=E.flowData??{};if(!d||!h)T={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await Ne(r,{flowId:d,sessionId:h,runId:t.runId,createdAt:new Date(o).toISOString(),data:c.snapshotData(),answerNodeIds:c.answerNodeIds()});let x={...E.results||{}};for(let _ of c.answerNodeIds())x[_]={...x[_]||{},persisted:!0,runId:t.runId};E={...E,results:x},e.setState({...e.state,engineState:E})}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()}),T={status:"failed",error:_}}}let{tenant:$,flowId:z,chatId:V}=E.flowData??{},ft=(pe=E.flowData)==null?void 0:pe.org;return $&&z&&V&&n.waitUntil(Ve(r,{id:`${z}::${V}`,tenant:$,org:ft,flowId:z,sessionId:V,userId:t.resolveUserId(),title:(fe=s.text)==null?void 0:fe.slice(0,120),turnTs:o,events:i})),e.setState({...e.state,lastUpdated:new Date}),{status:T.status,error:T.error,engineState:E}}import{nanoid as Nt}from"nanoid";function Mt(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 Ye(t,e,r,n){var s;try{let a=await e.json(),o=a.message;if(!o||typeof o!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let i=typeof a.userId=="string"?P(a.userId):null,c=Mt(e),l=c==null?void 0:c.email;c?t.setState({...t.state,user:c,injectedUserId:l}):i&&!((s=t.state.user)!=null&&s.email)&&t.setState({...t.state,injectedUserId:i});let u=()=>l??i??t.state.injectedUserId??void 0;t.skillRefCache||(t.skillRefCache=new Map);let m=a.inputs&&typeof a.inputs=="object"?a.inputs:void 0;if(!t.state.engineState&&!await M(t,r))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let f=`run-${Nt(12)}`;await t.registerManualRun(f,o,u()),await N(r,f).catch(w=>{console.warn(`[AgentHTTP] could not mark manual run ${f} as running`,w)});let p;try{p=await D({agent:t,env:r,ctx:n,payload:{text:o,inputs:m},skillRefCache:t.skillRefCache,user:c??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 y=(await O(t)).reverse().find(w=>w.role==="assistant");return new Response(JSON.stringify({answer:(y==null?void 0:y.content)||""}),{headers:{"content-type":"application/json"}})}catch(a){return new Response(JSON.stringify({error:a.message}),{status:500,headers:{"content-type":"application/json"}})}}async function Be(t){try{return await H(t),t.skillRefCache&&t.skillRefCache.clear(),t.setState({...t.state,error:"",engineState:void 0,modelsCache:{},lastUpdated:new Date}),new Response(JSON.stringify({success:!0,messages:[]}),{headers:{"content-type":"application/json"}})}catch(e){return new Response(JSON.stringify({error:e.message}),{status:500,headers:{"content-type":"application/json"}})}}var Qe="trigger:nonce:",$t=900*1e3,ee="run:stop:",et=class extends Ze{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{},memory:void 0};constructor(e,r){super(e,r),this.requireStateValidation()}validateStateChange(e,r){if(r!=="server")throw new Error("Client state updates are forbidden")}requireStateValidation(){if(typeof Ze.prototype.validateStateChange!="function")throw new Error("AgentDO requires agents >= 0.8.7 with validateStateChange; upgrade the tenant SDK")}resolveSessionUserId(){return this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async inspectPersistedSession(e){return e==="state"?{state:this.state}:e==="memory"?{memory:this.state.memory??null}:{messages:await O(this)}}async requestRunStop(e){return e!=null&&e.trim()?(await this.ctx.storage.put(`${ee}${e}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(e){return!!await this.ctx.storage.get(`${ee}${e}`)}async clearRunStopRequest(e){await this.ctx.storage.delete(`${ee}${e}`)}async onRequest(e){this.requireStateValidation();let r=new URL(e.url);if(r.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(r.pathname.endsWith("/history")){let n=await O(this);return new Response(JSON.stringify(n),{headers:{"content-type":"application/json"}})}return e.method==="POST"&&r.pathname.endsWith("/message")?Ye(this,e,this.env,this.ctx):e.method==="DELETE"&&r.pathname.endsWith("/clear")?Be(this):new Response("Ready to assist.")}async onConnect(e,r){var f,p,g,y,w;this.requireStateValidation();let[n,s]=e.server.split("::"),o=(f=(await b(n,this.env)).metadata)==null?void 0:f.tenant;this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let i=null;if(r.request){try{this.publicOrigin=new URL(r.request.url).origin}catch{}let R=r.request.headers.get("X-User-Payload");if(R)try{i=JSON.parse(R)}catch(S){console.warn("Failed to parse X-User-Payload",S)}}e.setState({...e.state,authorizedUser:i});let c=await C(n,this.env);this.setState({...this.state,user:i||null,sessionId:s,engineState:{flowData:{...c,tenant:o,flowId:n,chatId:s},executedNodes:[],context:i?{user:i}:{}}}),i||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let l=await O(this);k(e,I.SERVER_HISTORY,JSON.stringify({messages:l}));let m=(((p=c==null?void 0:c.state)==null?void 0:p.nodes)??(c==null?void 0:c.nodes)??[]).find(R=>R.type==="startNode");if(m){let R={allow_images:((g=m.data)==null?void 0:g.allow_images)??!1,allow_documents:((y=m.data)==null?void 0:y.allow_documents)??!1,greeting:(w=m.data)==null?void 0:w.greeting};k(e,I.SERVER_CONFIG,JSON.stringify(R))}}async onMessage(e,r){if(typeof r!="string")return;let n=r.indexOf(":");if(n===-1)return;let s=r.substring(0,n),a=r.substring(n+1);if(!s||!a)return;let i={[I.USER_MESSAGE]:c=>this.onUserMessage(e,c),[I.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[I.USER_AUTH]:c=>this.onUserAuth(e,c),[I.USER_IDENTITY]:c=>this.onUserIdentity(e,c)}[s];i&&await i(a)}async onUserMessage(e,r){var i;let n=Ie(r),s=((i=e.state)==null?void 0:i.authorizedUser)??void 0,a=()=>(s==null?void 0:s.email)??this.resolveSessionUserId(),o=`run-${Dt(12)}`;await this.registerManualRun(o,n.text,a()),await N(this.env,o).catch(c=>{console.warn(`[AgentDO] could not mark manual run ${o} as running`,c)});try{let c=await D({agent:this,env:this.env,ctx:this.ctx,payload:n,connection:e,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:s,resolveUserId:a,runId:o,shouldStop:()=>this.isRunStopRequested(o),onServerEvent:l=>{k(e,I.SERVER_EVENT,JSON.stringify(l))},onError:l=>{k(e,I.SERVER_ERROR,l)},onSecretsLoaded:l=>{this.secrets=l}});this.ctx.waitUntil(this.completeManualRun(o,c.status==="completed"?"succeeded":c.status==="stopped"?"skipped":"failed",c.error))}finally{await this.clearRunStopRequest(o)}}registerManualRun(e,r,n){var c;let{tenant:s,flowId:a,chatId:o}=((c=this.state.engineState)==null?void 0:c.flowData)??{};if(!s||!a||!o)return Promise.resolve();let i=Ke(n||this.resolveSessionUserId(),o);return qe(this.env,{id:e,tenant:s,flowId:a,userId:i,sessionId:o,label:r==null?void 0:r.slice(0,120)})}completeManualRun(e,r,n){return K(this.env,e,{status:r,error:n})}async enqueueTrigger(e){var s;if(!(e!=null&&e.runId)||!(e!=null&&e.flowId))return{queued:!1};if(e.nonce&&!await this.claimTriggerNonce(e.nonce))return console.warn(`[AgentDO] rejected replayed trigger nonce ${e.nonce}`),{queued:!1,duplicate:!0};let r=e.runAsUserId;return r&&!((s=this.state.user)!=null&&s.email)&&this.state.injectedUserId!==r&&this.setState({...this.state,injectedUserId:r}),{queued:!0,taskId:await this.queue("processTrigger",e)}}async claimTriggerNonce(e){let r=`${Qe}${e}`;if(await this.ctx.storage.get(r))return!1;let n=Date.now();await this.ctx.storage.put(r,n);let a=[...(await this.ctx.storage.list({prefix:Qe})).entries()].filter(([,o])=>n-o>$t).map(([o])=>o);return a.length>0&&await this.ctx.storage.delete(a),!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 M(this,this.env);let n=Se(G(this.state.engineState)),s=Ee(n,e.inputs||{},e.label),a=await D({agent:this,env:this.env,ctx:this.ctx,payload:{text:s,inputs:e.inputs||{}},composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>e.runAsUserId||this.resolveSessionUserId(),runId:e.runId,shouldStop:()=>this.isRunStopRequested(e.runId),onSecretsLoaded:o=>{this.secrets=o}});await K(this.env,e.runId,{status:a.status==="completed"?"succeeded":a.status==="stopped"?"skipped":"failed",error:a.error})}catch(n){let s=n instanceof Error?n.message:"Trigger execution failed";throw await K(this.env,e.runId,{status:"failed",error:s}),n}finally{await this.clearRunStopRequest(e.runId)}}async onUserIdentity(e,r){let n=P(r);if(!n){k(e,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=xe(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 H(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear(),this.setState({...this.state,error:"",engineState:this.state.engineState,memory:this.state.memory,modelsCache:{},lastUpdated:new Date}),e&&k(e,I.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await je(this);let e=await O(this);`${JSON.stringify(e)}`}async onClose(e,r,n,s){console.log(`Session closed: ${this.state.sessionId} ${r} - ${n}`)}async onError(e){console.error("AgentDO encountered an error:",e)}};function Os(t){let e=t.state;if(!e)return null;let r=["startNode","answerNode"];for(let n of r)if(!e.nodes.some(a=>a.type===n))return!1;return e.nodes.find(n=>n.type==="startNode")}import{importSPKI as Ft,jwtVerify as Lt}from"jose";function W(t){let e={};if(!t)return e;let r=t.split(";");for(let n of r){let s=n.indexOf("=");if(s>-1){let a=n.slice(0,s).trim(),o=n.slice(s+1).trim();a&&(e[a]=decodeURIComponent(o))}}return e}function Ht(t){return(typeof t.email=="string"?t.email.trim():"")||null}async function v(t,e,r){let n=W(t.headers.get("cookie")),s=new URL(t.url),a=n.access_token||s.searchParams.get("access_token"),o=await jt(e,a);if(o.ok){let i=o.payload,c=Ht(i);return c?{id:i.sub,email:c,name:i.name,first_name:i.given_name,last_name:i.family_name,tenant:i.tenant,org:typeof i.org=="string"?i.org:null,roles:i["ora-roles"],db_name:i.db_name||null,user_id:i.user_id||null}:null}return null}async function jt(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 Ft(r,"RS256");try{let{payload:s,protectedHeader:a}=await Lt(e,n);return{ok:!0,payload:s,protectedHeader:a}}catch(s){return console.error("JWT verification failed:",s),{ok:!1,payload:null,protectedHeader:null}}}async function Ts(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 X}from"agents";import{getAgentByName as Kt}from"agents";async function tt(t,e){let r=e.sessionId||e.runAsUserId,n=e.inputs||{},s=e.runId;if(!s){let c=await B(t,{tenant:e.tenant,flowId:e.flowId,userId:e.runAsUserId,sessionId:r,triggerId:e.triggerId,triggerKind:e.triggerKind,invocationMode:e.invocationMode,activationId:e.activationId,deliveryId:void 0,externalDeliveryId:e.externalDeliveryId,correlationKey:e.correlationKey,inputs:n,label:e.label});if(!c)return{status:"error",error:"Failed to register run"};if(!c.created&&c.run.status!=="queued")return{status:"deduped",runId:c.run.id};s=c.run.id}let a={...e,sessionId:r,runId:s,inputs:n},i=await(await Kt(t.AGENT,`${e.flowId}::${r}`)).enqueueTrigger(a);return i.duplicate?{status:"deduped",runId:s}:i.queued?{status:"queued",runId:s,activation:a,taskId:i.taskId}:{status:"error",error:"Failed to queue trigger"}}var rt="x-ora-signature",st="x-ora-timestamp",ot="x-ora-nonce",at="x-ora-tenant",bs=300,nt=new TextEncoder;function qt(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function Gt(t){try{let e=new URL(t);return`${e.origin}${e.pathname.replace(/\/$/,"")}`}catch{return t.replace(/\/$/,"")}}function it(t){return["v1",t.timestamp,t.nonce,t.tenant,Gt(t.destination),t.body].join(`
8
- `)}async function ct(t,e){let r=await crypto.subtle.importKey("raw",nt.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return qt(await crypto.subtle.sign("HMAC",r,nt.encode(e)))}function Wt(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 Os(t){let e=String(t.timestamp??Math.floor(Date.now()/1e3)),r=await ct(t.secret,it({timestamp:e,nonce:t.nonce,tenant:t.tenant,destination:t.destination,body:t.body}));return{"content-type":"application/json",[at]:t.tenant,[st]:e,[ot]:t.nonce,[rt]:`v1=${r}`}}async function lt(t){var l,u,m,f,p;if(!((l=t.secret)!=null&&l.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(u=t.headers.get(at))==null?void 0:u.trim(),r=(m=t.headers.get(st))==null?void 0:m.trim(),n=(f=t.headers.get(ot))==null?void 0:f.trim(),s=(p=t.headers.get(rt))==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 a=Number(r);if(!Number.isFinite(a))return{ok:!1,error:"invalid timestamp"};let o=Math.floor((t.now??Date.now())/1e3),i=t.toleranceSeconds??300;if(Math.abs(o-a)>i)return{ok:!1,error:"stale timestamp"};let c=await ct(t.secret.trim(),it({timestamp:r,nonce:n,tenant:e,destination:t.url,body:t.body}));return Wt(s.slice(3),c)?{ok:!0,tenant:e,nonce:n,timestamp:a}:{ok:!1,error:"signature mismatch"}}var A=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}});async function ut(t,e,r){var l;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(),a=await lt({secret:e.HX_API_KEY,body:s,url:t.url,headers:t.headers});if(!a.ok)return console.warn(`[triggers] rejected dispatch: ${a.error}`),A({error:"Invalid signature"},401);let o;try{o=JSON.parse(s)}catch{return A({error:"Invalid payload"},400)}if(!(o!=null&&o.runId)||!(o!=null&&o.flowId)||!(o!=null&&o.runAsUserId)||!(o!=null&&o.tenant)||!(o!=null&&o.activationId)||!(o!=null&&o.triggerId)||!(o!=null&&o.triggerKind)||!(o!=null&&o.invocationMode))return A({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(o.tenant!==a.tenant)return A({error:"Tenant mismatch"},403);let i;try{i=await b(o.flowId,e)}catch{return A({error:"Flow not found"},404)}if(!((l=i==null?void 0:i.metadata)!=null&&l.tenant)||i.metadata.tenant!==o.tenant)return console.warn(`[triggers] flow ${o.flowId} does not belong to tenant ${o.tenant}`),A({error:"Tenant mismatch"},403);let c=await tt(e,{...o,sessionId:o.sessionId||o.runAsUserId,nonce:a.nonce});return c.status==="error"?A({error:c.error},502):c.status==="deduped"?A({deduped:!0,runId:c.runId},200):A({accepted:!0,runId:c.runId,taskId:c.taskId},202)}var te=/^[A-Za-z0-9_-]{1,64}$/;async function ne(t,e,r,n,s,a=!1){let o=(f,p)=>({response:new Response(f,{status:p})});if(!/^[A-Za-z0-9_-]+$/.test(n))return o("Invalid flowId",400);if((!a||s)&&(!s||!te.test(s)))return o("Invalid sessionId",400);let i;try{i=await b(n,e)}catch{return o("Flow not found",404)}let c=i==null?void 0:i.metadata;if(!c||!["active","activo"].includes(c.status))return o("Flow not found",404);if(!e.TENANT||c.tenant!==e.TENANT)return o("Forbidden",403);let l=await v(t,e,r),u=l&&typeof l=="object"?l:void 0;if(u&&u.tenant!==e.TENANT)return o("Forbidden",403);if(c.visibility==="public")return{user:u};if(!u){if(!a)return o("Unauthorized",401);let f=new URL(t.url),p=new URL("/login",f.origin);return p.searchParams.set("nextURL",`${f.pathname}${f.search}`),{response:Response.redirect(p.toString(),302)}}if((c.org||"default")!==(u.org||"default"))return o("Forbidden",403);let m=W(t.headers.get("cookie")).access_token||new URL(t.url).searchParams.get("access_token");if(!m)return o("Unauthorized",401);try{let f=await fetch(`${e.HX_CORE_URL}/flows/${encodeURIComponent(n)}`,{headers:{Authorization:m},cache:"no-store"});if(!f.ok||(await f.json()).id!==n)return o("Forbidden",403)}catch{return o("Forbidden",403)}return{user:u}}var Xt=/^[A-Za-z0-9_-]+$/,zt=new Set(["state","messages","memory"]);async function Vt(t,e){let r=new URL(t.url);if(!r.pathname.startsWith("/api/internal/sessions/"))return;let n=r.pathname.split("/");if(n[6]!=="runs"||n[8]!=="stop"||n.length!==9)return;if(t.method!=="POST")return new Response("Method not allowed",{status:405});if(!e.HX_API_KEY||t.headers.get("Authorization")!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=decodeURIComponent(n[4]||""),a=decodeURIComponent(n[5]||""),o=decodeURIComponent(n[7]||"");if(!s||!a||!o)return new Response("Not found",{status:404});try{let i=await X(e.AGENT,`${s}::${a}`);return Response.json(await i.requestRunStop(o))}catch(i){return console.error("[agents] failed to request run stop",i),Response.json({error:"Failed to stop run"},{status:502})}}async function Jt(t,e){let r=new URL(t.url);if(!r.pathname.startsWith("/api/internal/sessions/"))return;if(t.method!=="GET")return new Response("Method not allowed",{status:405});let n=t.headers.get("Authorization")||"";if(!e.HX_API_KEY||n!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=r.pathname.split("/"),a=decodeURIComponent(s[4]||""),o=decodeURIComponent(s[5]||""),i=s[6];if(!a||!o||!i||!zt.has(i))return new Response("Not found",{status:404});try{let l=await(await X(e.AGENT,`${a}::${o}`)).inspectPersistedSession(i);return Response.json(l)}catch(c){return console.error("[agents] failed to inspect persisted session",c),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function Gs(t,e,r){var i,c;let n=new URL(t.url),s=await ut(t,e,r);if(s instanceof Response)return s;let a=await Vt(t,e);if(a instanceof Response)return a;let o=await Jt(t,e);if(o instanceof Response)return o;if(n.pathname.startsWith("/a/")){let l=n.pathname.split("/"),u=l[2],m=l[3];try{if(!u)return Response.redirect(new URL("/",n.origin).toString(),302);let f=await ne(t,e,r,u,m,!0);if(f.response)return f.response;if(!m){let p=crypto.randomUUID(),g=new URL(`/a/${u}/${p}`,n.origin);return Response.redirect(g.toString(),302)}}catch(f){return console.error("Error accessing flow KV:",f),new Response("Flow error",{status:500})}}if(n.pathname.startsWith("/api/agent/flow/")){let l=n.pathname.split("/"),u=l[4],m=l[5];return dt(t,e,r,u,m)}if(n.pathname.startsWith("/api/ora/connect")){let l=n.pathname.split("/"),u=l[4],m=l[5];if(!u||!m)return new Response("Missing flowId or sessionId",{status:400});let f=t.headers.get("Authorization")||n.searchParams.get("authorization");if(!f)return new Response("Missing Authorization header",{status:401});try{let p=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${u}`,y=await(await fetch(p,{method:"GET",headers:{Authorization:f}})).json();if(((i=y.payload)==null?void 0:i.flowId)!==u)return console.error("FlowId mismatch:",(c=y.payload)==null?void 0:c.flowId,"!==",u),new Response("Validation error",{status:403});let w=`${u}::${m}`,R=await v(t,e,r);if(!R){let $=new URL(t.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${$}) \u2014 Composio connections from tool editor will not apply`)}let S=new Headers(t.headers);S.delete("X-User-Payload"),R&&S.set("X-User-Payload",JSON.stringify(R));let U=new Request(t,{headers:S});return(await X(e.AGENT,w)).fetch(U)}catch(p){return console.error("Error in /api/ora/connect:",p),new Response("Internal error",{status:500})}}}async function dt(t,e,r,n,s){let a=`${n}::${s}`;try{let o=await ne(t,e,r,n,s);if(o.response)return o.response;let i=o.user,c=new Headers(t.headers);c.delete("X-User-Payload"),i&&c.set("X-User-Payload",JSON.stringify(i));let l=new Request(t,{headers:c});return(await X(e.AGENT,a)).fetch(l)}catch(o){return console.error("Error accessing agent:",o),new Response("Agent error",{status:500})}}var Ws=async(t,e,r,n)=>{if(!(n!=null&&n.flowId)||!Xt.test(n.flowId)||!(n!=null&&n.sessionId)||!te.test(n.sessionId))return new Response("Not found",{status:404});let s=new URL(`/api/agent/flow/${n.flowId}/${n.sessionId}`,t.url),a=new Headers;for(let[c,l]of t.headers.entries())c.toLowerCase().startsWith("x-")||a.append(c,l);let o={method:t.method,headers:a};t.body&&t.method!=="GET"&&t.method!=="HEAD"&&(o.body=t.body,o.duplex="half");let i=new Request(s.toString(),o);return dt(i,e,r,n.flowId,n.sessionId)};async function Vs(t,e,r){let n=new URL(t.url),s=t.method;if(!n.pathname.startsWith("/api/instances"))return;let a=await v(t,e,r);if(!a)return new Response("Unauthorized",{status:401});let o=e.HX_CORE_URL,i=e.HX_API_KEY;if(!o||!i)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let l=n.pathname.slice("/api/instances".length);l.startsWith("/")&&(l=l.slice(1)),l.endsWith("/")&&(l=l.slice(0,-1));let u="/ora/instances";l&&(u+=`/${l}`);let m=o.endsWith("/")?o.slice(0,-1):o,f=new URL(`${m}${u}`);n.searchParams.forEach((y,w)=>{f.searchParams.set(w,y)}),s==="GET"&&!l&&f.searchParams.set("filter_user_id",a.email);let p=new Headers;p.set("Authorization",i),p.set("Content-Type","application/json"),p.set("X-User-Payload",JSON.stringify(a));let g={method:s,headers:p};if(["POST","PATCH","PUT"].includes(s))try{g.body=await t.text()}catch(y){console.error("Error reading request body:",y)}try{let y=await fetch(f.toString(),g),w=await y.text();return new Response(w,{status:y.status,headers:{"Content-Type":"application/json"}})}catch(y){return console.error("Error proxying to flow instance backend:",y),new Response("Internal Server Error",{status:500})}}async function Bs(t,e,r){let n=new URL(t.url);if(t.method==="POST"&&n.pathname==="/auth/login")try{let s=await t.formData(),a=s.get("username"),o=s.get("password"),i=s.get("nextURL")||"/";if(!a||!o)return new Response("Missing username or password",{status:400});let c=new URLSearchParams;c.append("username",a),c.append("password",o),c.append("grant_type","password"),c.append("client_id",e.KC_CLIENT_ID),c.append("client_secret",e.KC_CLIENT_SECRET);let l=await fetch(`${e.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:c});if(!l.ok)return new Response("Unauthorized",{status:401});let u=await l.json(),m=new Response(null,{status:302,headers:{Location:i}}),p=n.protocol==="https:"?"; Secure":"",g=(y,w,R)=>{m.headers.append("Set-Cookie",`${y}=${w}; Path=/; HttpOnly${p}; SameSite=Lax; Max-Age=${R}`)};return u.access_token&&g("access_token",u.access_token,u.expires_in),u.refresh_token&&g("refresh_token",u.refresh_token,u.refresh_expires_in||3600*24*30),u.id_token&&g("id_token",u.id_token,u.expires_in),m}catch(s){return console.error("Auth error:",s),new Response("Internal Server Error",{status:500})}if(n.pathname==="/auth/logout"){let s=new Response(null,{status:302,headers:{Location:"/login"}}),a=o=>{s.headers.append("Set-Cookie",`${o}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return a("access_token"),a("refresh_token"),a("id_token"),s}if(n.pathname.startsWith("/s/")){let s=await v(t,e,r);if(!s){let a=new URL("/login",n.origin);return a.searchParams.set("nextURL",`${n.pathname}${n.search}`),Response.redirect(a.toString(),302)}return{user:s}}}import{WorkerEntrypoint as Yt}from"cloudflare:workers";import{getAgentByName as Bt}from"agents";var Zt=/^[A-Za-z0-9_-]+$/,Qt=/^art-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,pt=class extends Yt{async ask(e,r){var n,s,a,o;try{if(!e||typeof e!="string"||!Zt.test(e))throw console.error("[ArtifactWorkerGateway] invalid flowId:",e),new Error("Artifact worker request failed");if(!r||typeof r.message!="string")throw console.error("[ArtifactWorkerGateway] invalid input: message is required"),new Error("Artifact worker request failed");let i;if(r.sessionId!==void 0){if(typeof r.sessionId!="string"||!Qt.test(r.sessionId))throw console.error("[ArtifactWorkerGateway] invalid sessionId:",r.sessionId),new Error("Artifact worker request failed");i=r.sessionId}else i=`art-${crypto.randomUUID()}`;let c=(s=(n=this.ctx)==null?void 0:n.props)==null?void 0:s.slug,l=(o=(a=this.ctx)==null?void 0:a.props)==null?void 0:o.artifactUuid;if(!c||!l)throw console.error("[ArtifactWorkerGateway] missing slug or artifactUuid in gateway context props"),new Error("Artifact worker request failed");let u=this.env.ARTIFACT;if(!u)throw console.error("[ArtifactWorkerGateway] ARTIFACT binding not configured"),new Error("Artifact worker request failed");let m=u.idFromName(c),p=await u.get(m).allowsWorker({flowId:e,mode:"server",artifactUuid:l});if(!(p!=null&&p.ok))throw console.error(`[ArtifactWorkerGateway] grant check failed for flow ${e} on artifact ${c}`),new Error("Artifact worker request failed");let g=await Bt(this.env.AGENT,`${e}::${i}`),y={message:r.message};r.inputs&&typeof r.inputs=="object"&&(y.inputs=r.inputs);let w=new Request("http://localhost/message",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(y)}),R=await g.fetch(w);if(!R.ok)throw console.error(`[ArtifactWorkerGateway] agent returned status ${R.status}`),new Error("Artifact worker request failed");let S=await R.json();return{text:typeof(S==null?void 0:S.answer)=="string"?S.answer:"",sessionId:i}}catch(i){throw(i==null?void 0:i.message)==="Artifact worker request failed"?i:(console.error("[ArtifactWorkerGateway] unexpected error in ask:",i),new Error("Artifact worker request failed"))}}};export{gt as ANONYMOUS_RUN_USER_PREFIX,et as AgentDO,pt as ArtifactWorkerGateway,Wn as CRAWL_DEFAULTS,Xn as CRAWL_LIMITS,mn as DEFAULT_MEMORY_LENGTH,gn as DEFAULT_MEMORY_MODEL,ln as FLOW_INPUT_NAME_RE,hr as FlowExecutionStoppedError,Bn as GENERATION_PARAM_KEYS,Qn as GENERATION_PRESETS,dn as MAX_USER_IDENTITY_LENGTH,pn as MEMORY_LENGTH_MD_LINES,fn as MEMORY_LENGTH_TOKENS,wr as MODEL_REGISTRY_SNAPSHOT,F as NodeType,wn as OUT_VAR_NAME_RE,Zn as PRESET_PARAM_KEYS,ur as REASONING_EFFORT_LEVELS,qn as TENANT_ONLY_NODES,yr as TOOL_REGISTRY_SNAPSHOT,ot as TRIGGER_NONCE_HEADER,rt as TRIGGER_SIGNATURE_HEADER,bs as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,at as TRIGGER_TENANT_HEADER,st as TRIGGER_TIMESTAMP_HEADER,vn as VariableResolutionError,nr as applyPresetToOverrides,Ws as artifactAgentProxy,zn as buildCrawlRequestBody,$e as buildReasoningProviderOptions,Tn as buildScope,Os as buildSignedTriggerHeaders,Ee as buildTriggerMessageText,rn as buildUrl,Ht as canonicalUserEmail,ke as capMemoryContent,N as claimRun,H as clearAllMessages,K as completeRun,en as convertTempMessure,Vn as crawlRequestKey,B as createRun,er as deriveParamSupport,tt as dispatchTrigger,an as embedText,je as ensureAgentTables,mt as ensureMessagesTable,hn as estimateTokens,Nn as extractOutVarValues,Fn as extractTemplateReferences,ve as extractUserKeypoints,kn as findScopedSourceNode,dt as forwardToAgentFlow,O as getAllMessages,In as getAncestorNodeIds,Rn as getDefaultOutVars,En as getEffectiveOutVars,Se as getFlowInputDefs,Rr as getModelEntry,An as getRefTail,xn as getUpstreamOutVars,Gs as handleAgentsRoutes,Bs as handleAuthRoutes,Ts as handleCommonRoutes,Vs as handleIntancesRoutes,Jt as handlePersistedSessionInspection,Vt as handleSessionRunControl,ut as handleTriggerRoutes,on as hashText,M as initializeEngineState,Un as isBinaryOutVar,_n as isJsonContentType,Gn as isNodeTypeAllowedForTenant,Ae as isStartMemoryEnabled,Kn as jsonSchemaToZod,Re as logc,Oe as looksLikeTranscript,be as memoryGenerationMaxTokens,L as memoryMdLineLimit,Te as memoryTokenLimit,Ce as mergeKeypointMemory,I as messageTypes,Gt as normalizeDestination,sr as normalizeEffectiveParams,un as normalizeFlowInputs,mr as normalizeModelEntry,dr as normalizeReasoning,ar as openAiReasoningParamSupport,or as openAiStandardParamSupport,W as parseCookies,yn as parseMemoryLength,bn as parsePayloadText,$n as parseTemplateExpression,xe as parseUserAuth,Ie as parseUserMessage,rr as pickNodeOverrides,On as readFetchPayload,pr as reasoningEffortLevels,fr as reasoningExposable,qe as recordRun,gr as registerProvider,jn as resolveAnswerMappings,Fe as resolveModelById,Dn as resolveOutVarRef,Pn as resolveOutVarValue,tr as resolvePreset,De as resolveReasoningEffort,Mn as resolveReference,Ke as resolveRunUserId,Hn as resolveTemplate,Ln as rewriteTemplateNodeRefs,D as runAgentTurn,Yn as runCrawl,nn as safeParseJSON,J as sanitizeMemoryDocument,P as sanitizeUserIdentity,Je as sendEvent,k as serverSend,He as setMessage,Jn as shapeCrawlOutput,ct as signTriggerMaterial,Le as startEngine,_e as startMemoryLength,Ue as startMemoryModel,lr as stripUnsupportedFromNodeData,tn as tempTool,Wt as timingSafeEqualHex,Me as toStreamTextSettings,it as triggerSignatureMaterial,sn as twitter,ws as validateFlowStart,Sn as validateOutVars,cn as vectorize,jt as verifyToken,lt as verifyTriggerRequest,v as verifyUser,Cn as walkPath,cr as workersAiParamSupport,ir as xaiParamSupport};
7
+ -----END PUBLIC KEY-----`,n=await Ft(r,"RS256");try{let{payload:s,protectedHeader:a}=await Lt(e,n);return{ok:!0,payload:s,protectedHeader:a}}catch(s){return console.error("JWT verification failed:",s),{ok:!1,payload:null,protectedHeader:null}}}async function Ds(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 X}from"agents";import{getAgentByName as Kt}from"agents";async function tt(t,e){let r=e.sessionId||e.runAsUserId,n=e.inputs||{},s=e.runId;if(!s){let c=await B(t,{tenant:e.tenant,flowId:e.flowId,userId:e.runAsUserId,sessionId:r,triggerId:e.triggerId,triggerKind:e.triggerKind,invocationMode:e.invocationMode,activationId:e.activationId,deliveryId:void 0,externalDeliveryId:e.externalDeliveryId,correlationKey:e.correlationKey,inputs:n,label:e.label});if(!c)return{status:"error",error:"Failed to register run"};if(!c.created&&c.run.status!=="queued")return{status:"deduped",runId:c.run.id};s=c.run.id}let a={...e,sessionId:r,runId:s,inputs:n},i=await(await Kt(t.AGENT,`${e.flowId}::${r}`)).enqueueTrigger(a);return i.duplicate?{status:"deduped",runId:s}:i.queued?{status:"queued",runId:s,activation:a,taskId:i.taskId}:{status:"error",error:"Failed to queue trigger"}}var rt="x-ora-signature",st="x-ora-timestamp",ot="x-ora-nonce",at="x-ora-tenant",js=300,nt=new TextEncoder;function qt(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function Gt(t){try{let e=new URL(t);return`${e.origin}${e.pathname.replace(/\/$/,"")}`}catch{return t.replace(/\/$/,"")}}function it(t){return["v1",t.timestamp,t.nonce,t.tenant,Gt(t.destination),t.body].join(`
8
+ `)}async function ct(t,e){let r=await crypto.subtle.importKey("raw",nt.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return qt(await crypto.subtle.sign("HMAC",r,nt.encode(e)))}function Wt(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 Ks(t){let e=String(t.timestamp??Math.floor(Date.now()/1e3)),r=await ct(t.secret,it({timestamp:e,nonce:t.nonce,tenant:t.tenant,destination:t.destination,body:t.body}));return{"content-type":"application/json",[at]:t.tenant,[st]:e,[ot]:t.nonce,[rt]:`v1=${r}`}}async function lt(t){var l,u,m,f,p;if(!((l=t.secret)!=null&&l.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(u=t.headers.get(at))==null?void 0:u.trim(),r=(m=t.headers.get(st))==null?void 0:m.trim(),n=(f=t.headers.get(ot))==null?void 0:f.trim(),s=(p=t.headers.get(rt))==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 a=Number(r);if(!Number.isFinite(a))return{ok:!1,error:"invalid timestamp"};let o=Math.floor((t.now??Date.now())/1e3),i=t.toleranceSeconds??300;if(Math.abs(o-a)>i)return{ok:!1,error:"stale timestamp"};let c=await ct(t.secret.trim(),it({timestamp:r,nonce:n,tenant:e,destination:t.url,body:t.body}));return Wt(s.slice(3),c)?{ok:!0,tenant:e,nonce:n,timestamp:a}:{ok:!1,error:"signature mismatch"}}var A=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}});async function ut(t,e,r){var l;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(),a=await lt({secret:e.HX_API_KEY,body:s,url:t.url,headers:t.headers});if(!a.ok)return console.warn(`[triggers] rejected dispatch: ${a.error}`),A({error:"Invalid signature"},401);let o;try{o=JSON.parse(s)}catch{return A({error:"Invalid payload"},400)}if(!(o!=null&&o.runId)||!(o!=null&&o.flowId)||!(o!=null&&o.runAsUserId)||!(o!=null&&o.tenant)||!(o!=null&&o.activationId)||!(o!=null&&o.triggerId)||!(o!=null&&o.triggerKind)||!(o!=null&&o.invocationMode))return A({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(o.tenant!==a.tenant)return A({error:"Tenant mismatch"},403);let i;try{i=await b(o.flowId,e)}catch{return A({error:"Flow not found"},404)}if(!((l=i==null?void 0:i.metadata)!=null&&l.tenant)||i.metadata.tenant!==o.tenant)return console.warn(`[triggers] flow ${o.flowId} does not belong to tenant ${o.tenant}`),A({error:"Tenant mismatch"},403);let c=await tt(e,{...o,sessionId:o.sessionId||o.runAsUserId,nonce:a.nonce});return c.status==="error"?A({error:c.error},502):c.status==="deduped"?A({deduped:!0,runId:c.runId},200):A({accepted:!0,runId:c.runId,taskId:c.taskId},202)}var te=/^[A-Za-z0-9_-]{1,64}$/;async function ne(t,e,r,n,s,a=!1){let o=(f,p)=>({response:new Response(f,{status:p})});if(!/^[A-Za-z0-9_-]+$/.test(n))return o("Invalid flowId",400);if((!a||s)&&(!s||!te.test(s)))return o("Invalid sessionId",400);let i;try{i=await b(n,e)}catch{return o("Flow not found",404)}let c=i==null?void 0:i.metadata;if(!c||!["active","activo"].includes(c.status))return o("Flow not found",404);if(!e.TENANT||c.tenant!==e.TENANT)return o("Forbidden",403);let l=await v(t,e,r),u=l&&typeof l=="object"?l:void 0;if(u&&u.tenant!==e.TENANT)return o("Forbidden",403);if(c.visibility==="public")return{user:u};if(!u){if(!a)return o("Unauthorized",401);let f=new URL(t.url),p=new URL("/login",f.origin);return p.searchParams.set("nextURL",`${f.pathname}${f.search}`),{response:Response.redirect(p.toString(),302)}}if((c.org||"default")!==(u.org||"default"))return o("Forbidden",403);let m=W(t.headers.get("cookie")).access_token||new URL(t.url).searchParams.get("access_token");if(!m)return o("Unauthorized",401);try{let f=await fetch(`${e.HX_CORE_URL}/flows/${encodeURIComponent(n)}`,{headers:{Authorization:m},cache:"no-store"});if(!f.ok||(await f.json()).id!==n)return o("Forbidden",403)}catch{return o("Forbidden",403)}return{user:u}}var Xt=/^[A-Za-z0-9_-]+$/,zt=new Set(["state","messages","memory"]);async function Vt(t,e){let r=new URL(t.url);if(!r.pathname.startsWith("/api/internal/sessions/"))return;let n=r.pathname.split("/");if(n[6]!=="runs"||n[8]!=="stop"||n.length!==9)return;if(t.method!=="POST")return new Response("Method not allowed",{status:405});if(!e.HX_API_KEY||t.headers.get("Authorization")!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=decodeURIComponent(n[4]||""),a=decodeURIComponent(n[5]||""),o=decodeURIComponent(n[7]||"");if(!s||!a||!o)return new Response("Not found",{status:404});try{let i=await X(e.AGENT,`${s}::${a}`);return Response.json(await i.requestRunStop(o))}catch(i){return console.error("[agents] failed to request run stop",i),Response.json({error:"Failed to stop run"},{status:502})}}async function Jt(t,e){let r=new URL(t.url);if(!r.pathname.startsWith("/api/internal/sessions/"))return;if(t.method!=="GET")return new Response("Method not allowed",{status:405});let n=t.headers.get("Authorization")||"";if(!e.HX_API_KEY||n!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=r.pathname.split("/"),a=decodeURIComponent(s[4]||""),o=decodeURIComponent(s[5]||""),i=s[6];if(!a||!o||!i||!zt.has(i))return new Response("Not found",{status:404});try{let l=await(await X(e.AGENT,`${a}::${o}`)).inspectPersistedSession(i);return Response.json(l)}catch(c){return console.error("[agents] failed to inspect persisted session",c),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function no(t,e,r){var i,c;let n=new URL(t.url),s=await ut(t,e,r);if(s instanceof Response)return s;let a=await Vt(t,e);if(a instanceof Response)return a;let o=await Jt(t,e);if(o instanceof Response)return o;if(n.pathname.startsWith("/a/")){let l=n.pathname.split("/"),u=l[2],m=l[3];try{if(!u)return Response.redirect(new URL("/",n.origin).toString(),302);let f=await ne(t,e,r,u,m,!0);if(f.response)return f.response;if(!m){let p=crypto.randomUUID(),g=new URL(`/a/${u}/${p}`,n.origin);return Response.redirect(g.toString(),302)}}catch(f){return console.error("Error accessing flow KV:",f),new Response("Flow error",{status:500})}}if(n.pathname.startsWith("/api/agent/flow/")){let l=n.pathname.split("/"),u=l[4],m=l[5];return dt(t,e,r,u,m)}if(n.pathname.startsWith("/api/ora/connect")){let l=n.pathname.split("/"),u=l[4],m=l[5];if(!u||!m)return new Response("Missing flowId or sessionId",{status:400});let f=t.headers.get("Authorization")||n.searchParams.get("authorization");if(!f)return new Response("Missing Authorization header",{status:401});try{let p=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${u}`,y=await(await fetch(p,{method:"GET",headers:{Authorization:f}})).json();if(((i=y.payload)==null?void 0:i.flowId)!==u)return console.error("FlowId mismatch:",(c=y.payload)==null?void 0:c.flowId,"!==",u),new Response("Validation error",{status:403});let w=`${u}::${m}`,R=await v(t,e,r);if(!R){let $=new URL(t.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${$}) \u2014 Composio connections from tool editor will not apply`)}let S=new Headers(t.headers);S.delete("X-User-Payload"),R&&S.set("X-User-Payload",JSON.stringify(R));let U=new Request(t,{headers:S});return(await X(e.AGENT,w)).fetch(U)}catch(p){return console.error("Error in /api/ora/connect:",p),new Response("Internal error",{status:500})}}}async function dt(t,e,r,n,s){let a=`${n}::${s}`;try{let o=await ne(t,e,r,n,s);if(o.response)return o.response;let i=o.user,c=new Headers(t.headers);c.delete("X-User-Payload"),i&&c.set("X-User-Payload",JSON.stringify(i));let l=new Request(t,{headers:c});return(await X(e.AGENT,a)).fetch(l)}catch(o){return console.error("Error accessing agent:",o),new Response("Agent error",{status:500})}}var ro=async(t,e,r,n)=>{if(!(n!=null&&n.flowId)||!Xt.test(n.flowId)||!(n!=null&&n.sessionId)||!te.test(n.sessionId))return new Response("Not found",{status:404});let s=new URL(`/api/agent/flow/${n.flowId}/${n.sessionId}`,t.url),a=new Headers;for(let[c,l]of t.headers.entries())c.toLowerCase().startsWith("x-")||a.append(c,l);let o={method:t.method,headers:a};t.body&&t.method!=="GET"&&t.method!=="HEAD"&&(o.body=t.body,o.duplex="half");let i=new Request(s.toString(),o);return dt(i,e,r,n.flowId,n.sessionId)};async function ao(t,e,r){let n=new URL(t.url),s=t.method;if(!n.pathname.startsWith("/api/instances"))return;let a=await v(t,e,r);if(!a)return new Response("Unauthorized",{status:401});let o=e.HX_CORE_URL,i=e.HX_API_KEY;if(!o||!i)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let l=n.pathname.slice("/api/instances".length);l.startsWith("/")&&(l=l.slice(1)),l.endsWith("/")&&(l=l.slice(0,-1));let u="/ora/instances";l&&(u+=`/${l}`);let m=o.endsWith("/")?o.slice(0,-1):o,f=new URL(`${m}${u}`);n.searchParams.forEach((y,w)=>{f.searchParams.set(w,y)}),s==="GET"&&!l&&f.searchParams.set("filter_user_id",a.email);let p=new Headers;p.set("Authorization",i),p.set("Content-Type","application/json"),p.set("X-User-Payload",JSON.stringify(a));let g={method:s,headers:p};if(["POST","PATCH","PUT"].includes(s))try{g.body=await t.text()}catch(y){console.error("Error reading request body:",y)}try{let y=await fetch(f.toString(),g),w=await y.text();return new Response(w,{status:y.status,headers:{"Content-Type":"application/json"}})}catch(y){return console.error("Error proxying to flow instance backend:",y),new Response("Internal Server Error",{status:500})}}async function lo(t,e,r){let n=new URL(t.url);if(t.method==="POST"&&n.pathname==="/auth/login")try{let s=await t.formData(),a=s.get("username"),o=s.get("password"),i=s.get("nextURL")||"/";if(!a||!o)return new Response("Missing username or password",{status:400});let c=new URLSearchParams;c.append("username",a),c.append("password",o),c.append("grant_type","password"),c.append("client_id",e.KC_CLIENT_ID),c.append("client_secret",e.KC_CLIENT_SECRET);let l=await fetch(`${e.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:c});if(!l.ok)return new Response("Unauthorized",{status:401});let u=await l.json(),m=new Response(null,{status:302,headers:{Location:i}}),p=n.protocol==="https:"?"; Secure":"",g=(y,w,R)=>{m.headers.append("Set-Cookie",`${y}=${w}; Path=/; HttpOnly${p}; SameSite=Lax; Max-Age=${R}`)};return u.access_token&&g("access_token",u.access_token,u.expires_in),u.refresh_token&&g("refresh_token",u.refresh_token,u.refresh_expires_in||3600*24*30),u.id_token&&g("id_token",u.id_token,u.expires_in),m}catch(s){return console.error("Auth error:",s),new Response("Internal Server Error",{status:500})}if(n.pathname==="/auth/logout"){let s=new Response(null,{status:302,headers:{Location:"/login"}}),a=o=>{s.headers.append("Set-Cookie",`${o}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return a("access_token"),a("refresh_token"),a("id_token"),s}if(n.pathname.startsWith("/s/")){let s=await v(t,e,r);if(!s){let a=new URL("/login",n.origin);return a.searchParams.set("nextURL",`${n.pathname}${n.search}`),Response.redirect(a.toString(),302)}return{user:s}}}import{WorkerEntrypoint as Yt}from"cloudflare:workers";import{getAgentByName as Bt}from"agents";var Zt=/^[A-Za-z0-9_-]+$/,Qt=/^art-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,pt=class extends Yt{async ask(e,r){var n,s,a,o;try{if(!e||typeof e!="string"||!Zt.test(e))throw console.error("[ArtifactWorkerGateway] invalid flowId:",e),new Error("Artifact worker request failed");if(!r||typeof r.message!="string")throw console.error("[ArtifactWorkerGateway] invalid input: message is required"),new Error("Artifact worker request failed");let i;if(r.sessionId!==void 0){if(typeof r.sessionId!="string"||!Qt.test(r.sessionId))throw console.error("[ArtifactWorkerGateway] invalid sessionId:",r.sessionId),new Error("Artifact worker request failed");i=r.sessionId}else i=`art-${crypto.randomUUID()}`;let c=(s=(n=this.ctx)==null?void 0:n.props)==null?void 0:s.slug,l=(o=(a=this.ctx)==null?void 0:a.props)==null?void 0:o.artifactUuid;if(!c||!l)throw console.error("[ArtifactWorkerGateway] missing slug or artifactUuid in gateway context props"),new Error("Artifact worker request failed");let u=this.env.ARTIFACT;if(!u)throw console.error("[ArtifactWorkerGateway] ARTIFACT binding not configured"),new Error("Artifact worker request failed");let m=u.idFromName(c),p=await u.get(m).allowsWorker({flowId:e,mode:"server",artifactUuid:l});if(!(p!=null&&p.ok))throw console.error(`[ArtifactWorkerGateway] grant check failed for flow ${e} on artifact ${c}`),new Error("Artifact worker request failed");let g=await Bt(this.env.AGENT,`${e}::${i}`),y={message:r.message};r.inputs&&typeof r.inputs=="object"&&(y.inputs=r.inputs);let w=new Request("http://localhost/message",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(y)}),R=await g.fetch(w);if(!R.ok)throw console.error(`[ArtifactWorkerGateway] agent returned status ${R.status}`),new Error("Artifact worker request failed");let S=await R.json();return{text:typeof(S==null?void 0:S.answer)=="string"?S.answer:"",sessionId:i}}catch(i){throw(i==null?void 0:i.message)==="Artifact worker request failed"?i:(console.error("[ArtifactWorkerGateway] unexpected error in ask:",i),new Error("Artifact worker request failed"))}}};export{gt as ANONYMOUS_RUN_USER_PREFIX,et as AgentDO,pt as ArtifactWorkerGateway,fn as CLASSIFIER_DEFAULTS,mn as CLASSIFIER_RESERVED_HANDLES,pn as CLEF_MODELS,Vn as CRAWL_DEFAULTS,Jn as CRAWL_LIMITS,Rn as DEFAULT_MEMORY_LENGTH,Sn as DEFAULT_MEMORY_MODEL,ln as FLOW_INPUT_NAME_RE,Ur as FlowExecutionStoppedError,cr as GENERATION_PARAM_KEYS,ur as GENERATION_PRESETS,dn as MAX_USER_IDENTITY_LENGTH,hn as MEMORY_LENGTH_MD_LINES,wn as MEMORY_LENGTH_TOKENS,_r as MODEL_REGISTRY_SNAPSHOT,F as NodeType,xn as OUT_VAR_NAME_RE,lr as PRESET_PARAM_KEYS,Er as REASONING_EFFORT_LEVELS,Or as TENANT_ONLY_NODES,ir as TOOL_REGISTRY_SNAPSHOT,ot as TRIGGER_NONCE_HEADER,rt as TRIGGER_SIGNATURE_HEADER,js as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,at as TRIGGER_TENANT_HEADER,st as TRIGGER_TIMESTAMP_HEADER,Dn as VariableResolutionError,fr as applyPresetToOverrides,ro as artifactAgentProxy,er as buildClefRequest,Yn as buildCrawlRequestBody,$e as buildReasoningProviderOptions,bn as buildScope,Ks as buildSignedTriggerHeaders,Ee as buildTriggerMessageText,rn as buildUrl,Ht as canonicalUserEmail,ke as capMemoryContent,N as claimRun,or as classifierErrorResult,gn as classifierHandle,H as clearAllMessages,nr as clefTruncationWarning,K as completeRun,en as convertTempMessure,Bn as crawlRequestKey,B as createRun,dr as deriveParamSupport,tt as dispatchTrigger,an as embedText,je as ensureAgentTables,mt as ensureMessagesTable,tr as estimateClefTokens,In as estimateTokens,Ln as extractOutVarValues,qn as extractTemplateReferences,ve as extractUserKeypoints,On as findScopedSourceNode,dt as forwardToAgentFlow,O as getAllMessages,Un as getAncestorNodeIds,Tn as getDefaultOutVars,An as getEffectiveOutVars,Se as getFlowInputDefs,br as getModelEntry,vn as getRefTail,_n as getUpstreamOutVars,no as handleAgentsRoutes,lo as handleAuthRoutes,Ds as handleCommonRoutes,ao as handleIntancesRoutes,Jt as handlePersistedSessionInspection,Vt as handleSessionRunControl,ut as handleTriggerRoutes,on as hashText,M as initializeEngineState,Cn as isBinaryOutVar,Pn as isJsonContentType,vr as isNodeTypeAllowedForTenant,Ae as isStartMemoryEnabled,zn as jsonSchemaToZod,Re as logc,Oe as looksLikeTranscript,be as memoryGenerationMaxTokens,L as memoryMdLineLimit,Te as memoryTokenLimit,Ce as mergeKeypointMemory,I as messageTypes,Gt as normalizeDestination,gr as normalizeEffectiveParams,un as normalizeFlowInputs,kr as normalizeModelEntry,Ir as normalizeReasoning,hr as openAiReasoningParamSupport,yr as openAiStandardParamSupport,sr as parseClefResponse,W as parseCookies,En as parseMemoryLength,Nn as parsePayloadText,Kn as parseTemplateExpression,xe as parseUserAuth,Ie as parseUserMessage,mr as pickNodeOverrides,Mn as readFetchPayload,xr as reasoningEffortLevels,Tr as reasoningExposable,qe as recordRun,Ar as registerProvider,Xn as resolveAnswerMappings,Fe as resolveModelById,jn as resolveOutVarRef,Fn as resolveOutVarValue,pr as resolvePreset,De as resolveReasoningEffort,Hn as resolveReference,Ke as resolveRunUserId,Wn as resolveTemplate,Gn as rewriteTemplateNodeRefs,D as runAgentTurn,rr as runClef,Qn as runCrawl,nn as safeParseJSON,J as sanitizeMemoryDocument,P as sanitizeUserIdentity,ar as selectClefHistory,Je as sendEvent,k as serverSend,He as setMessage,Zn as shapeCrawlOutput,ct as signTriggerMaterial,Le as startEngine,_e as startMemoryLength,Ue as startMemoryModel,Sr as stripUnsupportedFromNodeData,tn as tempTool,Wt as timingSafeEqualHex,Me as toStreamTextSettings,it as triggerSignatureMaterial,sn as twitter,yn as validateClassifierData,Os as validateFlowStart,kn as validateOutVars,cn as vectorize,jt as verifyToken,lt as verifyTriggerRequest,v as verifyUser,$n as walkPath,Rr as workersAiParamSupport,wr as xaiParamSupport};
@@ -1,6 +1,6 @@
1
1
  import type { SessionEnv } from '../core/AgentDO';
2
2
  import type { FlowEngineEvent, FlowEngineState } from '../logic/FlowEngine';
3
- export default function classifierNodeRunner(sessionEnv: SessionEnv, node: any, engineState: FlowEngineState, onServerEvent?: (event: FlowEngineEvent) => void, onResult?: (key: string, result: any) => void, onChangeState?: (state: FlowEngineState) => void, onTelemetry?: (event: {
3
+ export default function classifierNodeRunner(sessionEnv: SessionEnv, node: any, engineState: FlowEngineState, onServerEvent?: (event: FlowEngineEvent) => void, onResult?: (key: string, result: any) => void, _onChangeState?: (state: FlowEngineState) => void, onTelemetry?: (event: {
4
4
  type: string;
5
5
  payload: any;
6
6
  }) => void): Promise<void>;
@@ -0,0 +1 @@
1
+ export * from '../../common/utils/clef';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hugex/ai",
3
- "version": "3.2.0-canary.3",
3
+ "version": "3.3.0",
4
4
  "description": "Ora AI Agent Framework",
5
5
  "author": "a@hugex.co",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -1,10 +0,0 @@
1
- var we={USER_MESSAGE:"M",USER_CLEAR_HISTORY:"CH",USER_AUTH:"AUT",USER_IDENTITY:"UID",SERVER_EVENT:"SE",SERVER_HISTORY:"HIS",SERVER_ERROR:"ERR",SERVER_STEP:"STEP",SERVER_TEXT_STREAM:"TS",SERVER_TEXT_STREAM_COMPLETE:"TSC",SERVER_REASONING_STREAM:"RS",SERVER_REASONING_STREAM_COMPLETE:"RSC",SERVER_CONFIG:"CFG"};function Ee(e){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t}catch{}return{text:e}}var Z=256;function Re(e){if(typeof e!="string")return null;let t=e.trim();return t?t.slice(0,Z):null}function be(e){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.name=="string"&&typeof t.value=="string"){let n=t.name.trim();return/^[A-Z][A-Z0-9_]*$/.test(n)?{name:n,value:t.value}:null}}catch{}return null}var X={short:100,medium:250,long:1e3},Q={short:2e3,medium:5e3,long:2e4},L="medium",ee="gpt_5_nano",F=4;function te(e){return e==="short"||e==="medium"||e==="long"?e:L}function ne(e=L){return Q[e]}function Te(e=L){return X[e]}function re(e){return e?Math.ceil(e.length/F):0}function oe(e,t){if(!e)return{content:"",truncated:!1};if(re(e)<=t)return{content:e,truncated:!1};let n=Math.max(0,t*F);return{content:e.slice(0,n),truncated:!0}}function Ce(e){let t=e==null?void 0:e.memory_enabled;return t===!0||t==="true"||t===1}function Me(e){let t=e==null?void 0:e.memory_model;return typeof t=="string"&&t.trim()?t.trim():ee}function ke(e){return te(e==null?void 0:e.memory_length)}function ve(e,t){let n=ne(e);return t&&t!=="none"?n+2048:n}var H=/^(user|assistant|usuario|asistente|u|a)\s*:/i,se=/^(hola|hello|hi|hey|buenas|buen[oa]s?\s+d[ií]as?|qu[eé]\s+tal|qu[eé]\s+haces)[\s,.!¡¿?]*$/i;function ie(e){let t=e.split(`
2
- `).map(r=>r.replace(/^[-*]\s*/,"").trim()).filter(Boolean);if(t.length<2)return!1;let n=t.filter(r=>H.test(r));return n.length>=2&&n.length>=Math.ceil(t.length/2)}function ae(e){let t=e.split(`
3
- `).map(n=>n.trim()).filter(Boolean).filter(n=>n!=="(empty)"&&n!=="(none)").filter(n=>!H.test(n.replace(/^[-*]\s*/,"")));return ie(t.join(`
4
- `))?"":t.join(`
5
- `)}function Oe(e){let t=e.trim();if(!t||se.test(t))return[];let n=[],r=t.match(/(?:me llamo|soy|i['’]m|i am|my name is)\s+([A-Za-zÁÉÍÓÚÜáéíóúüñÑ][\wÁÉÍÓÚÜáéíóúüñÑ'-]{1,40})/i);r&&n.push(`Name: ${r[1]}`);let i=t.match(/me gusta[n]?\s+([^,.!?]+)/i);if(i&&n.push(`Likes: ${i[1].trim()}`),/[?¿]/.test(t)||/^(pregunt|dime\b|cu[eé]nt)/i.test(t))return n;let m=t.replace(/^(hola|hey|hi)[,\s]+/i,"").replace(/(?:me llamo|soy)\s+[A-Za-zÁÉÍÓÚÜáéíóúüñÑ][\wÁÉÍÓÚÜáéíóúüñÑ'-]*/gi,"").replace(/me gusta[n]?\s+[^,.!?]+/gi,"").replace(/[,.\s]+/g," ").trim();return m.length>=16&&n.push(m.slice(0,140)),n}function _e(e,t,n){let i=[...ae(e).split(`
6
- `).map(s=>s.replace(/^[-*]\s*/,"").trim()).filter(Boolean)];for(let s of t){let m=s.replace(/^[-*]\s*/,"").trim();m&&(i.some(a=>a.toLowerCase()===m.toLowerCase())||i.push(m))}return i.length===0?"":oe(i.map(s=>`- ${s}`).join(`
7
- `),n).content}var Y={crawlNode:["cx_hugex"],toolNode:["cx_hugex"]};function Ie(e,t){let n=Object.hasOwn(Y,e)?Y[e]:void 0;return n===void 0||!!t&&n.includes(t)}var P={source:"all",limit:5,depth:2,render:!1,format:"markdown",includeSubdomains:!1,waitTimeoutMs:6e4,maxAgeS:86400,maxCharsPerPage:4e3},S={limit:50,depth:10,waitTimeoutMs:12e4,maxAgeS:604800,maxOutputBytes:256*1024};function v(e,t,n,r=0){return Math.min(n,Math.max(r,Math.floor(typeof e=="number"&&Number.isFinite(e)?e:t)))}function ue(e,t,n){let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error("Crawl URL must use http(s)");let i=e.format??P.format;return{url:r.href,source:e.source??P.source,limit:v(e.limit,P.limit,S.limit,1),depth:v(e.depth,P.depth,S.depth),render:e.render??P.render,formats:[i],...i==="json"?{jsonOptions:{...e.jsonPrompt!==void 0?{prompt:e.jsonPrompt}:{},...e.jsonSchema!==void 0?{response_format:e.jsonSchema}:{}}}:{},maxAge:v((n==null?void 0:n.maxAgeOverrideS)??e.maxAgeS,P.maxAgeS,S.maxAgeS),options:{includeExternalLinks:!1,includeSubdomains:e.includeSubdomains??P.includeSubdomains,includePatterns:e.includePatterns??[],excludePatterns:e.excludePatterns??[]}}}function I(e){return Array.isArray(e)?e.map(I):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,I(n)])):e}async function qe(e){let t=new TextEncoder().encode(JSON.stringify(I(e))),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}function le(e,t){let n=t.split(/(\*\*|\*)/).map(r=>r==="**"?".*":r==="*"?"[^/]*":r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("");return new RegExp(`^${n}$`).test(e)}function z(e,t,n){let r=(t==null?void 0:t.mode)??"pages",i=(t==null?void 0:t.fields)??["url","title",n],s=v(t==null?void 0:t.maxCharsPerPage,P.maxCharsPerPage,S.maxOutputBytes),m=e;if(r==="single"){let o=t==null?void 0:t.select,l=(o==null?void 0:o.url)!==void 0?e.find(u=>u.url===o.url):(o==null?void 0:o.pattern)!==void 0?e.find(u=>le(u.url,o.pattern)):e[(o==null?void 0:o.index)??0];m=l?[l]:[]}let a=!1,c=m.map(o=>{let l={url:o.url,status:o.status};o.httpStatus!==void 0&&(l.httpStatus=o.httpStatus),i.includes("title")&&o.title!==void 0&&(l.title=o.title);let u=o.truncated??!1;if(i.includes("markdown")&&o.markdown!==void 0&&(l.markdown=o.markdown.slice(0,s),u||=l.markdown.length<o.markdown.length),i.includes("json")&&o.json!==void 0){let T=o.truncated&&typeof o.json=="string"?o.json:JSON.stringify(o.json);l.json=T.length>s?T.slice(0,s):o.json,u||=T.length>s}return u&&(l.truncated=!0),a||=u,l});if(r!=="concat")return{pages:c,truncated:a};let d=c.map(o=>i.map(l=>{let u=o[l];return u===void 0?"":typeof u=="string"?u:JSON.stringify(u)}).filter(Boolean).join(`
8
- `)).join(`
9
-
10
- `);return{pages:[],text:d,truncated:a}}var B=e=>new TextEncoder().encode(JSON.stringify(e)).byteLength;async function Ue(e,t,n){var K,D,G;let r=Date.now(),i=r+v(t.waitTimeoutMs,P.waitTimeoutMs,S.waitTimeoutMs),s=n.fetchImpl??fetch,m=n.sleep??(g=>new Promise(w=>setTimeout(w,g))),a=n.resumeJobId??null,c={status:"running"},d=[],o=!1,l=2,u=()=>Math.max(0,i-Date.now()),T=async g=>{if(!u())throw new Error("timeout");if(await m(Math.min(g,u())),!u())throw new Error("timeout")},N=async(g,w)=>{var E,h,p,b,y;for(let R=0;;R++){if(!u())throw new Error("timeout");let f=new AbortController,M,k=new Promise((x,C)=>{M=setTimeout(()=>{f.abort(),C(new Error("timeout"))},u())});try{let x=await Promise.race([s(g,{...w,signal:f.signal,headers:{Authorization:`Bearer ${e.apiToken}`,"Content-Type":"application/json"}}),k]);if(x.status===429&&R<2){let O=x.headers.get("Retry-After"),$=O===null?NaN:Number(O),W=Number.isFinite($)?Math.max(0,$*1e3):O?Math.max(0,Date.parse(O)-Date.now()):2e3;await((E=x.body)==null?void 0:E.cancel()),clearTimeout(M),await T(Number.isFinite(W)?W:2e3);continue}let C=await Promise.race([x.json(),k]);if(C.success===!1)throw new Error(((p=(h=C.errors)==null?void 0:h[0])==null?void 0:p.message)??"Crawl API error");if(!x.ok)throw new Error(((y=(b=C.errors)==null?void 0:b[0])==null?void 0:y.message)??`Crawl API HTTP ${x.status}`);if(!u())throw new Error("timeout");return C}catch(x){throw f.signal.aborted||!u()?new Error("timeout"):x}finally{clearTimeout(M)}}},U=(g,w)=>{let E=()=>z(d.filter(b=>b.status==="completed"),t.output,t.format??"markdown"),h=E(),p={ok:g,error:w,data:a?{jobId:a,status:w==="timeout"?"running":c.status,total:c.total??0,finished:c.finished??0,browserSeconds:c.browserSecondsUsed??0,elapsedMs:Date.now()-r,...h,truncated:o||h.truncated}:null};for(;B(p)>S.maxOutputBytes&&d.length;)d.pop(),h=E(),Object.assign(p.data,h,{truncated:!0});return{result:p,allPages:d}};try{if(!e.accountId||!e.apiToken)throw new Error("Crawl no configurado: faltan CF_ACCOUNT_ID / CF_BROWSER_RUN_TOKEN");let g=ue(t,n.url,n),w=`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(e.accountId)}/browser-run/crawl`;if(!a){let y=await N(w,{method:"POST",body:JSON.stringify(g)});if(typeof y.result!="string"||!y.result)throw new Error("Crawl API returned no jobId");a=y.result}let E=`${w}/${encodeURIComponent(a)}`,h=2e3;do{let y=await N(`${E}?limit=1`);if(!y.result||typeof y.result!="object"||!y.result.status)throw new Error("Crawl API returned no status");if(c=y.result,c.status!=="running")break;await T(h),h=Math.min(5e3,h+1e3)}while(u());let p,b=new Set;do{let y=p===void 0?"":`?cursor=${encodeURIComponent(p)}`,R=await N(`${E}${y}`);if(!R.result||typeof R.result!="object")throw new Error("Crawl API returned invalid results");c={...c,...R.result};for(let f of R.result.records??[]){let M={url:f.url,status:f.status,...((K=f.metadata)==null?void 0:K.title)!==void 0?{title:f.metadata.title}:{},...((D=f.metadata)==null?void 0:D.status)!==void 0?{httpStatus:f.metadata.status}:{},...f.markdown!==void 0?{markdown:f.markdown}:{},...f.json!==void 0?{json:f.json}:{}},k=z([M],{mode:"pages",maxCharsPerPage:(G=t.output)==null?void 0:G.maxCharsPerPage},t.format??"markdown").pages[0],x=B(k)+1;if(l+x>S.maxOutputBytes){o=!0;break}d.push(k),l+=x}if(o)break;if(p=R.result.cursor,p!=null&&p!==""){if(b.has(String(p)))throw new Error("Crawl API repeated pagination cursor");b.add(String(p))}else p=void 0}while(p!==void 0);return U(c.status==="completed",c.status==="completed"?null:c.status)}catch(g){return U(!1,g instanceof Error?g.message:String(g))}}var q=["temperature","topP","topK","frequencyPenalty","presencePenalty","maxOutputTokens","seed","stopSequences","maxRetries"],J=["temperature","topP","topK","frequencyPenalty","presencePenalty"],V={precise:{temperature:.3,topP:.9,topK:30},balanced:{temperature:.8,topP:1,topK:50},creative:{temperature:1.1,topP:.95,topK:80}},ce=1e-6,j={temperature:{min:0,max:2,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:{min:-2,max:2,step:.1},presencePenalty:{min:-2,max:2,step:.1},maxOutputTokens:{max:128e3},seed:!0,stopSequences:{max:4}};function me(e){return/^gpt-5/i.test(e)}function _(e){let t=e.contextWindow??128e3;return e.provider==="openai"?me(e.providerModel)?{temperature:!1,topP:!1,topK:{min:1,max:500,step:1},frequencyPenalty:{min:-2,max:2,step:.1},presencePenalty:{min:-2,max:2,step:.1},maxOutputTokens:{max:t},seed:!0,stopSequences:{max:4}}:{...j,maxOutputTokens:{max:t}}:e.provider==="xai"?{...j,maxOutputTokens:{max:t},seed:!0}:e.provider==="anthropic"?{temperature:{min:0,max:1,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:!1,presencePenalty:!1,maxOutputTokens:{max:t},seed:!1,stopSequences:{max:4}}:e.provider==="openrouter"?{temperature:{min:0,max:2,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:{min:-2,max:2,step:.1},presencePenalty:{min:-2,max:2,step:.1},maxOutputTokens:{max:t},seed:!0,stopSequences:{max:4}}:e.provider==="workersai"||e.provider==="cloudflare"?{temperature:{min:0,max:2,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:!1,presencePenalty:!1,maxOutputTokens:{max:t},seed:!1,stopSequences:{max:4}}:{...j,maxOutputTokens:{max:t}}}function A(e,t){if(e==="maxRetries")return!0;let n=t[e];return n===!1?!1:e==="seed"?n===!0:n!==void 0}function pe(e,t,n){return Math.min(n,Math.max(t,e))}function fe(e,t){return e===void 0&&t===void 0?!0:e===void 0||t===void 0?!1:Math.abs(e-t)<ce}function De(e,t){for(let n of["precise","balanced","creative"]){let r=V[n],i=!0;for(let s of J){if(t&&!A(s,t))continue;let m=r[s],a=e[s];if(m!==void 0){if(typeof m=="number"&&typeof a=="number"){if(!fe(a,m)){i=!1;break}}else if(a!==m){i=!1;break}}}if(i)return n}return"custom"}function Ge(e,t){let n=V[e],r={};for(let i of J){if(t&&!A(i,t))continue;let s=n[i];s!==void 0&&(r[i]=s)}return r}function $e(e){if(!e)return{};let t={};for(let n of q){let r=e[n];r!==void 0&&(n==="stopSequences"?Array.isArray(r)&&(t.stopSequences=r.filter(i=>typeof i=="string")):n==="maxRetries"?typeof r=="number"&&(t.maxRetries=r):typeof r=="number"&&(t[n]=r))}return t}function We(e,t,n){var m;let r={...e,...t},i=[],s={};for(let a of q){let c=r[a];if(c===void 0)continue;if(a==="maxRetries"){s.maxRetries=c;continue}if(!A(a,n)){i.push({key:a,action:"stripped",detail:"unsupported by model"});continue}if(a==="stopSequences"){let o=c,l=((m=n.stopSequences)==null?void 0:m.max)??o.length;o.length>l?(s.stopSequences=o.slice(0,l),i.push({key:a,action:"clamped",detail:`truncated to ${l} sequences`})):s.stopSequences=o;continue}if(a==="seed"){s.seed=c;continue}let d=n[a];if(d&&typeof d=="object"&&"min"in d){let o=c,l=pe(o,d.min,d.max);s[a]=l,l!==o&&i.push({key:a,action:"clamped",detail:`clamped from ${o} to ${l}`})}else if(a==="maxOutputTokens"){let o=c,l=n.maxOutputTokens.max,u=Math.min(o,l);s.maxOutputTokens=u,u!==o&&i.push({key:a,action:"clamped",detail:`clamped from ${o} to ${u}`})}}return{effectiveParams:s,adjustments:i}}function Fe(e){let t={};return e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.maxOutputTokens!==void 0&&(t.maxOutputTokens=e.maxOutputTokens),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.maxRetries!==void 0&&(t.maxRetries=e.maxRetries),t}function He(e=128e3){return _({provider:"openai",providerModel:"gpt-4.1",contextWindow:e})}function Ye(e=2e6){return _({provider:"openai",providerModel:"gpt-5-nano",contextWindow:e})}function ze(e=256e3){return _({provider:"xai",providerModel:"grok-4-fast",contextWindow:e})}function Be(e=128e3){return _({provider:"cloudflare",providerModel:"@cf/meta/llama-3.2-3b-instruct",contextWindow:e})}function Je(e,t){let n={...e};for(let r of q)r==="maxRetries"||n[r]===void 0||A(r,t)||delete n[r];return n}var de=["none","minimal","low","medium","high","xhigh"],ge=e=>typeof e=="string"&&de.includes(e);function Ze(e){var n;let t=(n=e.capabilities)==null?void 0:n.reasoning;return t&&typeof t=="object"?t:t?{kind:"effort"}:{kind:"none"}}function ye(e){return e.kind!=="effort"?[]:e.levels??[]}var xe=e=>e===!0||e==="true";function Xe(e){return e.kind==="tag"?!0:e.kind==="effort"?xe(e.exposesReasoning):!1}function Qe(e,t){if(e.kind!=="effort")return;let n=ye(e);if(ge(t)&&n.includes(t))return t;if(e.defaultLevel&&n.includes(e.defaultLevel))return e.defaultLevel}function et(e,t){let{effort:n,exposeReasoning:r,maxTokens:i}=t;if(e==="openai"){let s={};return n&&(s.reasoningEffort=n),r&&(s.reasoningSummary="auto"),Object.keys(s).length?{openai:s}:void 0}if(e==="xai")return n?{xai:{reasoningEffort:n}}:void 0;if(e==="openrouter"){if(!i&&!n)return;let s={};return r!==void 0&&(s.exclude=!r),i?{openrouter:{reasoning:{...s,max_tokens:i}}}:{openrouter:{reasoning:{...s,effort:n}}}}if(e==="anthropic"){let s={};return(n||r)&&(s.thinking={type:"adaptive",...r?{display:"summarized"}:{}}),n&&(s.effort=n),Object.keys(s).length?{anthropic:s}:void 0}}var he=[{id:"convertTempMessure",label:"Convert Temperature",description:"Convert temperature between Celsius, Fahrenheit, and Kelvin with optional static parameters"},{id:"tempTool",label:"Temp Tool",description:"Temporary demo tool"},{id:"twitter",label:"Twitter",description:"Twitter API for user info, tweets, mentions, replies, advanced search, and trends"},{id:"vectorize",label:"Vectorize",description:"Perform a semantic vector search. Returns relevant matches with scores and metadata."}],nt=he.reduce((e,t)=>(e[t.id]=t,e),{});export{we as a,Ee as b,Z as c,Re as d,be as e,X as f,Q as g,L as h,ee as i,te as j,ne as k,Te as l,re as m,oe as n,Ce as o,Me as p,ke as q,ve as r,ie as s,ae as t,Oe as u,_e as v,Y as w,Ie as x,P as y,S as z,ue as A,qe as B,z as C,Ue as D,q as E,J as F,V as G,_ as H,De as I,Ge as J,$e as K,We as L,Fe as M,He as N,Ye as O,ze as P,Be as Q,Je as R,de as S,Ze as T,ye as U,Xe as V,Qe as W,et as X,nt as Y};
@@ -1,23 +0,0 @@
1
- import{a as Wt}from"./chunk-V35SRZAO.js";import{a as K,b as G,c as Ht,d as tt}from"./chunk-ZYIULB2P.js";import{a as to}from"./chunk-6AZ7RATD.js";import{a as jt,b as Ut,d as Vt,g as Lt,i as st}from"./chunk-XXB57DMN.js";import{a as oo,b as eo}from"./chunk-3K4IMMLP.js";import{A as Xt,B as qt,D as Kt,H as Bt,K as zt,L as Gt,M as Yt,T as Zt,V as Qt,W as Et,X as St,Y as vt,a as B,b as It,k as Ot,n as kt,o as Dt,q as Mt,x as Jt}from"./chunk-6JUKM6LT.js";import{B as Pt,c as S,d as $t,h as bt,k as Z,r as Ct,s as P,v as Q,w as W}from"./chunk-QEZQZG6Z.js";import{a as At,b as _t,d as Ft}from"./chunk-YLDLDEUP.js";import{a as v}from"./chunk-YHXUBVN2.js";import{a as E}from"./chunk-3TXHFKDN.js";async function io(e,o){return e.length?!o||!o.HX_ORA_URL||!o.HX_API_KEY?(console.error("extractDocuments: missing HX_ORA_URL or HX_API_KEY"),e.map(t=>({name:t.name,text:""}))):await Promise.all(e.map(async t=>{try{let s=await fetch(`${o.HX_ORA_URL}/internal/files/extract`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:o.HX_API_KEY},body:JSON.stringify(t)});if(!s.ok)return console.error(`extractDocuments: ${t.name} failed ${s.status}`),{name:t.name,text:""};let u=await s.json();return{name:t.name,text:u.text||""}}catch(s){return console.error(`extractDocuments: ${t.name} threw`,s),{name:t.name,text:""}}})):[]}function No(e,o,i){var t,s,u,p;return Z(((s=(t=i.flowData)==null?void 0:t.state)==null?void 0:s.nodes)??[],((p=(u=i.flowData)==null?void 0:u.state)==null?void 0:p.edges)??[],o.id).some(n=>n.ref===e&&(n.type==="image"||n.type==="file"))}function Ro(e,o){var p,n,f,d,c,g,a;let i=Array.isArray((p=e.data)==null?void 0:p.outputMapping)?e.data.outputMapping:[];if(i.length===0)return null;let t=((f=(n=o.flowData)==null?void 0:n.state)==null?void 0:f.nodes)||[],s={},u=new Set;for(let w of i){let r=(d=w.key)==null?void 0:d.trim(),y=(c=w.from)==null?void 0:c.trim();if(!r||!y)throw new Error(`Answer node ${e.id} has an incomplete variable mapping`);if(u.has(r))throw new Error(`Answer node ${e.id} has duplicate output key "${r}"`);if(No(y,e,o))throw new Error(`Answer node ${e.id} cannot persist binary source "${y}"`);let l=W(y,{context:o.context||{},results:o.results||{},nodes:t,edges:((a=(g=o.flowData)==null?void 0:g.state)==null?void 0:a.edges)??[],currentNodeId:e.id}),m=l.value;if(l.missing||m===void 0||m===null){if(w.default===void 0)throw new P(l.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Answer node ${e.id} could not resolve output "${y}"`);m=w.default}s[r]=m,u.add(r)}try{JSON.stringify(s)}catch{throw new Error(`Answer node ${e.id} produced a value that is not JSON serializable`)}return s}async function nt(e,o,i,t,s,u,p){var f,d,c;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n;try{n=Ro(o,i)}catch(g){throw t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(g)}}),g}n&&e.outputCollector&&e.outputCollector.add(o.id,n);try{let g=await((f=e.getMessages)==null?void 0:f.call(e))??[],a=((d=g[g.length-1])==null?void 0:d.type)==="text"?g[g.length-1].content:"NO-TEXT";p==null||p({type:"answer_node",payload:{userMessage:(c=i==null?void 0:i.context)==null?void 0:c.user_input,answer:a}})}catch(g){console.error("answerNodeRunner: failed to emit answer telemetry:",g),t==null||t({type:"debug",content:"Warning: failed to emit answer telemetry"})}s==null||s(o.id,{type:"answerNode",message:"Answer response for: "+o.data.response,saved:!0,persistenceRequested:!!n&&!!e.outputCollector,persisted:!1,...e.runId?{runId:e.runId}:{}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}function J(e,o,i,t,s){var n,f,d,c,g;let u=(s==null?void 0:s.callerTag)??"llmNodeRunner",p=(s==null?void 0:s.serializeNonStrings)??!1;return Pt(e,o,{context:i.context??{},results:i.results??{},nodes:((f=(n=i.flowData)==null?void 0:n.state)==null?void 0:f.nodes)??[],edges:((c=(d=i.flowData)==null?void 0:d.state)==null?void 0:c.edges)??[],currentNodeId:o.id,secrets:(g=s==null?void 0:s.sessionEnv)==null?void 0:g.secrets},{callerTag:u,serializeNonStrings:p,onError:a=>{t==null||t({type:`error:${u}`,content:a})}})}var at="[redacted]",so=8*1024;function xo(e){if(e==null)return{value:e,truncated:!1};let o=typeof e=="string"?e:JSON.stringify(e),i=new TextEncoder().encode(o);if(i.byteLength<=so){if(typeof e=="string")return{value:e,truncated:!1};try{return{value:JSON.parse(o),truncated:!1}}catch{return{value:o,truncated:!1}}}let t=i.slice(0,so);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function To(e,o){return Q(e,o)}var dt=(e,o,i,t,s)=>J(e,o,i,s,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function ct(e,o,i,t,s,u,p){var d,c,g,a,w,r;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=null,f=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(i.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(i.results||{}));let y=((d=o.data)==null?void 0:d.url)||"",l=dt(y,o,i,e,t);if(console.log("[apiNodeRunner] resolved url:",K(y)?G(l):l),!l){t==null||t({type:"error:apiNodeRunner",content:"Missing url"}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:"Missing url"}}),s==null||s(o.id,n);return}let m=(((c=o.data)==null?void 0:c.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",m);let N=((g=o.data)==null?void 0:g.headers)||{},R={},h={};for(let U in N)if(Object.prototype.hasOwnProperty.call(N,U)){let j=String(N[U]??"");h[U]=K(j),R[U]=dt(j,o,i,e,t)}let T,k=!1;if(m!=="GET"&&m!=="HEAD"&&((a=o.data)==null?void 0:a.body)!==void 0){let U=typeof o.data.body=="string"?o.data.body:JSON.stringify(o.data.body);k=K(U),T=dt(U,o,i,e,t),!R["Content-Type"]&&!R["content-type"]&&(R["Content-Type"]="application/json")}let _={};for(let U in R)_[U]=h[U]?at:R[U];console.log("[apiNodeRunner] headers:",JSON.stringify(_)),console.log("[apiNodeRunner] body:",k?at:T),t==null||t({type:"info:apiNodeRunner:request",content:{nodeId:o.id,method:m,url:K(y)?G(l):l,headers:_,body:k?at:T}});let b=Number((w=o.data)==null?void 0:w.timeoutMs),C=new AbortController,F=Number.isFinite(b)&&b>0?setTimeout(()=>C.abort(),b):null,x;try{console.log("[apiNodeRunner] fetching..."),x=await fetch(l,{method:m,headers:R,body:T,signal:C.signal}),console.log("[apiNodeRunner] fetch returned status:",x.status)}finally{F&&clearTimeout(F)}let D=x.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",D);let M=await Ct(x);console.log("[apiNodeRunner] payload preview:",typeof M=="string"?M.slice(0,200):JSON.stringify(M).slice(0,200)),n={ok:x.ok,status:x.status,data:M};let V=Date.now()-f;p==null||p({type:"api_call",payload:{nodeId:o.id,url:l,method:m,status:x.status,latencyMs:V}});let{value:I,truncated:q}=xo(M);t==null||t({type:"info:apiNodeRunner:response",content:{nodeId:o.id,ok:x.ok,status:x.status,latencyMs:V,data:I,truncated:q,outVars:To(o,n)}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}catch(y){console.error("Error processing ApiNode:",y),t==null||t({type:"error:apiNodeRunner",content:`API node execution failed: ${y}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(y)}})}finally{console.log("[apiNodeRunner] final result:",(r=JSON.stringify(n))==null?void 0:r.slice(0,300)),s==null||s(o.id,n)}}var Ao="[redacted]",no=8*1024;function lt(e,o){if(typeof e=="string")return K(e)?typeof o=="string"&&/^https?:\/\//i.test(o)?G(o):Ao:o;if(e&&typeof e=="object"&&!Array.isArray(e)){let i={},t=o&&typeof o=="object"&&!Array.isArray(o)?o:{};for(let[s,u]of Object.entries(e))i[s]=lt(u,t[s]);return i}if(Array.isArray(e)){let i=Array.isArray(o)?o:[];return e.map((t,s)=>lt(t,i[s]))}return o}function _o(e){if(e==null)return{value:e,truncated:!1};let o=typeof e=="string"?e:JSON.stringify(e),i=new TextEncoder().encode(o);if(i.byteLength<=no){if(typeof e=="string")return{value:e,truncated:!1};try{return{value:JSON.parse(o),truncated:!1}}catch{return{value:o,truncated:!1}}}let t=i.slice(0,no);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function Fo(e,o){return Q(e,o)}var $o=(e,o,i,t,s)=>J(e,o,i,s,{callerTag:"toolNodeRunner",serializeNonStrings:!0,sessionEnv:t});function ot(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Io(e){let o=ot(e);if(Array.isArray(o.enum)&&o.enum.length>0)return o.enum.every(s=>typeof s=="string"||typeof s=="number")?"enum":"unsupported";switch(Array.isArray(o.type)?o.type.find(t=>typeof t=="string"&&t!=="null"):o.type){case"string":return"string";case"number":return"number";case"integer":return"integer";case"boolean":return"boolean";case"object":return"object";case"array":return"array";default:return"unsupported"}}function Oo(e,o){var p,n;let i={},t={},s=((p=e.data)==null?void 0:p.inputSchema)??o;if(s&&typeof s=="object"&&!Array.isArray(s)){t=ot(ot(s).properties);for(let[f,d]of Object.entries(t))i[f]=Io(d);return{types:i,properties:t}}let u=(n=e.data)==null?void 0:n.argTypes;if(u&&typeof u=="object"&&!Array.isArray(u))for(let[f,d]of Object.entries(u))typeof d=="string"&&(i[f]=d);return{types:i,properties:t}}function ko(e,o,i){if(e.trim()!==""){if(e==="null"&&o&&o!=="string"&&o!=="enum")return null;switch(o){case"string":return e;case"enum":{let t=ot(i).enum;if(Array.isArray(t)){let s=t.find(u=>String(u)===e);if(s!==void 0)return s}return e}case"number":{let t=Number(e);return Number.isFinite(t)?t:e}case"integer":{let t=Number.parseInt(e,10);return Number.isFinite(t)?t:e}case"boolean":return e==="true"?!0:e==="false"?!1:e;case"object":case"array":case"unsupported":try{return JSON.parse(e)}catch{return e}default:return e}}}function Do(e){return e===void 0||typeof e=="string"&&e.trim()===""}function ut(e,o,i,t,s,u,p){if(typeof e=="string"){let n=e.includes("{{")?$o(e,o,i,t,s):e;return ko(n,u,p)}if(e&&typeof e=="object"&&!Array.isArray(e)){let n={};for(let[f,d]of Object.entries(e))n[f]=ut(d,o,i,t,s);return n}return Array.isArray(e)?e.map(n=>ut(n,o,i,t,s)):e}function Mo(e,o,i,t,s,u){let p={};for(let[n,f]of Object.entries(e)){let d=ut(f,o,i,t,s,u.types[n],u.properties[n]);Do(d)||(p[n]=d)}return p}async function bo(e){if(e.toolDefs)return e.toolDefs;if(!e.env)return e.toolDefs={},e.toolDefs;let o=await v(e.env),i={};for(let t of o)t!=null&&t.id&&(i[t.id]=t);return e.toolDefs=i,i}function Co(e){var o,i,t;return((o=e.data)==null?void 0:o.source)==="catalog"?"catalog":((i=e.data)==null?void 0:i.source)==="composio"?"composio":(((t=e.data)==null?void 0:t.source)==="http","http")}function Po(e,o,i){let t=st(e.execution);if(t.authMode==="manual"){let s=jt(t,e.id);if(!s)throw new Error(`Composio tool '${e.name}' is missing connection scope`);return Ut(s)}return Lt(o,i,{allowChatIdFallback:!0})}async function pt(e,o,i,t,s,u,p){var c,g,a,w,r,y;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n={ok:!1,data:null,error:null},f=Date.now(),d=Co(o);try{if(d==="catalog")throw new Error("This Tool node still uses a curated catalog connector. Reconfigure it to a tenant HTTP or connector tool.");let l=(c=o.data)!=null&&c.args&&typeof o.data.args=="object"&&!Array.isArray(o.data.args)?o.data.args:{},m=typeof((g=o.data)==null?void 0:g.toolId)=="string"?o.data.toolId.trim():"";if(!m)throw new Error("Tool nodes require toolId");let R=(await bo(e))[m];if(!R)throw new Error(`Tool ${m} not found`);let h="";if(d==="composio"){if(R.kind!=="composio")throw new Error(`Tool ${m} is not a connector tool`);if(h=typeof((a=o.data)==null?void 0:a.toolSlug)=="string"?o.data.toolSlug.trim():"",!h)throw new Error("Connector tool nodes require toolSlug");let F=st(R.execution);if(!Vt(F.tools).includes(h))throw new Error(`Tool slug ${h} is not enabled on connector ${m}`)}else if(R.kind!=="http")throw new Error(`Tool ${m} is not an HTTP tool`);let T=Oo(o,d==="http"?R.inputSchema:void 0),k=Mo(l,o,i,e,t,T);if(t==null||t({type:"info:toolNodeRunner:request",content:{nodeId:o.id,source:d,toolSlug:(w=o.data)==null?void 0:w.toolSlug,toolId:(r=o.data)==null?void 0:r.toolId,args:lt(l,k)}}),d==="composio"){let F=typeof((y=o.data)==null?void 0:y.toolVersion)=="string"?o.data.toolVersion.trim():"",x=await Wt(e,{toolSlug:h,connectionScope:Po(R,e,i),toolVersion:F||null,arguments:k});n={ok:x.ok,data:x.ok?x.data:null,error:x.ok?null:x.error??"Tool execution failed"}}else{let F=tt(R,e,i,t);if(!F.execute)throw new Error(`Tool ${m} is missing an execute handler`);let x=await F.execute(k,{}),D=x&&typeof x=="object"&&"error"in x&&x.error?String(x.error):null;n={ok:!D,data:x,error:D}}let _=Date.now()-f;p==null||p({type:"tool_call",payload:{nodeId:o.id,url:d==="composio"?`composio:${h}`:`tool:${m}`,method:"EXECUTE",status:n.ok?200:502,latencyMs:_}});let{value:b,truncated:C}=_o(n.data);t==null||t({type:"info:toolNodeRunner:response",content:{nodeId:o.id,ok:n.ok,latencyMs:_,data:b,truncated:C,error:n.error,outVars:Fo(o,n)}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:n.ok?"success":"error",error:n.error??void 0}})}catch(l){let m=l instanceof Error?l.message:String(l);n={ok:!1,data:null,error:m},t==null||t({type:"error:toolNodeRunner",content:`Tool node execution failed: ${m}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:m}})}finally{s==null||s(o.id,n)}}var jo=1440*60*1e3,ao=8*1024;function co(e){if(e==null)return{value:e,truncated:!1};let o=new TextEncoder().encode(JSON.stringify(e));return o.byteLength<=ao?{value:e,truncated:!1}:{value:new TextDecoder().decode(o.slice(0,ao)),truncated:!0}}async function ft(e,o,i,t,s,u,p){var g,a,w;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n={ok:!1,data:null,error:null},f=Date.now(),d="crawl:unknown",c=r=>{let y=JSON.stringify(r);for(let l of Object.values(e.secrets??{}))l&&(y=y.split(JSON.stringify(l).slice(1,-1)).join("[redacted]"),y=y.split(encodeURIComponent(l)).join("[redacted]"));return JSON.parse(y)};try{if(!Jt("crawlNode",(g=i.flowData)==null?void 0:g.tenant))throw new Error("Crawl node no disponible para este tenant");let r=e.env;if(!(r!=null&&r.CF_ACCOUNT_ID)||!(r!=null&&r.CF_BROWSER_RUN_TOKEN))throw new Error("Crawl no configurado: faltan CF_ACCOUNT_ID / CF_BROWSER_RUN_TOKEN");let y=J(o.data.url,o,i,t,{callerTag:"crawlNodeRunner",serializeNonStrings:!0,sessionEnv:e}),l=Xt(o.data,y),m=K(o.data.url);d=`crawl:${c(new URL(y).host)}`;let N=`crawl:pending:${await qt(l)}`,R=(a=e.ctx)==null?void 0:a.storage,h=await(R==null?void 0:R.get(N)),T=h&&typeof h.jobId=="string"&&h.jobId&&Number.isFinite(h.createdAt)&&Date.now()-h.createdAt>=0&&Date.now()-h.createdAt<jo;h&&!T&&await(R==null?void 0:R.delete(N)),t==null||t({type:"info:crawlNodeRunner:request",content:{nodeId:o.id,url:m?c(G(y)):y,resumeJobId:T?h.jobId:void 0}}),{result:n}=await Kt({accountId:r.CF_ACCOUNT_ID,apiToken:r.CF_BROWSER_RUN_TOKEN},o.data,{url:y,...T?{resumeJobId:h.jobId}:{}}),n.error==="timeout"&&((w=n.data)!=null&&w.jobId)?await(R==null?void 0:R.put(N,{jobId:n.data.jobId,createdAt:T?h.createdAt:Date.now()})):n.data&&n.data.status!=="running"&&await(R==null?void 0:R.delete(N))}catch(r){n={ok:!1,data:null,error:r instanceof Error?r.message:String(r)},t==null||t({type:"error:crawlNodeRunner",content:c(`Crawl node execution failed: ${n.error}`)})}finally{let r=Date.now()-f;p==null||p({type:"tool_call",payload:{nodeId:o.id,url:d,method:"EXECUTE",status:n.ok?200:502,latencyMs:r}});let y=co(c(n.data));t==null||t({type:"info:crawlNodeRunner:response",content:{nodeId:o.id,ok:n.ok,latencyMs:r,data:y.value,truncated:y.truncated,error:c(n.error),outVars:co(c(Q(o,n))).value}}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:n.ok?"success":"error",error:c(n.error)??void 0}}),s==null||s(o.id,n)}}function lo(){let e={};return{add(o,i){e[o]=i},hasOutputs(){return Object.keys(e).length>0},answerNodeIds(){return Object.keys(e)},snapshotData(){let o=Object.entries(e);return o.length===1?o[0][1]:Object.fromEntries(o)}}}function Uo(e){return!!(e!=null&&e.HX_ORA_URL)&&!!(e!=null&&e.HX_API_KEY)}async function Ve(e,o){if(!Uo(e))throw new Error("Structured outputs require HX_ORA_URL and HX_API_KEY");let i=await fetch(`${e.HX_ORA_URL}/internal/outputs/${encodeURIComponent(o.flowId)}/${encodeURIComponent(o.sessionId)}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:e.HX_API_KEY},body:JSON.stringify({runId:o.runId,createdAt:o.createdAt,data:o.data,answerNodeIds:o.answerNodeIds})});if(!i.ok){let t=await i.text().catch(()=>"");throw new Error(`Structured output persistence failed with ${i.status}${t?`: ${t}`:""}`)}}var uo=3,po=10,Vo=new Set(["agent:start","agent:complete","agent:telemetry"]);function Lo(e){let o=e.executedNodes||[];return o.length===0?"(none)":o.map(i=>i.label?`${i.id} (${i.label})`:i.id).join(" \u2192 ")}function Wo(e){let o=e.executedNodes||[];return o[o.length-1]}function X(e,o,i){throw e==null||e({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:i.message}}),i}function Ho(e,o){var u,p,n,f,d,c,g;let i=Array.isArray((u=e.data)==null?void 0:u.inputs)?e.data.inputs:[],t=((n=(p=o.flowData)==null?void 0:p.state)==null?void 0:n.nodes)||[],s={};for(let a of i){let w=(f=a.key)==null?void 0:f.trim();if(!w)continue;let r=(d=a.from)==null?void 0:d.trim();if(!r){if(a.default===void 0)continue;s[w]=a.default;continue}let y=W(r,{context:o.context||{},results:o.results||{},nodes:t,edges:((g=(c=o.flowData)==null?void 0:c.state)==null?void 0:g.edges)??[],currentNodeId:e.id}),l=y.value;if(y.missing||l===void 0||l===null){if(a.default===void 0)throw new P(y.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Worker node ${e.id} could not resolve input "${r}"`);l=a.default}s[w]=l}return s}async function mt(e,o,i,t,s,u,p){var C,F,x,D,M,V;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=typeof((C=o.data)==null?void 0:C.flowId)=="string"?o.data.flowId.trim():"";n||X(t,o,new Error(`Worker node ${o.id} is missing flowId`));let f=(F=i.flowData)==null?void 0:F.flowId,d=e.workerStack??(f?[f]:[]);d.includes(n)&&X(t,o,new Error(`Worker node ${o.id} cannot call ${n}: cycle detected (${[...d,n].join(" \u2192 ")})`)),d.length>=uo&&X(t,o,new Error(`Worker node ${o.id} exceeded max nesting depth (${uo})`));let c=e.workerCalls??{count:0};e.workerCalls=c,c.count>=po&&X(t,o,new Error(`Worker node ${o.id} exceeded max worker calls per run (${po})`)),c.count+=1;let g;try{g=Ho(o,i)}catch(I){X(t,o,I instanceof Error?I:new Error(String(I)));return}let a=e.env;a||X(t,o,new Error(`Worker node ${o.id} is missing runtime env`));let w,r;try{let I=await At(n,a);r=(x=I==null?void 0:I.metadata)==null?void 0:x.tenant,w=await _t(n,a)}catch(I){X(t,o,new Error(`Worker node ${o.id} could not load worker ${n}: ${I instanceof Error?I.message:String(I)}`))}let y=(D=i.flowData)==null?void 0:D.tenant;(!r||r!==y)&&X(t,o,new Error(`Worker ${n} belongs to a different tenant`));let l=lo(),m={flowData:{...w,tenant:r,flowId:n,chatId:((M=i.flowData)==null?void 0:M.chatId)||""},executedNodes:[],context:{},results:{}},N={env:a,ctx:e.ctx,secrets:e.secrets,userAuth:e.userAuth,user:e.user,toolDefs:e.toolDefs,composioSessions:e.composioSessions,skillRefCache:e.skillRefCache,publicOrigin:e.publicOrigin,getOraModel:e.getOraModel,runId:e.runId,shouldStop:e.shouldStop,workerCalls:c,conn:void 0,getMessages:async()=>[],setMessages:async()=>{},agentMemory:"",outputCollector:l,workerStack:[...d,n]},R,h={onChangeState:()=>{},onServerEvent:I=>{var q;Vo.has(I.type)||t==null||t({type:"worker:node",content:{workerNodeId:o.id,childNodeId:(q=I.content)==null?void 0:q.nodeId,event:I}})},onTelemetry:I=>p==null?void 0:p(I),onError:I=>{R=I},shouldStop:e.shouldStop},{startEngine:T,FlowExecutionStoppedError:k}=await import("./FlowEngine-H3QNWZVB.js"),_=await T(N,m,h)({text:"",inputs:g});if((_.status==="stopped"||await((V=e.shouldStop)==null?void 0:V.call(e)))&&X(t,o,new k),_.status!=="completed"){let I=Wo(m),q=Lo(m),U=_.error||R||"unknown error",j=I?` at node ${I.label?`${I.id} (${I.label})`:I.id}`:"";X(t,o,new Error(`Worker ${n} failed${j}: ${U}. Path: ${q}`))}l.hasOutputs()||X(t,o,new Error(`El worker ${n} complet\xF3 sin output estructurado. Agreg\xE1 un mapeo de salida en su nodo Answer.`));let b=(m.executedNodes||[]).map(I=>I.id);s==null||s(o.id,{ok:!0,data:l.snapshotData(),error:null,executed:b}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}import{generateObject as Zo}from"ai";import{z as fo}from"zod";import{openai as Jo}from"@ai-sdk/openai";import{extractReasoningMiddleware as Xo,wrapLanguageModel as qo}from"ai";import{createWorkersAI as Ko}from"workers-ai-provider";import{xai as Bo}from"@ai-sdk/xai";import{anthropic as zo}from"@ai-sdk/anthropic";import{createOpenRouter as Go}from"@openrouter/ai-sdk-provider";var gt={};function yt(e){if(e!=null){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}}function Yo(e){return{...e,defaultParams:yt(e.defaultParams)??e.defaultParams,capabilities:yt(e.capabilities)??e.capabilities,price:yt(e.price)??e.price}}async function et(e,o,i){var c,g;if(!(o!=null&&o.getOraModel))throw new Error("resolveModelById requires a sessionEnv with getOraModel capable of fetching models dynamically.");let t=await o.getOraModel(e);if(!t)return;let s=Yo(t),u=((c=s.capabilities)==null?void 0:c.params)??Bt(s),{effectiveParams:p,adjustments:n}=Gt(s.defaultParams,i,u),f;if(gt[s.provider])f=await gt[s.provider](s,o,i);else if(s.provider==="openai")f=Jo(s.providerModel);else if(s.provider==="xai")f=Bo(s.providerModel);else if(s.provider==="anthropic")f=zo(s.providerModel);else if(s.provider==="openrouter")f=Go()(s.providerModel);else if(s.provider==="workersai"||s.provider==="cloudflare"){if(!((g=o==null?void 0:o.env)!=null&&g.AI))throw new Error("Workers AI provider requires sessionEnv.env.AI binding");f=Ko({binding:o.env.AI})(s.providerModel)}else f={provider:s.provider,providerModel:s.providerModel};let d=Zt(s);return d.kind==="tag"&&f&&typeof f=="object"&&"specificationVersion"in f&&(f=qo({model:f,middleware:Xo({tagName:d.tagName??"think",startWithReasoning:d.startWithReasoning??!1})})),{provider:s.provider,modelHandle:f,entry:s,effectiveParams:p,paramAdjustments:n.length>0?n:void 0,reasoning:d}}function Ee(e,o){gt[e]=o}async function wt(e,o,i,t,s,u,p){var r,y,l,m,N,R,h;t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=String(((r=o==null?void 0:o.data)==null?void 0:r.input_variable)||"user_input").trim(),f;try{let T=W(n,{context:i.context??{},results:i.results??{},nodes:((l=(y=i.flowData)==null?void 0:y.state)==null?void 0:l.nodes)??[],edges:((N=(m=i.flowData)==null?void 0:m.state)==null?void 0:N.edges)??[],currentNodeId:o.id});if(T.missing)throw new Error(`Classifier input "${n}" did not produce a value`);f=T.value}catch(T){throw t==null||t({type:"error:classifier",content:String(T)}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(T)}}),T}let d=Array.isArray((R=o==null?void 0:o.data)==null?void 0:R.items)?o.data.items:[];if(d.length===0){t==null||t({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let c=String((h=d[d.length-1])==null?void 0:h.id);if(!f||String(f).trim().length===0){t==null||t({type:"warning:classifier",content:"No input for classification \u2014 falling back to last item."}),s==null||s(o.id,{classification:c}),i.context=i.context||{},i.context.classified_id=c,u==null||u(i);return}let a=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
2
- If the message is ambiguous or none clearly matches, choose the LAST category in the list.
3
-
4
- Categories:
5
- ${d.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
- `,w=`User message:
10
- """${String(f).trim()}"""
11
-
12
- Select the best matching category id.`;try{let T=Date.now(),k=d.map(V=>String(V.id)),_="gpt_4_1_mini",b=await et(_,e);if(!b)throw new Error(`Model '${_}' not found in registry`);let{modelHandle:C,effectiveParams:F}=b,x=await Zo({model:C,messages:[{role:"system",content:a},{role:"user",content:w}],schema:fo.object({classification:fo.enum(k).describe("The id of the best matching category")}),temperature:F.temperature??0}),D=Date.now()-T,M=x.object.classification;p==null||p({type:"class_telemetry",payload:{nodeId:o.id,totalLatency:D,model:x.response.modelId,usage:x.usage,options:k}}),p==null||p({type:"class_result",payload:{result:x}}),s==null||s(o.id,{classification:M}),i.context=i.context||{},i.context.classified_id=M,u==null||u(i),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}})}catch(T){throw t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"error",error:String(T)}}),T}}import{stepCountIs as vo,streamText as te}from"ai";import{nanoid as oe}from"nanoid";import"zod";function mo(e,o){var n,f,d,c,g;let i=((n=e.data)==null?void 0:n.attachments)??[];if(!Array.isArray(i))throw new P("INVALID_EXPRESSION",`Node ${e.id} attachments must be an array`);let t=((d=(f=o.flowData)==null?void 0:f.state)==null?void 0:d.nodes)??[],s=((g=(c=o.flowData)==null?void 0:c.state)==null?void 0:g.edges)??[],u=Z(t,s,e.id),p="";for(let a of i){if(typeof a!="string")throw new P("INVALID_EXPRESSION",`Node ${e.id} has an invalid attachment reference`);let w=u.find(y=>y.ref===a);if(!w)throw new P("OUT_OF_SCOPE",`Attachment "${a}" is not in this node's connection scope`);if(w.type!=="file"&&w.type!=="image")throw new P("UNKNOWN_OUTPUT",`Attachment "${a}" is not an image or file output`);if(w.type!=="file")continue;let r=W(a,{context:o.context??{},results:o.results??{},nodes:t,edges:s,currentNodeId:e.id});if(r.missing)throw new P(r.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${a}" did not produce a value`);if(typeof r.value!="string")throw new P("PATH_NOT_FOUND",`Attachment "${a}" must resolve to file text`);r.value.trim()&&(p+=(p?`
13
-
14
- `:"")+r.value)}return p}function Qo(e,o){var s,u,p,n,f;let i=((s=e.data)==null?void 0:s.attachments)??[];if(!Array.isArray(i))throw new P("INVALID_EXPRESSION",`Node ${e.id} attachments must be an array`);let t=Z(((p=(u=o.flowData)==null?void 0:u.state)==null?void 0:p.nodes)??[],((f=(n=o.flowData)==null?void 0:n.state)==null?void 0:f.edges)??[],e.id);return i.map(d=>{if(typeof d!="string")throw new P("INVALID_EXPRESSION",`Node ${e.id} has an invalid attachment reference`);let c=t.find(g=>g.ref===d);if(!c)throw new P("OUT_OF_SCOPE",`Attachment "${d}" is not in this node's connection scope`);if(c.type!=="image"&&c.type!=="file")throw new P("UNKNOWN_OUTPUT",`Attachment "${d}" is not a binary output`);return c.type==="image"?d:null}).filter(d=>d!==null)}function yo(e,o){var s,u,p,n;let i=[],t={context:o.context??{},results:o.results??{},nodes:((u=(s=o.flowData)==null?void 0:s.state)==null?void 0:u.nodes)??[],edges:((n=(p=o.flowData)==null?void 0:p.state)==null?void 0:n.edges)??[],currentNodeId:e.id};for(let f of Qo(e,o)){let d=W(f,t);if(d.missing)throw new P(d.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${f}" did not produce a value`);if(!Array.isArray(d.value))throw new P("PATH_NOT_FOUND",`Attachment "${f}" must resolve to an image array`);i.push(...d.value)}return i}var z=(e,o,i)=>{e.send(o+"::"+i)};var Eo=E({"../tools/composioDirectTool.ts":()=>import("./composioDirectTool-XOKIM5FJ.js"),"../tools/composioTool.ts":()=>import("./composioTool-C4KZMI4Q.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-RT5CTG4O.js"),"../tools/skillTool.ts":()=>import("./skillTool-JEAL3G33.js"),"../tools/tempTool.ts":()=>import("./tempTool-2RXAF56M.js"),"../tools/twitter.ts":()=>import("./twitter-OMDEG7T2.js"),"../tools/vectorize.ts":()=>import("./vectorize-CDB26DMD.js")});var So=E({});async function ee(e,o,i,t){var g;let s=Array.isArray((g=i==null?void 0:i.data)==null?void 0:g.tools)?i.data.tools:[];if(s.length===0)return{};let u={},p=a=>{var R,h;let w=typeof(a==null?void 0:a.description)=="string"?a.description:"",r=a==null?void 0:a.inputSchema,y;try{let T=(r==null?void 0:r.shape)??(typeof((R=r==null?void 0:r._def)==null?void 0:R.shape)=="function"?r._def.shape():(h=r==null?void 0:r._def)==null?void 0:h.shape);T&&typeof T=="object"&&(y=T)}catch{}let l=y?Object.keys(y):[],m=w?`description="${w.length>120?w.slice(0,120)+"\u2026":w}"`:"description=(none)",N=l.length?`inputSchema={${l.join(", ")}}`:"inputSchema=(none)";return`${m} ${N}`},n=(()=>{let a=[],w=[],r=[],y=[];for(let m=0;m<s.length;m++){let N=s[m];!N||typeof N!="object"||typeof N.id!="string"?y.push(m):N.kind==="builtin"?a.push(N.id):N.kind==="skill"?r.push(N.id):N.kind==="http"||N.kind==="mcp"||N.kind==="composio"?w.push(N.id):y.push(m)}let l=[];return a.length&&l.push(`builtin[${a.join(", ")}]`),w.length&&l.push(`custom[${w.join(", ")}]`),r.length&&l.push(`skill[${r.join(", ")}]`),y.length&&l.push(`invalid@[${y.join(", ")}]`),l.join(" ")||"(none)"})();console.log(`[tools] node ${i.id} requested (${s.length}): ${n}`);let f=!1,d=async()=>{if(f&&e.toolDefs)return e.toolDefs;if(!e.env)return e.toolDefs=e.toolDefs||{},f=!0,e.toolDefs;try{let a=await v(e.env),w={};for(let r of a)r&&r.id&&(w[r.id]=r);e.toolDefs=w}catch(a){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(a)}`}),e.toolDefs=e.toolDefs||{}}return f=!0,e.toolDefs},c=[];for(let a=0;a<s.length;a++){let w=s[a];if(!w||typeof w!="object"||typeof w.id!="string"||w.kind!=="builtin"&&w.kind!=="http"&&w.kind!=="mcp"&&w.kind!=="composio"&&w.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${a}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let r=w;if(r.kind!=="builtin"){let l=(await d())[r.id];if(!l){console.error(`[tools] \u2717 custom '${r.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${r.id}' not found for this tenant`});continue}if(r.kind==="composio"){try{let N=await to(l,e,o,t),R=Object.keys(N);for(let[h,T]of Object.entries(N))u[h]=T;console.log(`[tools] \u2713 composio '${r.id}' \u2192 ${R.length} tool(s)`)}catch(N){console.error(`[tools] \u2717 composio '${r.id}': ${String(N)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${r.id}': ${String(N)}`})}continue}if(r.kind==="skill"){if(l.kind!=="skill"){console.error(`[tools] \u2717 skill '${r.id}': row is of kind '${l.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${r.id}' is not a skill`});continue}let N=l.name;if(u[N]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${N}' \u2014 builtin/other already registered, skipping skill '${r.id}'`});continue}try{u[N]=oo(l,e,o,t),c.push(l);let R=typeof l.execution=="string"?JSON.parse(l.execution):l.execution||{},h=Array.isArray(R.references)?R.references.map(T=>T==null?void 0:T.name):[];console.log(`[tools] \u2713 skill '${r.id}' \u2192 '${N}' (refs: ${h.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:N,refCount:h.length,refs:h}})}catch(R){console.error(`[tools] \u2717 skill '${r.id}': ${String(R)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${r.id}': ${String(R)}`})}continue}let m=l.name;if(u[m]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${m}' \u2014 builtin already registered, skipping custom tool '${r.id}'`});continue}try{let N=tt(l,e,o,t);u[m]=N,console.log(`[tools] \u2713 custom '${r.id}' \u2192 '${m}'`),console.log(`[tools] ${p(u[m])}`)}catch(N){console.error(`[tools] \u2717 custom '${r.id}': ${String(N)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${r.id}': ${String(N)}`})}continue}if(!vt[r.id]){console.error(`[tools] \u2717 builtin '${r.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${r.id}' not found in registry`});continue}try{let y;try{y=await Eo(`../tools/${r.id}.ts`)}catch{y=await So(`../tools/${r.id}.js`)}let l;if(y[r.id])l=y[r.id];else if(y.default)l=y.default;else if(y.create)l=y.create;else{let _=Object.values(y);_.length>0&&(l=_[0])}if(!l){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${r.id}'`});continue}let m,N,R={};if(r.params&&typeof r.params=="object"){if(typeof r.params.description=="string"?m=r.params.description:r.params.description!==void 0&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${r.id}' \u2014 must be a string`})),r.params.inputSchema!==void 0){let _=r.params.inputSchema;typeof _=="object"&&(typeof _.safeParse=="function"||_._def)?N=_:typeof _=="object"&&_!==null&&_.type==="object"&&_.properties?(N=Ht(_),N||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${r.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${r.id}' \u2014 must be a Zod schema or JSON Schema object`})}r.params.defaults!==void 0?typeof r.params.defaults=="object"&&r.params.defaults!==null&&!Array.isArray(r.params.defaults)?R=r.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${r.id}' \u2014 must be an object`}),R={}):r.params.source!==void 0||r.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${r.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),R={}):R={}}let h=l(e,o,R,t);m&&h&&typeof h=="object"&&(h.description=m),N&&h&&typeof h=="object"&&(h.inputSchema=N),u[r.id]=h;let T=[];m&&T.push("description"),N&&T.push("inputSchema"),Object.keys(R).length&&T.push(`defaults(${Object.keys(R).join(",")})`);let k=T.length?` [overrides: ${T.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${r.id}'${k}`),console.log(`[tools] ${p(h)}`)}catch(y){console.error(`[tools] \u2717 builtin '${r.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${r.id}': ${String(y)}`});continue}}if(c.length>0)if(u.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{u.readSkillRef=eo(e,c,o,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${c.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:c.map(a=>a.name)}})}catch(a){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(a)}`)}return u}async function ht(e,o,i,t,s,u,p){var _,b,C,F;`${o.id}`,t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n=!1;try{let x=(_=i.flowData)==null?void 0:_.state;if(x&&x.edges&&x.nodes){let D=x.edges.filter(M=>M.source===o.id);if(D.length>0){let M=x.nodes.find(V=>V.id===D[0].target);M&&M.type==="answerNode"&&(n=!0)}}}catch(x){console.error("Error determining next node for streaming:",x)}let f=J(o.data.template,o,i,t,{sessionEnv:e});(!f||!f.trim())&&(f="Answer straight forward to the user, dont offer any other option to continue");let d=f,c=J(o.data.user_template||"",o,i,t,{sessionEnv:e}),g=x=>x&&Object.fromEntries(Object.keys(x).map(D=>[D,"[redacted]"])),a=e!=null&&e.secrets||e!=null&&e.userAuth?{...e,secrets:g(e.secrets),userAuth:g(e.userAuth)}:e,w=J(o.data.template,o,i,void 0,{sessionEnv:a})||d,r=J(o.data.user_template||"",o,i,void 0,{sessionEnv:a});t==null||t({type:`info:llmNodeRunner:${o.id}`,content:w}),t==null||t({type:`info:llmNodeRunner:${o.id}`,content:r});let y=(b=o==null?void 0:o.data)==null?void 0:b.window_size,l=Number(y);(!Number.isInteger(l)||l<=0)&&(l=5);let m=yo(o,i),N=mo(o,i);t==null||t({type:"info:llmNodeRunner:attachments",content:{nodeId:o.id,refs:Array.isArray((C=o.data)==null?void 0:C.attachments)?o.data.attachments:[],images:m.length,documents:N?1:0}});let h=(await((F=e.getMessages)==null?void 0:F.call(e))??[]).slice(-l),T=h.filter(x=>x&&typeof x.role=="string"&&typeof x.content=="string");T.length!==h.length&&console.warn(`Filtered ${h.length-T.length} invalid messages from history`);let k=se(T,c,m,N);await ie(f,k,e.conn,t,o,n,s,i,u,e,p)}async function ie(e,o,i,t,s,u,p,n,f,d,c){var a;let g=Date.now();if(!((a=d.env)!=null&&a.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(w,r)=>{var D,M,V,I,q,U;let y,l={},m,N="none",R=!1,h,T=!1,k=!1,_=0,b=0,C=(D=s==null?void 0:s.data)==null?void 0:D.sendReasoning,F=C!==!1;try{let j=(M=s==null?void 0:s.data)==null?void 0:M.model,Y=Array.isArray(j)?j[0]:j||"gpt_5_nano",A=zt(s==null?void 0:s.data),O=await et(Y,d,A);if(!O)throw new Error(`Model '${Y}' not found in registry`);y=O.modelHandle,l=O.effectiveParams||{},N=O.reasoning.kind;let $=Et(O.reasoning,(V=s==null?void 0:s.data)==null?void 0:V.reasoningEffort);R=F&&Qt(O.reasoning);let H=typeof((I=s==null?void 0:s.data)==null?void 0:I.reasoningMaxTokens)=="number"?s.data.reasoningMaxTokens:void 0;m=St(O.provider,{effort:$,exposeReasoning:R,maxTokens:H}),$&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:$})),console.log(`[reasoning] ${JSON.stringify({model:Y,provider:O.provider,capability:O.reasoning,requestedEffort:((q=s==null?void 0:s.data)==null?void 0:q.reasoningEffort)??null,resolvedEffort:$??null,sendReasoning:F,exposeReasoning:R,providerOptions:m??null},null,2)}`);for(let L of O.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:L});t==null||t({type:"info:llmNodeRunner:model",content:Y}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(U=s==null?void 0:s.data)!=null&&U.generationPreset?{preset:s.data.generationPreset}:{},...l,...N!=="none"?{reasoning:N,configuredSendReasoning:C,sendReasoning:F,exposeReasoning:R,...$?{effort:$}:{}}:{}}})}catch(j){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(j)}`}),j}let x=await ee(d,n,s,t);console.log(`[tools] node ${s.id} loaded ${Object.keys(x).length}: ${Object.keys(x).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:s.id,tools:Object.keys(x)}});try{let j=te({model:y,system:e,messages:o,stopWhen:(()=>{var L;let O=!!x.readSkillRef?10:5,$=Number(((L=s.data)==null?void 0:L.max_steps)??O),H=Number.isFinite($)?Math.max(1,Math.min(30,$)):O;return vo(H)})(),...Yt(l),...m?{providerOptions:m}:{},tools:x,onFinish:async A=>{var xt,Tt;let O=A.text||"",$=A.reasoningText??((xt=A.reasoning)==null?void 0:xt.text)??"";if(console.log(`[reasoning] done: deltas=${_} chars=${b} result.reasoningText=${$.length} finishReason=${A.finishReason??"n/a"} reasoningTokens=${((Tt=A.usage)==null?void 0:Tt.reasoningTokens)??"n/a"}`),F&&R&&!T&&$&&i){T=!0;try{z(i,B.SERVER_REASONING_STREAM,$)}catch(ho){console.warn("Failed to send finished reasoning over connection",ho)}}let H={id:oe(),role:"assistant",type:"text",content:O,ts:Date.now()};u&&(d.setMessages?await d.setMessages(H):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),i&&F&&T&&!k&&(k=!0,z(i,B.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),u&&i&&z(i,B.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),p==null||p((s==null?void 0:s.id)||"llm_result",O),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(A)});let L=Date.now()-g,wo=h?h-g:void 0;c==null||c({type:"llm_telemetry",payload:{nodeId:s.id,totalLatency:L,timeToFirstToken:wo,model:A.response.modelId,usage:A.usage}}),c==null||c({type:"llm_result",payload:{result:A}})},onStepFinish:async A=>{let O=($,H=200)=>{let L=typeof $=="string"?$:JSON.stringify($);return L?L.length>H?`${L.slice(0,H)}\u2026(+${L.length-H})`:L:""};if(A.toolCalls&&A.toolCalls.length>0){for(let $ of A.toolCalls)console.log(`[tools] \u2192 ${$.toolName}(${O($.args??$.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${s.id}`,content:JSON.stringify(A.toolCalls)})}if(A.toolResults&&A.toolResults.length>0){for(let $ of A.toolResults)console.log(`[tools] \u2190 ${$.toolName} \u2192 ${O($.result??$.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${s.id}`,content:JSON.stringify(A.toolResults)})}},experimental_onToolCallStart:A=>{var O;t==null||t({type:"tool:execution",content:{nodeId:s.id,toolName:(O=A==null?void 0:A.toolCall)==null?void 0:O.toolName,status:"start"}})},experimental_onToolCallFinish:A=>{var O,$;t==null||t({type:"tool:execution",content:{nodeId:s.id,toolName:(O=A==null?void 0:A.toolCall)==null?void 0:O.toolName,status:(($=A==null?void 0:A.toolOutput)==null?void 0:$.type)==="tool-error"?"error":"success"}})},onError:A=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),r(A)},onChunk:A=>{if(A.chunk.type==="reasoning-delta"){let $=A.chunk.text??A.chunk.delta??"";if($&&(T=!0,_+=1,b+=$.length,_===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),F&&i&&$)try{z(i,B.SERVER_REASONING_STREAM,$)}catch(H){console.warn("Failed to send reasoning chunk over connection",H)}return}if(A.chunk.type==="text-delta"){if(h||(h=Date.now()),i&&F&&T&&!k){k=!0;try{z(i,B.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch($){console.warn("Failed to send reasoning complete over connection",$)}}return}c==null||c({type:A.chunk.type,payload:{nodeId:s.id,chunk:A.chunk}});let O=`llm_chunk:${A.chunk.type}`;t==null||t({type:O,content:{...A}})}}),Y=async()=>{let A="";for await(let O of j.fullStream)if(O.type==="text-delta"){if(A+=O.text,u&&i)try{z(i,B.SERVER_TEXT_STREAM,O.text)}catch($){console.warn("Failed to send chunk over connection",$)}}else if(O.type==="finish-step"&&O.finishReason==="tool-calls"){if(u&&i&&A.trim())try{z(i,B.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch($){console.warn("Failed to flush text segment over connection",$)}A=""}};await Promise.all([j,Y()]),w(),t==null||t({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"success"}})}catch(j){t==null||t({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"error",error:String(j)}}),r(j)}})}function se(e,o,i,t){let s=!!(i&&i.length>0),u=!!t,p=s||u,f=e.length>0&&e[e.length-1].role==="user"?e[e.length-1]:void 0,d=c=>{let g=[],a="";if(u&&(a+=`[Attached files]
15
- ${t}
16
- [End of attached files]
17
-
18
- `),c&&(a+=c),a&&g.push({type:"text",text:a}),s)for(let w of i)g.push({type:"image",image:w.data,mimeType:w.mimeType});return g};return o&&f&&f.content===o?[...e.slice(0,-1).map(g=>({role:g.role,content:g.content})),{role:"user",content:d(o)}]:o?[...e.map(c=>({role:c.role,content:c.content})),{role:"user",content:d(o)}]:p&&f?[...e.slice(0,-1).map(g=>({role:g.role,content:g.content})),{role:"user",content:d(f.content)}]:e.map(c=>({role:c.role,content:c.content}))}async function Nt(e,o,i,t,s,u,p){var c,g,a,w,r,y,l;console.log(`**** MEMO Node id: ${o.id} ****`),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"start"}});let n="",f=!1,d=Date.now();try{t==null||t({type:"info:memoNodeRunner",content:"Starting memo node execution"});let m=String(((c=o.data)==null?void 0:c.query_key)||"user_input"),N=W(m,{context:i.context??{},results:i.results??{},nodes:((a=(g=i.flowData)==null?void 0:g.state)==null?void 0:a.nodes)??[],edges:((r=(w=i.flowData)==null?void 0:w.state)==null?void 0:r.edges)??[],currentNodeId:o.id});if(N.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,n);return}if(!o.data.rag_id){t==null||t({type:"error:memoNodeRunner",content:"Missing rag_id"}),s==null||s(o.id,n);return}let R=String(N.value??"");t==null||t({type:"info:memoNodeRunner",content:`Query text: ${R}`}),t==null||t({type:"info:memoNodeRunner",content:"Generating embedding for query"});let h=await Ft(e,R,!0);t==null||t({type:"info:memoNodeRunner",content:`Embedding generated successfully, length: ${h.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 x=await e.env[`VDB_${(y=i.flowData)==null?void 0:y.tenant}_1024`].query(h.data[0],{namespace:F,topK:o.data.topk,returnMetadata:"all"});t==null||t({type:"info:memoNodeRunner",content:`RAG query completed for namespace ${F}, matches: ${((l=x.matches)==null?void 0:l.length)||0}`}),Array.isArray(x.matches)&&k.push(...x.matches)}let _=Date.now()-d;n=k.map(F=>{var x;return(x=F.metadata)==null?void 0:x.value}).filter(F=>typeof F=="string").join(`
19
-
20
- `),p==null||p({type:"memo_search",payload:{nodeId:o.id,searchLatencyMs:_,retrievedContext:n}}),t==null||t({type:"info:memoNodeRunner",content:`Context retrieval complete, length: ${n.length}, preview: ${n.substring(0,200)}...`}),t==null||t({type:"info:memoNodeRunner",content:"Memo node execution completed successfully"}),f=!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{f&&(s==null||s(o.id,n),t==null||t({type:"info:memoNodeRunner",content:`onResult called with context length: ${n.length}`}),t==null||t({type:"node:execution",content:{nodeId:o.id,nodeType:o.type,status:"success"}}))}}async function Rt(e,o,i,t,s,u,p){var c,g,a,w,r,y,l,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}),p==null||p({type:"start_node",payload:{userMessage:(c=i==null?void 0:i.context)==null?void 0:c.user_input}});let n=((g=o.data)==null?void 0:g.allow_images)!==!1,f=((a=o.data)==null?void 0:a.allow_documents)!==!1;!n&&(i!=null&&i.context)&&(i.context.user_images=[],u==null||u({...i})),!f&&(i!=null&&i.context)&&(i.context.files="",u==null||u({...i}));let d={};for(let N of S(o.data))d[N.name]=(w=i==null?void 0:i.context)==null?void 0:w[N.name];s==null||s(o.id,{...d,user_input:(r=i==null?void 0:i.context)==null?void 0:r.user_input,images:n?(y=i==null?void 0:i.context)==null?void 0:y.user_images:[],files:f?(l=i==null?void 0:i.context)==null?void 0:l.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 ss(e,o,i){let t=o;async function s(){var d;if(await((d=i==null?void 0:i.shouldStop)==null?void 0:d.call(i)))throw new it}async function u(d){let c=d;for(t.executedNodes=t.executedNodes||[],t.context=t.context||{},t.results=t.results||{};c&&c.id;)await s(),await p(c),await s(),c=ae(c,t.flowData,t)}async function p(d){var r,y;let c=f[d.type];if(!c){(r=i==null?void 0:i.onError)==null||r.call(i,`Unknown node type: ${d.type}`);return}t.executedNodes=t.executedNodes||[],t.executedNodes.push({id:d.id,type:d.type,label:typeof((y=d.data)==null?void 0:y.label)=="string"?d.data.label:void 0}),t.lastNodeId=d.id;let g=l=>{var m;return(m=i==null?void 0:i.onServerEvent)==null?void 0:m.call(i,{...l,ts:Date.now()})},a=l=>{var m,N;if((m=i==null?void 0:i.onTelemetry)==null||m.call(i,l),l.type==="llm_telemetry"||l.type==="class_telemetry"||l.type==="memory_update"){let R=(N=l.payload)==null?void 0:N.usage;R&&(t.tokenUsage=t.tokenUsage||{promptTokens:0,completionTokens:0,totalTokens:0},t.tokenUsage.promptTokens+=R.promptTokens||0,t.tokenUsage.completionTokens+=R.completionTokens||0,t.tokenUsage.totalTokens+=R.totalTokens||0)}};return await c(e,d,t,g,(l,m)=>{t.results[l]=m},i==null?void 0:i.onChangeState,a)}let n=async d=>{var w,r,y,l,m,N,R;let c=Date.now(),g="completed",a;try{await s();let h=typeof d=="string"?It(d):d,T=(h==null?void 0:h.text)||"",k=(h==null?void 0:h.images)||[],_=(h==null?void 0:h.documents)||[],b=await io(_,e.env),C=b.length>0?b.map(D=>`--- file: ${D.name} ---
21
- ${D.text}`).join(`
22
-
23
- `):"";t.context={user_input:T,user_images:k,files:C},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},t.executedNodes=[],(w=i==null?void 0:i.onServerEvent)==null||w.call(i,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:F,error:x}=re(t.flowData);if(!F)g="failed",a=x||"Flow Format Error",(r=i==null?void 0:i.onError)==null||r.call(i,a);else{let D=S(F.data),{values:M,errors:V}=$t(D,h==null?void 0:h.inputs);if(V.length>0)return g="failed",a=`Invalid flow inputs: ${V.join("; ")}`,(y=i==null?void 0:i.onError)==null||y.call(i,a),{status:g,error:a};if(t.context={...t.context,inputs:M,...M},t.context.user_input||(t.context.user_input=T),Dt(F.data)){let I=Ot(Mt(F.data));t.context.memory=kt(e.agentMemory||"",I).content}else t.context.memory="";await u(F),(l=i==null?void 0:i.onServerEvent)==null||l.call(i,{type:"agent:telemetry",content:{durationMs:Date.now()-c,tokenUsage:t.tokenUsage},timestamp:Date.now()})}}catch(h){h instanceof it?(g="stopped",a=h.message,(m=i==null?void 0:i.onServerEvent)==null||m.call(i,{type:"agent:stopped",content:a,timestamp:Date.now()})):(g="failed",a=h instanceof Error?h.message:"Agent execution failed",(N=i==null?void 0:i.onError)==null||N.call(i,a))}finally{(R=i==null?void 0:i.onServerEvent)==null||R.call(i,{type:"agent:complete",content:{status:g,durationMs:Date.now()-c},timestamp:Date.now()})}return{status:g,error:a}},f={startNode:Rt,classifierNode:wt,llmNode:ht,memoNode:Nt,answerNode:nt,apiNode:ct,toolNode:pt,workerNode:mt,crawlNode:ft};return n}var it=class extends Error{constructor(){super("Stopped by user"),this.name="FlowExecutionStoppedError"}};function re(e){var c,g;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 a of o.nodes){if(((c=a.data)==null?void 0:c.varMapping)!==void 0)return{error:`Flow uses removed varMapping on node ${a.id}.`};let w=bt(a);if(w.length>0)return{error:w[0]}}let i=o.nodes.filter(a=>a.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(a=>a.type==="answerNode");if(s.length===0)return{error:"Flow must include at least one ANSWER node."};let u=new Map;for(let a of o.edges)u.has(a.source)||u.set(a.source,[]),u.get(a.source).push(a.target);let p=new Map;for(let a of o.edges)p.has(a.target)||p.set(a.target,[]),p.get(a.target).push(a.source);let n=go(t.id,u),f=new Set;for(let a of s){let w=go(a.id,p);for(let r of w)f.add(r)}let d=[];for(let a of n)if(!f.has(a)){let w=o.nodes.find(r=>r.id===a);if(w){let r=((g=w.data)==null?void 0:g.label)||"";d.push(`${a}(${r},${w.type})`)}}return d.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${d.join(", ")}`}:{startNode:t}}function go(e,o){let i=new Set,t=[e];for(i.add(e);t.length>0;){let s=t.shift(),u=o.get(s)||[];for(let p of u)i.has(p)||(i.add(p),t.push(p))}return i}function ne(e,o){var i;return((i=e.state)==null?void 0:i.nodes.find(t=>t.id===o))||null}function ae(e,o,i){var n;let t=o==null?void 0:o.state;if(!t)return null;let s=t.edges.filter(f=>f.source===e.id);if(s.length===0)return null;let u=s[0].target;if(e.type==="classifierNode"&&((n=i==null?void 0:i.context)!=null&&n.classified_id)){let f=i.context.classified_id,d=s.find(c=>c.sourceHandle===`source-${f}`);d?u=d.target:console.log(`No matching edge, falling back to first: ${u}`)}return ne(o,u)}export{z as a,Ro as b,lo as c,Ve as d,Yo as e,et as f,Ee as g,ss as h,it as i};
@@ -1,3 +0,0 @@
1
- var g=(a=>(a.START_NODE="startNode",a.CLASSIFIER_NODE="classifierNode",a.MEMO_NODE="memoNode",a.LLM_NODE="llmNode",a.ANSWER_NODE="answerNode",a.API_NODE="apiNode",a.TOOL_NODE="toolNode",a.WORKER_NODE="workerNode",a.CRAWL_NODE="crawlNode",a))(g||{});var b=/^[a-zA-Z][a-zA-Z0-9_]*$/;function m(e){let t=e==null?void 0:e.inputs;if(!Array.isArray(t))return[];let n=[],r=new Set;for(let o of t){let s=typeof(o==null?void 0:o.name)=="string"?o.name.trim():"";if(!s||!b.test(s)||r.has(s))continue;r.add(s);let i=k.includes(o==null?void 0:o.type)?o.type:"string";n.push({name:s,type:i,required:(o==null?void 0:o.required)===!0,default:(o==null?void 0:o.default)??void 0})}return n}function P(e,t){let n=e.label||e.name;switch(e.type){case"number":{let r=typeof t=="number"?t:Number(String(t).trim());return Number.isFinite(r)?{value:r}:{error:`"${n}" must be a number`}}case"boolean":{if(typeof t=="boolean")return{value:t};let r=String(t).trim().toLowerCase();return["true","1","yes","si","s\xED"].includes(r)?{value:!0}:["false","0","no"].includes(r)?{value:!1}:{error:`"${n}" must be true or false`}}case"json":{if(typeof t=="object")return{value:t};try{return{value:JSON.parse(String(t))}}catch{return{error:`"${n}" must be valid JSON`}}}default:return{value:typeof t=="string"?t:String(t)}}}function S(e){return e==null||typeof e=="string"&&e.trim()===""}function Z(e,t){let n={},r=[],o=t??{};for(let s of e){let i=o[s.name],u=S(i)?s.default:i;if(S(u)){s.required&&r.push(`"${s.label||s.name}" is required`);continue}let{value:c,error:a}=P(s,u);a?r.push(a):n[s.name]=c}return{values:n,errors:r}}function $(e){return typeof e=="string"?e:e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function G(e,t,n){let r=t.user_input;if(typeof r=="string"&&r.trim())return r;let o=e.filter(i=>i.name!=="user_input"&&t[i.name]!==void 0).map(i=>`- ${i.label||i.name}: ${$(t[i.name])}`),s=(n==null?void 0:n.trim())||"Automated execution";return o.length>0?`${s}
2
- ${o.join(`
3
- `)}`:s}var k=["string","number","boolean","json"];var O=/^[A-Za-z][A-Za-z0-9_]*$/;function N(e){switch(e){case"startNode":return[{name:"user_input",path:"user_input",type:"string"},{name:"images",path:"images",type:"image"},{name:"files",path:"files",type:"file"},{name:"memory",path:"memory",type:"string"}];case"llmNode":return[{name:"output",path:"",type:"string"}];case"apiNode":return[{name:"ok",path:"ok",type:"boolean"},{name:"status",path:"status",type:"number"},{name:"data",path:"data",type:"object"}];case"toolNode":case"workerNode":case"crawlNode":return[{name:"ok",path:"ok",type:"boolean"},{name:"data",path:"data",type:"object"},{name:"error",path:"error",type:"string"}];case"classifierNode":return[{name:"classification",path:"classification",type:"string"}];case"memoNode":return[{name:"context",path:"",type:"string"}];default:return[]}}function T(e){return e.type!=="startNode"?[]:m(e.data).map(t=>({name:t.name,path:t.name,type:t.type==="json"?"object":t.type}))}function C(e){var o;let t=[...N(e.type),...T(e),...Array.isArray((o=e.data)==null?void 0:o.outVars)?e.data.outVars:[]],n=new Set,r=[];for(let s of t){let i=typeof(s==null?void 0:s.name)=="string"?s.name.trim():"";O.test(i)?n.has(i)?r.push(`Node ${e.id} has duplicate output name "${i}"`):n.add(i):r.push(`Node ${e.id} has an invalid output name`)}return r}function d(e){var r;let t=[...N(e.type),...T(e)];return[...(Array.isArray((r=e.data)==null?void 0:r.outVars)?e.data.outVars:[]).map(o=>({...o,name:typeof(o==null?void 0:o.name)=="string"?o.name.trim():""})).filter(o=>O.test(o.name)).map(o=>({...o,source:"user"})),...t.map(o=>({...o,source:"default"}))]}function x(e,t){let n=new Set,r=[t],o=new Set([t]);for(;r.length>0;){let s=r.shift();for(let i of e)i.target!==s||o.has(i.source)||(o.add(i.source),n.add(i.source),r.push(i.source))}return n}function L(e,t){var o,s;if(e.type!=="startNode")return t;let n=((o=e.data)==null?void 0:o.allow_images)===!0,r=((s=e.data)==null?void 0:s.allow_documents)===!0;return t.filter(i=>!(i.name==="images"&&!n||i.name==="files"&&!r))}function U(e,t,n){let r=x(t,n),o=[],s=new Set;for(let i of r){let u=e.find(c=>c.id===i);if(u)for(let c of L(u,d(u))){let a=u.type==="startNode"&&c.source==="default"?c.name:`${u.id}.${c.name}`;s.has(a)||(s.add(a),o.push({...c,ref:a,nodeId:u.id}))}}return o}function ae(e,t,n){return new Set(U(e,t,n).map(r=>r.ref))}function v(e,t){let n=x(t.edges,t.currentNodeId);return t.nodes.filter(r=>n.has(r.id)&&e.startsWith(`${r.id}.`)).sort((r,o)=>o.id.length-r.id.length)[0]}function I(e,t){return e.slice(t.length+1)}function ue(e){return e.type==="image"||e.type==="file"}function j(e){if(!e)return!1;let t=e.split(";")[0].trim().toLowerCase();return t==="application/json"||t.endsWith("+json")}function E(e,t){let n=e.trim();if(!n||!(j(t)||n.startsWith("{")||n.startsWith("[")))return e;try{return JSON.parse(n)}catch{return e}}async function le(e){let t=e.headers.get("content-type"),n=await e.text();return E(n,t)}var W=new Set(["__proto__","prototype","constructor"]),y="\0__ORA_OB__\0",h="\0__ORA_CB__\0",f=class extends Error{constructor(n,r){super(r);this.code=n;this.name="VariableResolutionError"}code};function M(e){for(let t of e.split("."))if(W.has(t))throw new f("UNSAFE_PATH",`Unsafe variable path segment "${t}"`)}function w(e,t){if(!t)return e;M(t);let n=e;for(let r of t.split(".")){if(n==null||!Object.prototype.hasOwnProperty.call(Object(n),r))return;n=n[r]}return n}var J=new Set(["apiNode","toolNode","workerNode"]);function X(e){if(e!==null&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"data")){let t=e.data;return typeof t=="string"?E(t):t}}function V(e,t,n){let r=t.path??"";if(t.source==="user"&&n&&J.has(n)){let o=w(X(e),r);if(o!==void 0)return o}return w(e,r)}function Ne(e,t){let n={};for(let r of d(e))n[r.name]=V(t,r,e.type);return n}function q(e,t){var r,o,s,i,u,c,a,p;if(Object.prototype.hasOwnProperty.call(t.refOverrides??{},e))return{value:t.refOverrides[e]};let n=t.nodes.find(l=>l.type==="startNode");if(e==="user_input")return{value:(r=t.context)==null?void 0:r.user_input};if(e==="memory")return{value:((o=t.context)==null?void 0:o.memory)??""};if(e==="images"&&((s=n==null?void 0:n.data)==null?void 0:s.allow_images)===!0)return{value:(i=t.context)==null?void 0:i.user_images};if(e==="files"&&((u=n==null?void 0:n.data)==null?void 0:u.allow_documents)===!0)return{value:(c=t.context)==null?void 0:c.files};if(e==="classified_id")return{value:(a=t.context)==null?void 0:a.classified_id};if(n&&m(n.data).some(l=>l.name===e))return{value:(p=t.context)==null?void 0:p[e]}}function A(e,t){var R;let n=e.trim();if(!n)throw new f("INVALID_EXPRESSION","Variable reference is empty");let r=n.includes(".")?void 0:q(n,t);if(r)return r;if(!n.includes("."))throw new f("UNKNOWN_CONTEXT_REF",`Unknown run-context variable "${n}"`);let o=v(n,t);if(!o)throw new f("OUT_OF_SCOPE",`Variable "${n}" is not in this node's connection scope`);let s=I(n,o.id),[i,...u]=s.split("."),c=d(o).find(D=>D.name===i);if(!c)throw new f("UNKNOWN_OUTPUT",`Node "${o.id}" does not expose output "${i}"`);if(Object.prototype.hasOwnProperty.call(t.refOverrides??{},n))return{value:t.refOverrides[n]};let a=(R=t.results)==null?void 0:R[o.id];if(a==null)return{value:void 0,missing:"ancestor_not_executed"};let p=V(a,c,o.type),l=u.length>0?w(p,u.join(".")):p;return l==null?{value:void 0,missing:"path_not_found"}:{value:l}}function Ee(e,t){return A(e,t).value}function K(e){let t=null,n=!1;for(let r=0;r<e.length-1;r+=1){let o=e[r];if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(t){o===t&&(t=null);continue}if(o==='"'||o==="'"){t=o;continue}if(o==="?"&&e[r+1]==="?")return{ref:e.slice(0,r).trim(),rawDefault:e.slice(r+2).trim()}}return{ref:e.trim()}}function B(e){if(e.length<2||!['"',"'"].includes(e[0])||e.at(-1)!==e[0])throw new f("INVALID_EXPRESSION","Template defaults must be quoted string literals");if(e[0]==='"')try{return JSON.parse(e)}catch{throw new f("INVALID_EXPRESSION","Invalid double-quoted template default")}return e.slice(1,-1).replace(/\\'/g,"'").replace(/\\\\/g,"\\")}function F(e){let{ref:t,rawDefault:n}=K(e.trim());if(!t)throw new f("INVALID_EXPRESSION","Template expression is missing a variable reference");return{ref:t,...n===void 0?{}:{defaultValue:B(n)}}}function _e(e){let t=e.replace(/\\\{\{/g,y).replace(/\\\}\}/g,h),n=[],r=/\{\{\s*([^}]+?)\s*\}\}/g;for(let o of t.matchAll(r))n.push(F(o[1]).ref);return n}function z(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ye(e,t,n){let r=z(t);return e.replace(new RegExp(`(\\{\\{\\s*)${r}(?=\\.)`,"g"),`$1${n}`)}function _(e,t){return typeof e=="string"?t?JSON.stringify(e).slice(1,-1):e:typeof e=="object"&&e!==null?t?JSON.stringify(e):JSON.stringify(e,null,2):e!=null?t?JSON.stringify(e):String(e):""}function H(e,t){var n;throw(n=t==null?void 0:t.onError)==null||n.call(t,e.message),e}function he(e,t,n,r){if(!e)return e;let o=(r==null?void 0:r.serializeNonStrings)??!1,s=e.replace(/\\\{\{/g,y).replace(/\\\}\}/g,h),i=/\{\{\s*([^}]+?)\s*\}\}/g;return s=s.replace(i,(u,c)=>{try{let a=F(c);if(a.ref.startsWith("secrets.")){let l=a.ref.slice(8);if(!Object.prototype.hasOwnProperty.call(n.secrets??{},l))throw new f("MISSING_SECRET",`Secret "${l}" is not defined for this tenant`);return _(n.secrets[l],o)}let p=A(a.ref,n);if(p.missing){if(a.defaultValue!==void 0)return _(a.defaultValue,o);let l=p.missing==="ancestor_not_executed"?`Ancestor for variable "${a.ref}" did not execute in this branch`:`Variable path "${a.ref}" did not produce a value`;throw new f(p.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",l)}return _(p.value,o)}catch(a){if(a instanceof f)return H(a,r);throw a}}),s.split(y).join("{{").split(h).join("}}")}export{g as a,b,m as c,Z as d,G as e,O as f,N as g,C as h,d as i,x as j,U as k,ae as l,v as m,I as n,ue as o,j as p,E as q,le as r,f as s,w as t,V as u,Ne as v,A as w,Ee as x,F as y,_e as z,ye as A,he as B};
@@ -1 +0,0 @@
1
- var r={};function e(o){}export{r as a,e as b};
@@ -1 +0,0 @@
1
- import{d as a,e as b}from"./chunk-ZYIULB2P.js";import"./chunk-QEZQZG6Z.js";import"./chunk-V6JSMX5A.js";import"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{a as customHttpTool,b as default};