@hugex/ai 3.4.1 → 3.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{FlowEngine-UNMMHMN6.js → FlowEngine-JDCHJG3W.js} +1 -1
- package/dist/{chunk-Z4CYLB7J.js → chunk-62G7NURX.js} +1 -1
- package/dist/chunk-BMZU5UOO.js +12 -0
- package/dist/chunk-G73VSMK7.js +12 -0
- package/dist/chunk-GHMAKIZO.js +1 -0
- package/dist/chunk-LUS5CJY2.js +3 -0
- package/dist/client.js +1 -1
- package/dist/common/flow-graph/schema.d.ts +6 -6
- package/dist/common/types/node-types.d.ts +3 -2
- package/dist/common/types/web-actions-types.d.ts +206 -0
- package/dist/common/utils/webActions.d.ts +31 -0
- package/dist/common/utils/webActionsBlock.d.ts +11 -0
- package/dist/common/utils/webActionsBrowser.d.ts +117 -0
- package/dist/common/utils/webActionsExec.d.ts +25 -0
- package/dist/common/utils/webActionsInspect.d.ts +12 -0
- package/dist/common/utils/webActionsSession.d.ts +14 -0
- package/dist/common.d.ts +7 -0
- package/dist/common.js +1 -1
- package/dist/httpTool-DIQRGKMU.js +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +6 -6
- package/dist/server/core/WebSessionDO.d.ts +31 -0
- package/dist/server/runners/webActionsNodeRunner.d.ts +23 -0
- package/package.json +2 -1
- package/dist/chunk-J67BCWE3.js +0 -1
- package/dist/chunk-KKJW6HJA.js +0 -3
- package/dist/chunk-V43Y4KSA.js +0 -12
- package/dist/chunk-YXG3ZEUP.js +0 -10
- package/dist/httpTool-IW4W7CGE.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as a,i as b}from"./chunk-
|
|
1
|
+
import{h as a,i as b}from"./chunk-BMZU5UOO.js";import"./chunk-3D77ZXDC.js";import"./chunk-62G7NURX.js";import"./chunk-AKJFVR6J.js";import"./chunk-EHOK5FW2.js";import"./chunk-3K4IMMLP.js";import"./chunk-G73VSMK7.js";import"./chunk-LUS5CJY2.js";import"./chunk-HJPR76HF.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 +1 @@
|
|
|
1
|
-
import{t as N}from"./chunk-
|
|
1
|
+
import{t as N}from"./chunk-LUS5CJY2.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};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{a as pe}from"./chunk-3D77ZXDC.js";import{a as Z,b as E,c as fe,d as ft}from"./chunk-62G7NURX.js";import{a as We}from"./chunk-AKJFVR6J.js";import{a as ce,b as de,d as le,g as ue,i as Rt}from"./chunk-EHOK5FW2.js";import{a as Ue,b as Le}from"./chunk-3K4IMMLP.js";import{Aa as B,B as vt,Ba as he,C as Nt,Fa as xt,Ga as Ne,Ha as Re,Ia as Te,Ja as Ae,Ka as xe,L as oe,La as kt,Ma as ke,Na as Oe,O as ie,Oa as _e,P as ne,Pa as Ie,R as re,Ta as $e,Wa as be,Xa as Fe,Ya as De,a as v,aa as se,b as Yt,db as Ce,fb as Pe,gb as Me,hb as je,i as wt,ma as ae,pa as at,qa as me,r as Zt,s as Qt,sa as ge,ta as ye,u as Et,ua as we,v as ht,va as Tt,wa as At}from"./chunk-G73VSMK7.js";import{B as ee,c as ut,d as Gt,i as St,k as ot,r as te,s as q,v as it,w as z}from"./chunk-LUS5CJY2.js";import{a as Xt,b as Kt,d as zt}from"./chunk-YLDLDEUP.js";import{a as pt}from"./chunk-YHXUBVN2.js";import{a as lt}from"./chunk-3TXHFKDN.js";async function Ve(o,e){return o.length?!e||!e.HX_ORA_URL||!e.HX_API_KEY?(console.error("extractDocuments: missing HX_ORA_URL or HX_API_KEY"),o.map(t=>({name:t.name,text:""}))):await Promise.all(o.map(async t=>{try{let n=await fetch(`${e.HX_ORA_URL}/internal/files/extract`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e.HX_API_KEY},body:JSON.stringify(t)});if(!n.ok)return console.error(`extractDocuments: ${t.name} failed ${n.status}`),{name:t.name,text:""};let h=await n.json();return{name:t.name,text:h.text||""}}catch(n){return console.error(`extractDocuments: ${t.name} threw`,n),{name:t.name,text:""}}})):[]}function to(o,e,i){var t,n,h,f;return ot(((n=(t=i.flowData)==null?void 0:t.state)==null?void 0:n.nodes)??[],((f=(h=i.flowData)==null?void 0:h.state)==null?void 0:f.edges)??[],e.id).some(s=>s.ref===o&&(s.type==="image"||s.type==="file"))}function eo(o,e){var f,s,d,a,p,w,l;let i=Array.isArray((f=o.data)==null?void 0:f.outputMapping)?o.data.outputMapping:[];if(i.length===0)return null;let t=((d=(s=e.flowData)==null?void 0:s.state)==null?void 0:d.nodes)||[],n={},h=new Set;for(let u of i){let r=(a=u.key)==null?void 0:a.trim(),g=(p=u.from)==null?void 0:p.trim();if(!r||!g)throw new Error(`Answer node ${o.id} has an incomplete variable mapping`);if(h.has(r))throw new Error(`Answer node ${o.id} has duplicate output key "${r}"`);if(to(g,o,e))throw new Error(`Answer node ${o.id} cannot persist binary source "${g}"`);let m=z(g,{context:e.context||{},results:e.results||{},nodes:t,edges:((l=(w=e.flowData)==null?void 0:w.state)==null?void 0:l.edges)??[],currentNodeId:o.id}),c=m.value;if(m.missing||c===void 0||c===null){if(u.default===void 0)throw new q(m.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Answer node ${o.id} could not resolve output "${g}"`);c=u.default}n[r]=c,h.add(r)}try{JSON.stringify(n)}catch{throw new Error(`Answer node ${o.id} produced a value that is not JSON serializable`)}return n}async function Ot(o,e,i,t,n,h,f){var d,a,p;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let s;try{s=eo(e,i)}catch(w){throw t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(w)}}),w}s&&o.outputCollector&&o.outputCollector.add(e.id,s);try{let w=await((d=o.getMessages)==null?void 0:d.call(o))??[],l=((a=w[w.length-1])==null?void 0:a.type)==="text"?w[w.length-1].content:"NO-TEXT";f==null||f({type:"answer_node",payload:{userMessage:(p=i==null?void 0:i.context)==null?void 0:p.user_input,answer:l}})}catch(w){console.error("answerNodeRunner: failed to emit answer telemetry:",w),t==null||t({type:"debug",content:"Warning: failed to emit answer telemetry"})}n==null||n(e.id,{type:"answerNode",message:"Answer response for: "+e.data.response,saved:!0,persistenceRequested:!!s&&!!o.outputCollector,persisted:!1,...o.runId?{runId:o.runId}:{}}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}function X(o,e,i,t,n){var s,d,a,p,w;let h=(n==null?void 0:n.callerTag)??"llmNodeRunner",f=(n==null?void 0:n.serializeNonStrings)??!1;return ee(o,e,{context:i.context??{},results:i.results??{},nodes:((d=(s=i.flowData)==null?void 0:s.state)==null?void 0:d.nodes)??[],edges:((p=(a=i.flowData)==null?void 0:a.state)==null?void 0:p.edges)??[],currentNodeId:e.id,secrets:(w=n==null?void 0:n.sessionEnv)==null?void 0:w.secrets},{callerTag:h,serializeNonStrings:f,onError:l=>{t==null||t({type:`error:${h}`,content:l})}})}var _t="[redacted]",Be=8*1024;function oo(o){if(o==null)return{value:o,truncated:!1};let e=typeof o=="string"?o:JSON.stringify(o),i=new TextEncoder().encode(e);if(i.byteLength<=Be){if(typeof o=="string")return{value:o,truncated:!1};try{return{value:JSON.parse(e),truncated:!1}}catch{return{value:e,truncated:!1}}}let t=i.slice(0,Be);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function io(o,e){return it(o,e)}var It=(o,e,i,t,n)=>X(o,e,i,n,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function $t(o,e,i,t,n,h,f){var a,p,w,l,u,r;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let s=null,d=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(i.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(i.results||{}));let g=((a=e.data)==null?void 0:a.url)||"",m=It(g,e,i,o,t);if(console.log("[apiNodeRunner] resolved url:",Z(g)?E(m):m),!m){t==null||t({type:"error:apiNodeRunner",content:"Missing url"}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:"Missing url"}}),n==null||n(e.id,s);return}let c=(((p=e.data)==null?void 0:p.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",c);let y=((w=e.data)==null?void 0:w.headers)||{},R={},N={};for(let j in y)if(Object.prototype.hasOwnProperty.call(y,j)){let M=String(y[j]??"");N[j]=Z(M),R[j]=It(M,e,i,o,t)}let A,C=!1;if(c!=="GET"&&c!=="HEAD"&&((l=e.data)==null?void 0:l.body)!==void 0){let j=typeof e.data.body=="string"?e.data.body:JSON.stringify(e.data.body);C=Z(j),A=It(j,e,i,o,t),!R["Content-Type"]&&!R["content-type"]&&(R["Content-Type"]="application/json")}let I={};for(let j in R)I[j]=N[j]?_t:R[j];console.log("[apiNodeRunner] headers:",JSON.stringify(I)),console.log("[apiNodeRunner] body:",C?_t:A),t==null||t({type:"info:apiNodeRunner:request",content:{nodeId:e.id,method:c,url:Z(g)?E(m):m,headers:I,body:C?_t:A}});let D=Number((u=e.data)==null?void 0:u.timeoutMs),U=new AbortController,x=Number.isFinite(D)&&D>0?setTimeout(()=>U.abort(),D):null,T;try{console.log("[apiNodeRunner] fetching..."),T=await fetch(m,{method:c,headers:R,body:A,signal:U.signal}),console.log("[apiNodeRunner] fetch returned status:",T.status)}finally{x&&clearTimeout(x)}let b=T.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",b);let P=await te(T);console.log("[apiNodeRunner] payload preview:",typeof P=="string"?P.slice(0,200):JSON.stringify(P).slice(0,200)),s={ok:T.ok,status:T.status,data:P};let $=Date.now()-d;f==null||f({type:"api_call",payload:{nodeId:e.id,url:m,method:c,status:T.status,latencyMs:$}});let{value:_,truncated:V}=oo(P);t==null||t({type:"info:apiNodeRunner:response",content:{nodeId:e.id,ok:T.ok,status:T.status,latencyMs:$,data:_,truncated:V,outVars:io(e,s)}}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}catch(g){console.error("Error processing ApiNode:",g),t==null||t({type:"error:apiNodeRunner",content:`API node execution failed: ${g}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(g)}})}finally{console.log("[apiNodeRunner] final result:",(r=JSON.stringify(s))==null?void 0:r.slice(0,300)),n==null||n(e.id,s)}}var no="[redacted]",qe=8*1024;function bt(o,e){if(typeof o=="string")return Z(o)?typeof e=="string"&&/^https?:\/\//i.test(e)?E(e):no:e;if(o&&typeof o=="object"&&!Array.isArray(o)){let i={},t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};for(let[n,h]of Object.entries(o))i[n]=bt(h,t[n]);return i}if(Array.isArray(o)){let i=Array.isArray(e)?e:[];return o.map((t,n)=>bt(t,i[n]))}return e}function ro(o){if(o==null)return{value:o,truncated:!1};let e=typeof o=="string"?o:JSON.stringify(o),i=new TextEncoder().encode(e);if(i.byteLength<=qe){if(typeof o=="string")return{value:o,truncated:!1};try{return{value:JSON.parse(e),truncated:!1}}catch{return{value:e,truncated:!1}}}let t=i.slice(0,qe);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function so(o,e){return it(o,e)}var ao=(o,e,i,t,n)=>X(o,e,i,n,{callerTag:"toolNodeRunner",serializeNonStrings:!0,sessionEnv:t});function mt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:{}}function co(o){let e=mt(o);if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum.every(n=>typeof n=="string"||typeof n=="number")?"enum":"unsupported";switch(Array.isArray(e.type)?e.type.find(t=>typeof t=="string"&&t!=="null"):e.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 lo(o,e){var f,s;let i={},t={},n=((f=o.data)==null?void 0:f.inputSchema)??e;if(n&&typeof n=="object"&&!Array.isArray(n)){t=mt(mt(n).properties);for(let[d,a]of Object.entries(t))i[d]=co(a);return{types:i,properties:t}}let h=(s=o.data)==null?void 0:s.argTypes;if(h&&typeof h=="object"&&!Array.isArray(h))for(let[d,a]of Object.entries(h))typeof a=="string"&&(i[d]=a);return{types:i,properties:t}}function uo(o,e,i){if(o.trim()!==""){if(o==="null"&&e&&e!=="string"&&e!=="enum")return null;switch(e){case"string":return o;case"enum":{let t=mt(i).enum;if(Array.isArray(t)){let n=t.find(h=>String(h)===o);if(n!==void 0)return n}return o}case"number":{let t=Number(o);return Number.isFinite(t)?t:o}case"integer":{let t=Number.parseInt(o,10);return Number.isFinite(t)?t:o}case"boolean":return o==="true"?!0:o==="false"?!1:o;case"object":case"array":case"unsupported":try{return JSON.parse(o)}catch{return o}default:return o}}}function po(o){return o===void 0||typeof o=="string"&&o.trim()===""}function Ft(o,e,i,t,n,h,f){if(typeof o=="string"){let s=o.includes("{{")?ao(o,e,i,t,n):o;return uo(s,h,f)}if(o&&typeof o=="object"&&!Array.isArray(o)){let s={};for(let[d,a]of Object.entries(o))s[d]=Ft(a,e,i,t,n);return s}return Array.isArray(o)?o.map(s=>Ft(s,e,i,t,n)):o}function fo(o,e,i,t,n,h){let f={};for(let[s,d]of Object.entries(o)){let a=Ft(d,e,i,t,n,h.types[s],h.properties[s]);po(a)||(f[s]=a)}return f}async function mo(o){if(o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs={},o.toolDefs;let e=await pt(o.env),i={};for(let t of e)t!=null&&t.id&&(i[t.id]=t);return o.toolDefs=i,i}function go(o){var e,i,t;return((e=o.data)==null?void 0:e.source)==="catalog"?"catalog":((i=o.data)==null?void 0:i.source)==="composio"?"composio":(((t=o.data)==null?void 0:t.source)==="http","http")}function yo(o,e,i){let t=Rt(o.execution);if(t.authMode==="manual"){let n=ce(t,o.id);if(!n)throw new Error(`Composio tool '${o.name}' is missing connection scope`);return de(n)}return ue(e,i,{allowChatIdFallback:!0})}async function Dt(o,e,i,t,n,h,f){var p,w,l,u,r,g;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let s={ok:!1,data:null,error:null},d=Date.now(),a=go(e);try{if(a==="catalog")throw new Error("This Tool node still uses a curated catalog connector. Reconfigure it to a tenant HTTP or connector tool.");let m=(p=e.data)!=null&&p.args&&typeof e.data.args=="object"&&!Array.isArray(e.data.args)?e.data.args:{},c=typeof((w=e.data)==null?void 0:w.toolId)=="string"?e.data.toolId.trim():"";if(!c)throw new Error("Tool nodes require toolId");let R=(await mo(o))[c];if(!R)throw new Error(`Tool ${c} not found`);let N="";if(a==="composio"){if(R.kind!=="composio")throw new Error(`Tool ${c} is not a connector tool`);if(N=typeof((l=e.data)==null?void 0:l.toolSlug)=="string"?e.data.toolSlug.trim():"",!N)throw new Error("Connector tool nodes require toolSlug");let x=Rt(R.execution);if(!le(x.tools).includes(N))throw new Error(`Tool slug ${N} is not enabled on connector ${c}`)}else if(R.kind!=="http")throw new Error(`Tool ${c} is not an HTTP tool`);let A=lo(e,a==="http"?R.inputSchema:void 0),C=fo(m,e,i,o,t,A);if(t==null||t({type:"info:toolNodeRunner:request",content:{nodeId:e.id,source:a,toolSlug:(u=e.data)==null?void 0:u.toolSlug,toolId:(r=e.data)==null?void 0:r.toolId,args:bt(m,C)}}),a==="composio"){let x=typeof((g=e.data)==null?void 0:g.toolVersion)=="string"?e.data.toolVersion.trim():"",T=await pe(o,{toolSlug:N,connectionScope:yo(R,o,i),toolVersion:x||null,arguments:C});s={ok:T.ok,data:T.ok?T.data:null,error:T.ok?null:T.error??"Tool execution failed"}}else{let x=ft(R,o,i,t);if(!x.execute)throw new Error(`Tool ${c} is missing an execute handler`);let T=await x.execute(C,{}),b=T&&typeof T=="object"&&"error"in T&&T.error?String(T.error):null;s={ok:!b,data:T,error:b}}let I=Date.now()-d;f==null||f({type:"tool_call",payload:{nodeId:e.id,url:a==="composio"?`composio:${N}`:`tool:${c}`,method:"EXECUTE",status:s.ok?200:502,latencyMs:I}});let{value:D,truncated:U}=ro(s.data);t==null||t({type:"info:toolNodeRunner:response",content:{nodeId:e.id,ok:s.ok,latencyMs:I,data:D,truncated:U,error:s.error,outVars:so(e,s)}}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:s.ok?"success":"error",error:s.error??void 0}})}catch(m){let c=m instanceof Error?m.message:String(m);s={ok:!1,data:null,error:c},t==null||t({type:"error:toolNodeRunner",content:`Tool node execution failed: ${c}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:c}})}finally{n==null||n(e.id,s)}}var wo=1440*60*1e3,Xe=8*1024;function Ke(o){if(o==null)return{value:o,truncated:!1};let e=new TextEncoder().encode(JSON.stringify(o));return e.byteLength<=Xe?{value:o,truncated:!1}:{value:new TextDecoder().decode(e.slice(0,Xe)),truncated:!0}}async function Ct(o,e,i,t,n,h,f){var w,l;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let s={ok:!1,data:null,error:null},d=Date.now(),a="crawl:unknown",p=u=>{let r=JSON.stringify(u);for(let g of Object.values(o.secrets??{}))g&&(r=r.split(JSON.stringify(g).slice(1,-1)).join("[redacted]"),r=r.split(encodeURIComponent(g)).join("[redacted]"));return JSON.parse(r)};try{let u=o.env;if(!(u!=null&&u.CF_ACCOUNT_ID)||!(u!=null&&u.CF_BROWSER_RUN_TOKEN))throw new Error("Crawl no configurado: faltan CF_ACCOUNT_ID / CF_BROWSER_RUN_TOKEN");let r=X(e.data.url,e,i,t,{callerTag:"crawlNodeRunner",serializeNonStrings:!0,sessionEnv:o}),g=Zt(e.data,r),m=Z(e.data.url);a=`crawl:${p(new URL(r).host)}`;let c=`crawl:pending:${await Qt(g)}`,y=(w=o.ctx)==null?void 0:w.storage,R=await(y==null?void 0:y.get(c)),N=R&&typeof R.jobId=="string"&&R.jobId&&Number.isFinite(R.createdAt)&&Date.now()-R.createdAt>=0&&Date.now()-R.createdAt<wo;R&&!N&&await(y==null?void 0:y.delete(c)),t==null||t({type:"info:crawlNodeRunner:request",content:{nodeId:e.id,url:m?p(E(r)):r,resumeJobId:N?R.jobId:void 0}}),{result:s}=await Et({accountId:u.CF_ACCOUNT_ID,apiToken:u.CF_BROWSER_RUN_TOKEN},e.data,{url:r,...N?{resumeJobId:R.jobId}:{}}),s.error==="timeout"&&((l=s.data)!=null&&l.jobId)?await(y==null?void 0:y.put(c,{jobId:s.data.jobId,createdAt:N?R.createdAt:Date.now()})):s.data&&s.data.status!=="running"&&await(y==null?void 0:y.delete(c))}catch(u){s={ok:!1,data:null,error:u instanceof Error?u.message:String(u)},t==null||t({type:"error:crawlNodeRunner",content:p(`Crawl node execution failed: ${s.error}`)})}finally{let u=Date.now()-d;f==null||f({type:"tool_call",payload:{nodeId:e.id,url:a,method:"EXECUTE",status:s.ok?200:502,latencyMs:u}});let r=Ke(p(s.data));t==null||t({type:"info:crawlNodeRunner:response",content:{nodeId:e.id,ok:s.ok,latencyMs:u,data:r.value,truncated:r.truncated,error:p(s.error),outVars:Ke(p(it(e,s))).value}}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:s.ok?"success":"error",error:p(s.error)??void 0}}),n==null||n(e.id,s)}}var ho=6e4,No=250,Ro=2e3;function To(o){let e=o;if(!(e!=null&&e.WEB_SESSION)||!e.WEB_SESSION_KEY)return null;let i=e.WEB_SESSION;return t=>i.get(i.idFromName(t))}async function Pt(o,e,i,t,n,h,f){var U,x,T,b,P;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let s=Date.now(),d=s+ht.timeoutMs,a=((U=o.env)==null?void 0:U.WEB_ACTIONS_ALLOW_PRIVATE)==="true",p=Object.values(o.secrets??{}).filter($=>typeof $=="string"&&$!==""),w=[],l=()=>[...p,...w],u=$=>{t==null||t({type:$.type,content:at($.content,l())})},r={callerTag:"webActionsNodeRunner",serializeNonStrings:!0,sessionEnv:o},g={ok:!1,data:null,error:null},m="unknown",c,y,R,N,A,C=async()=>{let $=R;if(R=void 0,A=void 0,$)try{await B($.close(),Date.now()+3e3)}catch{}},I={},D=[];try{let $=e.data??{},_=vt($);if(_.length>0)throw new Error(`WebActions inv\xE1lido: ${_[0].message}`);let V=(x=o.env)==null?void 0:x.BROWSER;if(!V)throw new Error("WebActions no configurado: falta el binding BROWSER");if(typeof $.url!="string")throw new Error("WebActions inv\xE1lido: url is required.");let j=X($.url,e,i,u,r);c=j,ge(j,{allowPrivate:a});let M=Array.isArray($.actions)?$.actions:[];d=s+($.timeoutMs??ht.timeoutMs),u({type:"info:webActionsNodeRunner:request",content:{nodeId:e.id,url:Z($.url)?E(j):j,steps:M.length}});let G=L=>X(L,e,i,u,r),k={};for(let L of $.headers??[]){let H=G(L.value);H&&w.push(H),k[L.name]=H}let F=L=>{let H=L.find(Y=>Y.blocked);return H!=null&&H.blocked?(u({type:"info:webActionsNodeRunner:blocked",content:{nodeId:e.id,vendor:H.blocked.vendor,kind:H.blocked.kind}}),!0):!1},O=(T=$.session)!=null&&T.enabled?$.session:void 0,W=null,J,nt;if(O){let L=To(o.env);if(!L)u({type:"info:webActionsNodeRunner:session",content:{nodeId:e.id,mode:"unavailable",reason:"falta WEB_SESSION o WEB_SESSION_KEY"}});else{let H=M.slice(0,O.loginSteps).map(K=>"value"in K&&typeof K.value=="string"?G(K.value):"checked"in K&&typeof K.checked=="string"?G(K.checked):"");w.push(...H.filter((K,S)=>K!==""&&["fill","select"].includes(M[S].op)));let Y=String(((b=i.flowData)==null?void 0:b.tenant)??((P=o.env)==null?void 0:P.TENANT)??"");W=L(await Ne(Y,j,H,O.generation??0)),J=M[Nt(M,0,O.loginSteps)].target,nt=M[Nt(M,O.loginSteps)].target}}let{launch:ct}=await import("@cloudflare/playwright"),rt=!1,yt=ct(V).then(async L=>{if(rt){try{await B(L.close(),Date.now()+3e3)}catch{}throw new Error("timeout")}return L});try{y=await B(yt,d)}catch(L){throw rt=!0,L}let ve=y,Bt=(L,H)=>({deadline:d,sensitive:w,allowPrivate:a,activity:L,indexOffset:H,resolve:G,onAmbiguous:(Y,K)=>{u({type:"info:webActionsNodeRunner:ambiguous",content:{nodeId:e.id,stepId:K.id,count:Y}})}}),Jt=async L=>{if(W)try{await B(W.save(await L.storageState({indexedDB:!0}),Date.now()),d),u({type:"info:webActionsNodeRunner:session",content:{nodeId:e.id,mode:"saved"}})}catch(H){u({type:"info:webActionsNodeRunner:session",content:{nodeId:e.id,mode:"save_failed",error:At(H).message}})}};for(let L=0;;L++){D.length=0;for(let dt of Object.keys(I))delete I[dt];let H=W?await B(W.load(),d).catch(()=>null):null;R=await B(ve.newContext(H?{storageState:H.state}:{}),d),A=await B(R.newPage(),d),Object.keys(k).length>0&&await B(R.setExtraHTTPHeaders(k),d),await ye(A,{allowPrivate:a},d),N==null||N.dispose(),N=he(A);try{await A.goto(j,{waitUntil:"domcontentloaded",timeout:Tt(d)})}catch(dt){throw At(dt)}await N.settle(d,Ro);let Y=0,K=!1;if(W&&O&&J&&nt)if(await Te(A,J,nt,d)==="session")K=!0,Y=O.loginSteps,D.push(...M.slice(0,Y).map(st=>({id:st.id,op:st.op,ok:!0,ms:0,skipped:"session"}))),u({type:"info:webActionsNodeRunner:session",content:{nodeId:e.id,mode:"reused"}});else{let st=crypto.randomUUID(),qt=await B(W.acquire(st,ho),d);if(!qt&&L===0){for(u({type:"info:webActionsNodeRunner:session",content:{nodeId:e.id,mode:"waiting"}});await B(W.busy(),d);)await new Promise(et=>setTimeout(et,Math.min(No,Tt(d))));await C();continue}try{u({type:"info:webActionsNodeRunner:session",content:{nodeId:e.id,mode:"login"}});let et=await B(xt(A,M.slice(0,O.loginSteps),Bt(N,0)),d);if(D.push(...et.steps),et.error)throw F(et.steps),new Error(et.error);await Jt(R)}finally{qt&&await B(W.release(st),Date.now()+3e3).catch(()=>{})}Y=O.loginSteps}let S=await B(xt(A,M.slice(Y),Bt(N,Y)),d);if(D.push(...S.steps),Object.assign(I,S.extracted),S.error){if(F(S.steps))throw new Error(S.error);if(W&&K&&L===0&&J&&await Re(A,J,d)){u({type:"info:webActionsNodeRunner:session",content:{nodeId:e.id,mode:"invalidated"}}),await B(W.invalidate(),d).catch(()=>{}),await C();continue}throw new Error(S.error)}await Jt(R),g={ok:!0,error:null,data:{url:A.url(),title:await B(A.title(),d),extracted:I,steps:D}};break}}catch($){let _=$ instanceof Error?$.message:String($);g={ok:!1,error:_,data:A?await B(Ao(A,I,D,d),d).catch(()=>({url:"",title:"",extracted:I,steps:D})):null},u({type:"error:webActionsNodeRunner",content:`WebActions node execution failed: ${_}`})}finally{if(N==null||N.dispose(),y)try{await B(y.close(),Date.now()+3e3)}catch{}let $=Date.now()-s;c&&(m=we(c,l())),f==null||f({type:"tool_call",payload:{nodeId:e.id,url:`webActions:${m}`,method:"EXECUTE",status:g.ok?200:502,latencyMs:$}});let _=me(at(g.data,l()));u({type:"info:webActionsNodeRunner:response",content:{nodeId:e.id,ok:g.ok,latencyMs:$,data:_.value,truncated:_.truncated,error:g.error}}),u({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:g.ok?"success":"error",error:g.error??void 0}}),g.error=at(g.error,l()),g.data&&(g.data.steps=g.data.steps.map(V=>V.error===void 0?V:{...V,error:at(V.error,l())})),n==null||n(e.id,g)}}async function Ao(o,e,i,t){let n="",h="";try{n=o.url()}catch{}try{h=await B(o.title(),t)}catch{}return{url:n,title:h,extracted:e,steps:i}}function ze(){let o={};return{add(e,i){o[e]=i},hasOutputs(){return Object.keys(o).length>0},answerNodeIds(){return Object.keys(o)},snapshotData(){let e=Object.entries(o);return e.length===1?e[0][1]:Object.fromEntries(e)}}}function xo(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function Ii(o,e){if(!xo(o))throw new Error("Structured outputs require HX_ORA_URL and HX_API_KEY");let i=await fetch(`${o.HX_ORA_URL}/internal/outputs/${encodeURIComponent(e.flowId)}/${encodeURIComponent(e.sessionId)}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:o.HX_API_KEY},body:JSON.stringify({runId:e.runId,createdAt:e.createdAt,data:e.data,answerNodeIds:e.answerNodeIds})});if(!i.ok){let t=await i.text().catch(()=>"");throw new Error(`Structured output persistence failed with ${i.status}${t?`: ${t}`:""}`)}}var Ge=3,Ye=10,ko=new Set(["agent:start","agent:complete","agent:telemetry"]);function Oo(o){let e=o.executedNodes||[];return e.length===0?"(none)":e.map(i=>i.label?`${i.id} (${i.label})`:i.id).join(" \u2192 ")}function _o(o){let e=o.executedNodes||[];return e[e.length-1]}function Q(o,e,i){throw o==null||o({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:i.message}}),i}function Io(o,e){var h,f,s,d,a,p,w;let i=Array.isArray((h=o.data)==null?void 0:h.inputs)?o.data.inputs:[],t=((s=(f=e.flowData)==null?void 0:f.state)==null?void 0:s.nodes)||[],n={};for(let l of i){let u=(d=l.key)==null?void 0:d.trim();if(!u)continue;let r=(a=l.from)==null?void 0:a.trim();if(!r){if(l.default===void 0)continue;n[u]=l.default;continue}let g=z(r,{context:e.context||{},results:e.results||{},nodes:t,edges:((w=(p=e.flowData)==null?void 0:p.state)==null?void 0:w.edges)??[],currentNodeId:o.id}),m=g.value;if(g.missing||m===void 0||m===null){if(l.default===void 0)throw new q(g.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Worker node ${o.id} could not resolve input "${r}"`);m=l.default}n[u]=m}return n}async function Mt(o,e,i,t,n,h,f){var U,x,T,b,P,$;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let s=typeof((U=e.data)==null?void 0:U.flowId)=="string"?e.data.flowId.trim():"";s||Q(t,e,new Error(`Worker node ${e.id} is missing flowId`));let d=(x=i.flowData)==null?void 0:x.flowId,a=o.workerStack??(d?[d]:[]);a.includes(s)&&Q(t,e,new Error(`Worker node ${e.id} cannot call ${s}: cycle detected (${[...a,s].join(" \u2192 ")})`)),a.length>=Ge&&Q(t,e,new Error(`Worker node ${e.id} exceeded max nesting depth (${Ge})`));let p=o.workerCalls??{count:0};o.workerCalls=p,p.count>=Ye&&Q(t,e,new Error(`Worker node ${e.id} exceeded max worker calls per run (${Ye})`)),p.count+=1;let w;try{w=Io(e,i)}catch(_){Q(t,e,_ instanceof Error?_:new Error(String(_)));return}let l=o.env;l||Q(t,e,new Error(`Worker node ${e.id} is missing runtime env`));let u,r;try{let _=await Xt(s,l);r=(T=_==null?void 0:_.metadata)==null?void 0:T.tenant,u=await Kt(s,l)}catch(_){Q(t,e,new Error(`Worker node ${e.id} could not load worker ${s}: ${_ instanceof Error?_.message:String(_)}`))}let g=(b=i.flowData)==null?void 0:b.tenant;(!r||r!==g)&&Q(t,e,new Error(`Worker ${s} belongs to a different tenant`));let m=ze(),c={flowData:{...u,tenant:r,flowId:s,chatId:((P=i.flowData)==null?void 0:P.chatId)||""},executedNodes:[],context:{},results:{}},y={env:l,ctx:o.ctx,secrets:o.secrets,userAuth:o.userAuth,user:o.user,toolDefs:o.toolDefs,composioSessions:o.composioSessions,skillRefCache:o.skillRefCache,publicOrigin:o.publicOrigin,getOraModel:o.getOraModel,runId:o.runId,shouldStop:o.shouldStop,workerCalls:p,conn:void 0,getMessages:async()=>[],setMessages:async()=>{},agentMemory:"",outputCollector:m,workerStack:[...a,s]},R,N={onChangeState:()=>{},onServerEvent:_=>{var V;ko.has(_.type)||t==null||t({type:"worker:node",content:{workerNodeId:e.id,childNodeId:(V=_.content)==null?void 0:V.nodeId,event:_}})},onTelemetry:_=>f==null?void 0:f(_),onError:_=>{R=_},shouldStop:o.shouldStop},{startEngine:A,FlowExecutionStoppedError:C}=await import("./FlowEngine-JDCHJG3W.js"),I=await A(y,c,N)({text:"",inputs:w});if((I.status==="stopped"||await(($=o.shouldStop)==null?void 0:$.call(o)))&&Q(t,e,new C),I.status!=="completed"){let _=_o(c),V=Oo(c),j=I.error||R||"unknown error",M=_?` at node ${_.label?`${_.id} (${_.label})`:_.id}`:"";Q(t,e,new Error(`Worker ${s} failed${M}: ${j}. Path: ${V}`))}m.hasOutputs()||Q(t,e,new Error(`El worker ${s} complet\xF3 sin output estructurado. Agreg\xE1 un mapeo de salida en su nodo Answer.`));let D=(c.executedNodes||[]).map(_=>_.id);n==null||n(e.id,{ok:!0,data:m.snapshotData(),error:null,executed:D}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}async function jt(o,e,i,t,n,h,f){var a,p,w,l,u,r,g,m;let s=Date.now(),d=(c,y={})=>t==null?void 0:t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:c,...y}});d("start");try{let c=e.data,y={context:i.context??{},results:i.results??{},nodes:((p=(a=i.flowData)==null?void 0:a.state)==null?void 0:p.nodes)??[],edges:((l=(w=i.flowData)==null?void 0:w.state)==null?void 0:l.edges)??[],currentNodeId:e.id},R=b=>{let P=y.nodes.find(V=>b.startsWith(`${V.id}.`)),$=P&&St(P).find(V=>V.name===b.slice(P.id.length+1).split(".")[0]);if(b==="images"||($==null?void 0:$.type)==="image")throw new Error("Classifier accepts text context only");let _=z(b,y);if(_.missing||_.value===void 0||_.value===null)throw new Error(`Classifier input "${b}" did not produce a value`);return _.value},N=R(c.input.message);if(typeof N!="string")throw new Error("Classifier message must be text");let A=c.input.historyTurns>0&&o.getMessages?Ie(await o.getMessages(),c.input.historyTurns,(u=i.context)==null?void 0:u.user_input):[],C=Object.fromEntries(c.input.vars.map(b=>[b,R(b)])),I=Ae(c,{message:N,history:A,vars:C});console.log(`[classifier] node ${e.id} model=${c.model} message=${N.length}ch history=${A.length} vars=${Object.keys(C).length} options=${c.options.length} checks=${c.checks.length} estTokens=${xe(I)}`);let D=kt(I);if(D&&console.warn(`[classifier] node ${e.id} ${D}`),D&&(t==null||t({type:"warning:classifier",content:{nodeId:e.id,message:D}})),!((r=o.env)!=null&&r.AI))throw new Error("Classifier requires AI binding");let U;try{U=await ke(o.env.AI,c.model,I)}finally{let b=kt(I);b&&b!==D&&console.warn(`[classifier] node ${e.id} ${b}`),b&&b!==D&&(t==null||t({type:"warning:classifier",content:{nodeId:e.id,message:b}}))}let{result:x,usage:T}=Oe(U,c);console.log(`[classifier] \u2713 node ${e.id} route=${x.route} class=${x.classification} confidence=${x.confidence} margin=${x.margin.toFixed(4)} tokens=${T.promptTokens} ${Date.now()-s}ms`),n==null||n(e.id,x),f==null||f({type:"decision_telemetry",payload:{nodeId:e.id,model:c.model,totalLatency:Date.now()-s,usage:T,route:x.route}}),d("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((b,P)=>P[1]-b[1]).slice(0,5)),checks:x.checks}})}catch(c){console.error(`[classifier] \u2717 node ${e.id} model=${(g=e.data)==null?void 0:g.model} ${Date.now()-s}ms: ${c instanceof Error?`${c.name}: ${c.message}`:String(c)}`),n==null||n(e.id,_e()),f==null||f({type:"decision_telemetry",payload:{nodeId:e.id,model:(m=e.data)==null?void 0:m.model,totalLatency:Date.now()-s,route:"error",usage:{promptTokens:0,completionTokens:0,totalTokens:0}}}),d("error",{error:c instanceof Error&&c.message==="Clef timeout"?"Clef timeout":"Classifier decision failed",route:"error"})}}import{stepCountIs as Vo,streamText as Ho}from"ai";import{nanoid as Bo}from"nanoid";import"zod";function Ze(o,e){var s,d,a,p,w;let i=((s=o.data)==null?void 0:s.attachments)??[];if(!Array.isArray(i))throw new q("INVALID_EXPRESSION",`Node ${o.id} attachments must be an array`);let t=((a=(d=e.flowData)==null?void 0:d.state)==null?void 0:a.nodes)??[],n=((w=(p=e.flowData)==null?void 0:p.state)==null?void 0:w.edges)??[],h=ot(t,n,o.id),f="";for(let l of i){if(typeof l!="string")throw new q("INVALID_EXPRESSION",`Node ${o.id} has an invalid attachment reference`);let u=h.find(g=>g.ref===l);if(!u)throw new q("OUT_OF_SCOPE",`Attachment "${l}" is not in this node's connection scope`);if(u.type!=="file"&&u.type!=="image")throw new q("UNKNOWN_OUTPUT",`Attachment "${l}" is not an image or file output`);if(u.type!=="file")continue;let r=z(l,{context:e.context??{},results:e.results??{},nodes:t,edges:n,currentNodeId:o.id});if(r.missing)throw new q(r.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${l}" did not produce a value`);if(typeof r.value!="string")throw new q("PATH_NOT_FOUND",`Attachment "${l}" must resolve to file text`);r.value.trim()&&(f+=(f?`
|
|
2
|
+
|
|
3
|
+
`:"")+r.value)}return f}function $o(o,e){var n,h,f,s,d;let i=((n=o.data)==null?void 0:n.attachments)??[];if(!Array.isArray(i))throw new q("INVALID_EXPRESSION",`Node ${o.id} attachments must be an array`);let t=ot(((f=(h=e.flowData)==null?void 0:h.state)==null?void 0:f.nodes)??[],((d=(s=e.flowData)==null?void 0:s.state)==null?void 0:d.edges)??[],o.id);return i.map(a=>{if(typeof a!="string")throw new q("INVALID_EXPRESSION",`Node ${o.id} has an invalid attachment reference`);let p=t.find(w=>w.ref===a);if(!p)throw new q("OUT_OF_SCOPE",`Attachment "${a}" is not in this node's connection scope`);if(p.type!=="image"&&p.type!=="file")throw new q("UNKNOWN_OUTPUT",`Attachment "${a}" is not a binary output`);return p.type==="image"?a:null}).filter(a=>a!==null)}function Qe(o,e){var n,h,f,s;let i=[],t={context:e.context??{},results:e.results??{},nodes:((h=(n=e.flowData)==null?void 0:n.state)==null?void 0:h.nodes)??[],edges:((s=(f=e.flowData)==null?void 0:f.state)==null?void 0:s.edges)??[],currentNodeId:o.id};for(let d of $o(o,e)){let a=z(d,t);if(a.missing)throw new q(a.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${d}" did not produce a value`);if(!Array.isArray(a.value))throw new q("PATH_NOT_FOUND",`Attachment "${d}" must resolve to an image array`);i.push(...a.value)}return i}var tt=(o,e,i)=>{o.send(e+"::"+i)};import{openai as bo}from"@ai-sdk/openai";import{extractReasoningMiddleware as Fo,wrapLanguageModel as Do}from"ai";import{createWorkersAI as Co}from"workers-ai-provider";import{xai as Po}from"@ai-sdk/xai";import{anthropic as Mo}from"@ai-sdk/anthropic";import{createOpenRouter as jo}from"@openrouter/ai-sdk-provider";var Ut={};function Wt(o){if(o!=null){if(typeof o!="string")return o;try{return JSON.parse(o)}catch{return}}}function Wo(o){return{...o,defaultParams:Wt(o.defaultParams)??o.defaultParams,capabilities:Wt(o.capabilities)??o.capabilities,price:Wt(o.price)??o.price}}async function Ee(o,e,i){var p,w;if(!(e!=null&&e.getOraModel))throw new Error("resolveModelById requires a sessionEnv with getOraModel capable of fetching models dynamically.");let t=await e.getOraModel(o);if(!t)return;let n=Wo(t),h=((p=n.capabilities)==null?void 0:p.params)??$e(n),{effectiveParams:f,adjustments:s}=Fe(n.defaultParams,i,h),d;if(Ut[n.provider])d=await Ut[n.provider](n,e,i);else if(n.provider==="openai")d=bo(n.providerModel);else if(n.provider==="xai")d=Po(n.providerModel);else if(n.provider==="anthropic")d=Mo(n.providerModel);else if(n.provider==="openrouter")d=jo()(n.providerModel);else if(n.provider==="workersai"||n.provider==="cloudflare"){if(!((w=e==null?void 0:e.env)!=null&&w.AI))throw new Error("Workers AI provider requires sessionEnv.env.AI binding");d=Co({binding:e.env.AI})(n.providerModel)}else d={provider:n.provider,providerModel:n.providerModel};let a=Ce(n);return a.kind==="tag"&&d&&typeof d=="object"&&"specificationVersion"in d&&(d=Do({model:d,middleware:Fo({tagName:a.tagName??"think",startWithReasoning:a.startWithReasoning??!1})})),{provider:n.provider,modelHandle:d,entry:n,effectiveParams:f,paramAdjustments:s.length>0?s:void 0,reasoning:a}}function tn(o,e){Ut[o]=e}var Uo=lt({"../tools/composioDirectTool.ts":()=>import("./composioDirectTool-ZCZRW5WU.js"),"../tools/composioTool.ts":()=>import("./composioTool-RKVCX25U.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-DIQRGKMU.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 Lo=lt({});async function Jo(o,e,i,t){var w;let n=Array.isArray((w=i==null?void 0:i.data)==null?void 0:w.tools)?i.data.tools:[];if(n.length===0)return{};let h={},f=l=>{var R,N;let u=typeof(l==null?void 0:l.description)=="string"?l.description:"",r=l==null?void 0:l.inputSchema,g;try{let A=(r==null?void 0:r.shape)??(typeof((R=r==null?void 0:r._def)==null?void 0:R.shape)=="function"?r._def.shape():(N=r==null?void 0:r._def)==null?void 0:N.shape);A&&typeof A=="object"&&(g=A)}catch{}let m=g?Object.keys(g):[],c=u?`description="${u.length>120?u.slice(0,120)+"\u2026":u}"`:"description=(none)",y=m.length?`inputSchema={${m.join(", ")}}`:"inputSchema=(none)";return`${c} ${y}`},s=(()=>{let l=[],u=[],r=[],g=[];for(let c=0;c<n.length;c++){let y=n[c];!y||typeof y!="object"||typeof y.id!="string"?g.push(c):y.kind==="builtin"?l.push(y.id):y.kind==="skill"?r.push(y.id):y.kind==="http"||y.kind==="mcp"||y.kind==="composio"?u.push(y.id):g.push(c)}let m=[];return l.length&&m.push(`builtin[${l.join(", ")}]`),u.length&&m.push(`custom[${u.join(", ")}]`),r.length&&m.push(`skill[${r.join(", ")}]`),g.length&&m.push(`invalid@[${g.join(", ")}]`),m.join(" ")||"(none)"})();console.log(`[tools] node ${i.id} requested (${n.length}): ${s}`);let d=!1,a=async()=>{if(d&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},d=!0,o.toolDefs;try{let l=await pt(o.env),u={};for(let r of l)r&&r.id&&(u[r.id]=r);o.toolDefs=u}catch(l){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(l)}`}),o.toolDefs=o.toolDefs||{}}return d=!0,o.toolDefs},p=[];for(let l=0;l<n.length;l++){let u=n[l];if(!u||typeof u!="object"||typeof u.id!="string"||u.kind!=="builtin"&&u.kind!=="http"&&u.kind!=="mcp"&&u.kind!=="composio"&&u.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${l}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let r=u;if(r.kind!=="builtin"){let m=(await a())[r.id];if(!m){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 y=await We(m,o,e,t),R=Object.keys(y);for(let[N,A]of Object.entries(y))h[N]=A;console.log(`[tools] \u2713 composio '${r.id}' \u2192 ${R.length} tool(s)`)}catch(y){console.error(`[tools] \u2717 composio '${r.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${r.id}': ${String(y)}`})}continue}if(r.kind==="skill"){if(m.kind!=="skill"){console.error(`[tools] \u2717 skill '${r.id}': row is of kind '${m.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${r.id}' is not a skill`});continue}let y=m.name;if(h[y]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${y}' \u2014 builtin/other already registered, skipping skill '${r.id}'`});continue}try{h[y]=Ue(m,o,e,t),p.push(m);let R=typeof m.execution=="string"?JSON.parse(m.execution):m.execution||{},N=Array.isArray(R.references)?R.references.map(A=>A==null?void 0:A.name):[];console.log(`[tools] \u2713 skill '${r.id}' \u2192 '${y}' (refs: ${N.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:y,refCount:N.length,refs:N}})}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 c=m.name;if(h[c]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${c}' \u2014 builtin already registered, skipping custom tool '${r.id}'`});continue}try{let y=ft(m,o,e,t);h[c]=y,console.log(`[tools] \u2713 custom '${r.id}' \u2192 '${c}'`),console.log(`[tools] ${f(h[c])}`)}catch(y){console.error(`[tools] \u2717 custom '${r.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${r.id}': ${String(y)}`})}continue}if(!ae[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 g;try{g=await Uo(`../tools/${r.id}.ts`)}catch{g=await Lo(`../tools/${r.id}.js`)}let m;if(g[r.id])m=g[r.id];else if(g.default)m=g.default;else if(g.create)m=g.create;else{let I=Object.values(g);I.length>0&&(m=I[0])}if(!m){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${r.id}'`});continue}let c,y,R={};if(r.params&&typeof r.params=="object"){if(typeof r.params.description=="string"?c=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 I=r.params.inputSchema;typeof I=="object"&&(typeof I.safeParse=="function"||I._def)?y=I:typeof I=="object"&&I!==null&&I.type==="object"&&I.properties?(y=fe(I),y||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 N=m(o,e,R,t);c&&N&&typeof N=="object"&&(N.description=c),y&&N&&typeof N=="object"&&(N.inputSchema=y),h[r.id]=N;let A=[];c&&A.push("description"),y&&A.push("inputSchema"),Object.keys(R).length&&A.push(`defaults(${Object.keys(R).join(",")})`);let C=A.length?` [overrides: ${A.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${r.id}'${C}`),console.log(`[tools] ${f(N)}`)}catch(g){console.error(`[tools] \u2717 builtin '${r.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${r.id}': ${String(g)}`});continue}}if(p.length>0)if(h.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{h.readSkillRef=Le(o,p,e,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${p.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:p.map(l=>l.name)}})}catch(l){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(l)}`)}return h}async function Lt(o,e,i,t,n,h,f){var I,D,U,x;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let s=!1;try{let T=(I=i.flowData)==null?void 0:I.state;if(T&&T.edges&&T.nodes){let b=T.edges.filter(P=>P.source===e.id);if(b.length>0){let P=T.nodes.find($=>$.id===b[0].target);P&&P.type==="answerNode"&&(s=!0)}}}catch(T){console.error("Error determining next node for streaming:",T)}let d=X(e.data.template,e,i,t,{sessionEnv:o});(!d||!d.trim())&&(d="Answer straight forward to the user, dont offer any other option to continue");let a=d,p=X(e.data.user_template||"",e,i,t,{sessionEnv:o}),w=T=>T&&Object.fromEntries(Object.keys(T).map(b=>[b,"[redacted]"])),l=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:w(o.secrets),userAuth:w(o.userAuth)}:o,u=X(e.data.template,e,i,void 0,{sessionEnv:l})||a,r=X(e.data.user_template||"",e,i,void 0,{sessionEnv:l});t==null||t({type:`info:llmNodeRunner:${e.id}`,content:u}),t==null||t({type:`info:llmNodeRunner:${e.id}`,content:r});let g=(D=e==null?void 0:e.data)==null?void 0:D.window_size,m=Number(g);(!Number.isInteger(m)||m<=0)&&(m=5);let c=Qe(e,i),y=Ze(e,i);t==null||t({type:"info:llmNodeRunner:attachments",content:{nodeId:e.id,refs:Array.isArray((U=e.data)==null?void 0:U.attachments)?e.data.attachments:[],images:c.length,documents:y?1:0}});let N=(await((x=o.getMessages)==null?void 0:x.call(o))??[]).slice(-m),A=N.filter(T=>T&&typeof T.role=="string"&&typeof T.content=="string");A.length!==N.length&&console.warn(`Filtered ${N.length-A.length} invalid messages from history`);let C=Xo(A,p,c,y);await qo(d,C,o.conn,t,e,s,n,i,h,o,f)}async function qo(o,e,i,t,n,h,f,s,d,a,p){var l;let w=Date.now();if(!((l=a.env)!=null&&l.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(u,r)=>{var b,P,$,_,V,j;let g,m={},c,y="none",R=!1,N,A=!1,C=!1,I=0,D=0,U=(b=n==null?void 0:n.data)==null?void 0:b.sendReasoning,x=U!==!1;try{let M=(P=n==null?void 0:n.data)==null?void 0:P.model,G=Array.isArray(M)?M[0]:M||"gpt_5_nano",k=be(n==null?void 0:n.data),F=await Ee(G,a,k);if(!F)throw new Error(`Model '${G}' not found in registry`);g=F.modelHandle,m=F.effectiveParams||{},y=F.reasoning.kind;let O=Me(F.reasoning,($=n==null?void 0:n.data)==null?void 0:$.reasoningEffort);R=x&&Pe(F.reasoning);let W=typeof((_=n==null?void 0:n.data)==null?void 0:_.reasoningMaxTokens)=="number"?n.data.reasoningMaxTokens:void 0;c=je(F.provider,{effort:O,exposeReasoning:R,maxTokens:W}),O&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:O})),console.log(`[reasoning] ${JSON.stringify({model:G,provider:F.provider,capability:F.reasoning,requestedEffort:((V=n==null?void 0:n.data)==null?void 0:V.reasoningEffort)??null,resolvedEffort:O??null,sendReasoning:x,exposeReasoning:R,providerOptions:c??null},null,2)}`);for(let J of F.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:J});t==null||t({type:"info:llmNodeRunner:model",content:G}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(j=n==null?void 0:n.data)!=null&&j.generationPreset?{preset:n.data.generationPreset}:{},...m,...y!=="none"?{reasoning:y,configuredSendReasoning:U,sendReasoning:x,exposeReasoning:R,...O?{effort:O}:{}}:{}}})}catch(M){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(M)}`}),M}let T=await Jo(a,s,n,t);console.log(`[tools] node ${n.id} loaded ${Object.keys(T).length}: ${Object.keys(T).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:n.id,tools:Object.keys(T)}});try{let M=Ho({model:g,system:o,messages:e,stopWhen:(()=>{var J;let F=!!T.readSkillRef?10:5,O=Number(((J=n.data)==null?void 0:J.max_steps)??F),W=Number.isFinite(O)?Math.max(1,Math.min(30,O)):F;return Vo(W)})(),...De(m),...c?{providerOptions:c}:{},tools:T,onFinish:async k=>{var ct,rt;let F=k.text||"",O=k.reasoningText??((ct=k.reasoning)==null?void 0:ct.text)??"";if(console.log(`[reasoning] done: deltas=${I} chars=${D} result.reasoningText=${O.length} finishReason=${k.finishReason??"n/a"} reasoningTokens=${((rt=k.usage)==null?void 0:rt.reasoningTokens)??"n/a"}`),x&&R&&!A&&O&&i){A=!0;try{tt(i,v.SERVER_REASONING_STREAM,O)}catch(yt){console.warn("Failed to send finished reasoning over connection",yt)}}let W={id:Bo(),role:"assistant",type:"text",content:F,ts:Date.now()};h&&(a.setMessages?await a.setMessages(W):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),i&&x&&A&&!C&&(C=!0,tt(i,v.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),h&&i&&tt(i,v.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),f==null||f((n==null?void 0:n.id)||"llm_result",F),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(k)});let J=Date.now()-w,nt=N?N-w:void 0;p==null||p({type:"llm_telemetry",payload:{nodeId:n.id,totalLatency:J,timeToFirstToken:nt,model:k.response.modelId,usage:k.usage}}),p==null||p({type:"llm_result",payload:{result:k}})},onStepFinish:async k=>{let F=(O,W=200)=>{let J=typeof O=="string"?O:JSON.stringify(O);return J?J.length>W?`${J.slice(0,W)}\u2026(+${J.length-W})`:J:""};if(k.toolCalls&&k.toolCalls.length>0){for(let O of k.toolCalls)console.log(`[tools] \u2192 ${O.toolName}(${F(O.args??O.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${n.id}`,content:JSON.stringify(k.toolCalls)})}if(k.toolResults&&k.toolResults.length>0){for(let O of k.toolResults)console.log(`[tools] \u2190 ${O.toolName} \u2192 ${F(O.result??O.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${n.id}`,content:JSON.stringify(k.toolResults)})}},experimental_onToolCallStart:k=>{var F;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(F=k==null?void 0:k.toolCall)==null?void 0:F.toolName,status:"start"}})},experimental_onToolCallFinish:k=>{var F,O;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(F=k==null?void 0:k.toolCall)==null?void 0:F.toolName,status:((O=k==null?void 0:k.toolOutput)==null?void 0:O.type)==="tool-error"?"error":"success"}})},onError:k=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),r(k)},onChunk:k=>{if(k.chunk.type==="reasoning-delta"){let O=k.chunk.text??k.chunk.delta??"";if(O&&(A=!0,I+=1,D+=O.length,I===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),x&&i&&O)try{tt(i,v.SERVER_REASONING_STREAM,O)}catch(W){console.warn("Failed to send reasoning chunk over connection",W)}return}if(k.chunk.type==="text-delta"){if(N||(N=Date.now()),i&&x&&A&&!C){C=!0;try{tt(i,v.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to send reasoning complete over connection",O)}}return}p==null||p({type:k.chunk.type,payload:{nodeId:n.id,chunk:k.chunk}});let F=`llm_chunk:${k.chunk.type}`;t==null||t({type:F,content:{...k}})}}),G=async()=>{let k="";for await(let F of M.fullStream)if(F.type==="text-delta"){if(k+=F.text,h&&i)try{tt(i,v.SERVER_TEXT_STREAM,F.text)}catch(O){console.warn("Failed to send chunk over connection",O)}}else if(F.type==="finish-step"&&F.finishReason==="tool-calls"){if(h&&i&&k.trim())try{tt(i,v.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to flush text segment over connection",O)}k=""}};await Promise.all([M,G()]),u(),t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"success"}})}catch(M){t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"error",error:String(M)}}),r(M)}})}function Xo(o,e,i,t){let n=!!(i&&i.length>0),h=!!t,f=n||h,d=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,a=p=>{let w=[],l="";if(h&&(l+=`[Attached files]
|
|
4
|
+
${t}
|
|
5
|
+
[End of attached files]
|
|
6
|
+
|
|
7
|
+
`),p&&(l+=p),l&&w.push({type:"text",text:l}),n)for(let u of i)w.push({type:"image",image:u.data,mimeType:u.mimeType});return w};return e&&d&&d.content===e?[...o.slice(0,-1).map(w=>({role:w.role,content:w.content})),{role:"user",content:a(e)}]:e?[...o.map(p=>({role:p.role,content:p.content})),{role:"user",content:a(e)}]:f&&d?[...o.slice(0,-1).map(w=>({role:w.role,content:w.content})),{role:"user",content:a(d.content)}]:o.map(p=>({role:p.role,content:p.content}))}async function Vt(o,e,i,t,n,h,f){var p,w,l,u,r,g,m;console.log(`**** MEMO Node id: ${e.id} ****`),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let s="",d=!1,a=Date.now();try{t==null||t({type:"info:memoNodeRunner",content:"Starting memo node execution"});let c=String(((p=e.data)==null?void 0:p.query_key)||"user_input"),y=z(c,{context:i.context??{},results:i.results??{},nodes:((l=(w=i.flowData)==null?void 0:w.state)==null?void 0:l.nodes)??[],edges:((r=(u=i.flowData)==null?void 0:u.state)==null?void 0:r.edges)??[],currentNodeId:e.id});if(y.missing)throw new Error(`Memo query "${c}" did not produce a value`);if(!o.env||!o.ctx){t==null||t({type:"error:memoNodeRunner",content:"Missing env or ctx"}),n==null||n(e.id,s);return}if(!e.data.rag_id){t==null||t({type:"error:memoNodeRunner",content:"Missing rag_id"}),n==null||n(e.id,s);return}let R=String(y.value??"");t==null||t({type:"info:memoNodeRunner",content:`Query text: ${R}`}),t==null||t({type:"info:memoNodeRunner",content:"Generating embedding for query"});let N=await zt(o,R,!0);t==null||t({type:"info:memoNodeRunner",content:`Embedding generated successfully, length: ${N.data[0].length}`});let A=Array.isArray(e.data.rag_id)?e.data.rag_id:[e.data.rag_id],C=[];for(let x of A){t==null||t({type:"info:memoNodeRunner",content:`Executing RAG query with namespace: ${x}`});let T=await o.env[`VDB_${(g=i.flowData)==null?void 0:g.tenant}_1024`].query(N.data[0],{namespace:x,topK:e.data.topk,returnMetadata:"all"});t==null||t({type:"info:memoNodeRunner",content:`RAG query completed for namespace ${x}, matches: ${((m=T.matches)==null?void 0:m.length)||0}`}),Array.isArray(T.matches)&&C.push(...T.matches)}let I=Date.now()-a;s=C.map(x=>{var T;return(T=x.metadata)==null?void 0:T.value}).filter(x=>typeof x=="string").join(`
|
|
8
|
+
|
|
9
|
+
`),f==null||f({type:"memo_search",payload:{nodeId:e.id,searchLatencyMs:I,retrievedContext:s}}),t==null||t({type:"info:memoNodeRunner",content:`Context retrieval complete, length: ${s.length}, preview: ${s.substring(0,200)}...`}),t==null||t({type:"info:memoNodeRunner",content:"Memo node execution completed successfully"}),d=!0}catch(c){throw console.error("Error processing MemoNode:",c),t==null||t({type:"error:memoNodeRunner",content:`Memo node execution failed: ${c}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(c)}}),c}finally{d&&(n==null||n(e.id,s),t==null||t({type:"info:memoNodeRunner",content:`onResult called with context length: ${s.length}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}}))}}async function Ht(o,e,i,t,n,h,f){var p,w,l,u,r,g,m,c;console.log(`**** START Node ${e.id} ****`),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}}),t==null||t({type:"info:flow",content:i}),f==null||f({type:"start_node",payload:{userMessage:(p=i==null?void 0:i.context)==null?void 0:p.user_input}});let s=((w=e.data)==null?void 0:w.allow_images)!==!1,d=((l=e.data)==null?void 0:l.allow_documents)!==!1;!s&&(i!=null&&i.context)&&(i.context.user_images=[],h==null||h({...i})),!d&&(i!=null&&i.context)&&(i.context.files="",h==null||h({...i}));let a={};for(let y of ut(e.data))a[y.name]=(u=i==null?void 0:i.context)==null?void 0:u[y.name];n==null||n(e.id,{...a,user_input:(r=i==null?void 0:i.context)==null?void 0:r.user_input,images:s?(g=i==null?void 0:i.context)==null?void 0:g.user_images:[],files:d?(m=i==null?void 0:i.context)==null?void 0:m.files:"",memory:((c=i==null?void 0:i.context)==null?void 0:c.memory)??""}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}function Sn(o,e,i){let t=e;async function n(){var a;if(await((a=i==null?void 0:i.shouldStop)==null?void 0:a.call(i)))throw new gt}async function h(a){let p=a;for(t.executedNodes=t.executedNodes||[],t.context=t.context||{},t.results=t.results||{};p&&p.id;)await n(),await f(p),await n(),p=zo(p,t.flowData,t)}async function f(a){var r,g;let p=d[a.type];if(!p){(r=i==null?void 0:i.onError)==null||r.call(i,`Unknown node type: ${a.type}`);return}t.executedNodes=t.executedNodes||[],t.executedNodes.push({id:a.id,type:a.type,label:typeof((g=a.data)==null?void 0:g.label)=="string"?a.data.label:void 0}),t.lastNodeId=a.id;let w=m=>{var c;return(c=i==null?void 0:i.onServerEvent)==null?void 0:c.call(i,{...m,ts:Date.now()})},l=m=>{var c,y;if((c=i==null?void 0:i.onTelemetry)==null||c.call(i,m),m.type==="llm_telemetry"||m.type==="decision_telemetry"||m.type==="memory_update"){let R=(y=m.payload)==null?void 0:y.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 p(o,a,t,w,(m,c)=>{t.results[m]=c},i==null?void 0:i.onChangeState,l)}let s=async a=>{var u,r,g,m,c,y,R;let p=Date.now(),w="completed",l;try{await n();let N=typeof a=="string"?Yt(a):a,A=(N==null?void 0:N.text)||"",C=(N==null?void 0:N.images)||[],I=(N==null?void 0:N.documents)||[],D=await Ve(I,o.env),U=D.length>0?D.map(b=>`--- file: ${b.name} ---
|
|
10
|
+
${b.text}`).join(`
|
|
11
|
+
|
|
12
|
+
`):"";t.context={user_input:A,user_images:C,files:U},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},t.executedNodes=[],(u=i==null?void 0:i.onServerEvent)==null||u.call(i,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:x,error:T}=Ko(t.flowData);if(!x)w="failed",l=T||"Flow Format Error",(r=i==null?void 0:i.onError)==null||r.call(i,l);else{let b=ut(x.data),{values:P,errors:$}=Gt(b,N==null?void 0:N.inputs);if($.length>0)return w="failed",l=`Invalid flow inputs: ${$.join("; ")}`,(g=i==null?void 0:i.onError)==null||g.call(i,l),{status:w,error:l};if(t.context={...t.context,inputs:P,...P},t.context.user_input||(t.context.user_input=A),ne(x.data)){let _=oe(re(x.data));t.context.memory=ie(o.agentMemory||"",_).content}else t.context.memory="";await h(x),(m=i==null?void 0:i.onServerEvent)==null||m.call(i,{type:"agent:telemetry",content:{durationMs:Date.now()-p,tokenUsage:t.tokenUsage},timestamp:Date.now()})}}catch(N){N instanceof gt?(w="stopped",l=N.message,(c=i==null?void 0:i.onServerEvent)==null||c.call(i,{type:"agent:stopped",content:l,timestamp:Date.now()})):(w="failed",l=N instanceof Error?N.message:"Agent execution failed",(y=i==null?void 0:i.onError)==null||y.call(i,l))}finally{(R=i==null?void 0:i.onServerEvent)==null||R.call(i,{type:"agent:complete",content:{status:w,durationMs:Date.now()-p},timestamp:Date.now()})}return{status:w,error:l}},d={startNode:Ht,classifierNode:jt,llmNode:Lt,memoNode:Vt,answerNode:Ot,apiNode:$t,toolNode:Dt,workerNode:Mt,crawlNode:Ct,webActionsNode:Pt};return s}var gt=class extends Error{constructor(){super("Stopped by user"),this.name="FlowExecutionStoppedError"}};function Ko(o){let e=(o==null?void 0:o.state)??o,i=se(e);return i.length?{error:i[0].message}:{startNode:e.nodes.find(t=>t.type==="startNode")}}function Se(o,e){var i;return((i=o.state)==null?void 0:i.nodes.find(t=>t.id===e))||null}function zo(o,e,i){var h;let t=e==null?void 0:e.state;if(!t)return null;let n=t.edges.filter(f=>f.source===o.id);if(o.type==="classifierNode"){let f=(h=i==null?void 0:i.results)==null?void 0:h[o.id];if(!f||!["class","uncertain","blocked","error"].includes(f.route))throw new Error(`Classifier ${o.id}: missing decision result`);let s=f.route,d=w=>n.find(l=>l.sourceHandle===wt(w,f.classification)),a=d(s);if(!a&&s==="blocked"&&(s=f.confidence<o.data.confidence.threshold||f.margin<o.data.confidence.margin?"uncertain":"class",a=d(s)),!a&&s==="uncertain"&&(s="class",a=d(s)),!a)throw new Error(`Classifier ${o.id}: no connected edge for ${wt(s,f.classification)}`);let p=Se(e,a.target);if(!p)throw new Error(`Classifier ${o.id}: edge target ${a.target} does not exist`);return p}return n.length===0?null:Se(e,n[0].target)}export{tt as a,eo as b,ze as c,Ii as d,Wo as e,Ee as f,tn as g,Sn as h,gt as i};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{A as $e,a as Ze,b as Ye,g as Xe,h as Qe,k as et,o as tt,s as nt,w as rt,y as ye}from"./chunk-LUS5CJY2.js";var no={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 oo(e){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t}catch{}return{text:e}}var an=256;function io(e){if(typeof e!="string")return null;let t=e.trim();return t?t.slice(0,an):null}function so(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 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}},F={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}},ot={uncertain:"source-__uncertain",blocked:"source-__blocked",error:"source-__error"};function it(e,t){return e==="class"&&t!==void 0?`source-${t}`:Object.hasOwn(ot,e)?ot[e]:`source-${e}`}var dt={enum:["startNode","classifierNode","memoNode","llmNode","answerNode","apiNode","toolNode","workerNode","crawlNode","webActionsNode"]},dn={type:"string",pattern:"^[A-Za-z0-9_-]{1,128}$"},ut={type:"object",additionalProperties:!1,required:["x","y"],properties:{x:{type:"number"},y:{type:"number"}}},un={type:"object",additionalProperties:!1,required:["id","type","position","data"],properties:{id:{$ref:"#/$defs/nodeId"},type:{$ref:"#/$defs/nodeType"},position:{$ref:"#/$defs/position"},data:{type:"object",maxProperties:100}}},cn={type:"object",additionalProperties:!1,required:["source","target"],properties:{id:{type:"string",minLength:1,maxLength:300},source:{$ref:"#/$defs/nodeId"},target:{$ref:"#/$defs/nodeId"},sourceHandle:{type:["string","null"],pattern:"^source-[A-Za-z0-9_.-]{1,100}$"}}},ln={type:"object",additionalProperties:!1,required:["schemaVersion","nodes","edges"],properties:{schemaVersion:{const:3},nodes:{type:"array",maxItems:200,items:{$ref:"#/$defs/node"}},edges:{type:"array",maxItems:400,items:{$ref:"#/$defs/edge"}}}},fn={nodeType:dt,nodeId:dn,position:ut,node:un,edge:cn,graph:ln},pn={$schema:"https://json-schema.org/draft/2020-12/schema",$defs:fn,$ref:"#/$defs/graph"},mn={type:"string",pattern:"^[A-Za-z0-9_-]{1,128}$"},gn={type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,63}$"},hn={type:"string",pattern:"^(source-)?[A-Za-z0-9_.-]{1,100}$"},yn={type:"object",maxProperties:100},st={type:"object",additionalProperties:!1,required:["node"],properties:{node:{$ref:"#/$defs/existingId"},handle:{$ref:"#/$defs/handle"}}},at={type:"object",additionalProperties:!1,required:["flowId","baseVersion","ops"],properties:{flowId:{type:"string",pattern:"^[A-Za-z0-9_-]{1,128}$"},baseVersion:{type:"integer",minimum:0},ops:{type:"array",minItems:1,maxItems:50,items:{$ref:"#/$defs/op"}},dryRun:{type:"boolean"},acknowledgeInlineCredentials:{type:"boolean"},returnGraph:{type:"boolean"}},$defs:{nodeType:dt,existingId:mn,newId:gn,handle:hn,position:ut,data:yn,op:{oneOf:[{type:"object",additionalProperties:!1,required:["op","type"],properties:{op:{const:"add_node"},type:{$ref:"#/$defs/nodeType"},id:{$ref:"#/$defs/newId"},data:{$ref:"#/$defs/data"},position:{$ref:"#/$defs/position"},from:st,to:st}},{type:"object",additionalProperties:!1,required:["op","type","between"],properties:{op:{const:"insert_node"},type:{enum:["memoNode","llmNode","apiNode","toolNode","workerNode","crawlNode","webActionsNode"]},id:{$ref:"#/$defs/newId"},data:{$ref:"#/$defs/data"},between:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{$ref:"#/$defs/existingId"},to:{$ref:"#/$defs/existingId"},handle:{$ref:"#/$defs/handle"}}}}},{type:"object",additionalProperties:!1,required:["op","id","data"],properties:{op:{const:"update_node"},id:{$ref:"#/$defs/existingId"},data:{$ref:"#/$defs/data"}}},{type:"object",additionalProperties:!1,required:["op","id","newId"],properties:{op:{const:"rename_node"},id:{$ref:"#/$defs/existingId"},newId:{$ref:"#/$defs/newId"}}},{type:"object",additionalProperties:!1,required:["op","id"],properties:{op:{const:"remove_node"},id:{$ref:"#/$defs/existingId"},reconnect:{type:"boolean"}}},{type:"object",additionalProperties:!1,required:["op","from","to"],properties:{op:{const:"connect"},from:{$ref:"#/$defs/existingId"},to:{$ref:"#/$defs/existingId"},handle:{$ref:"#/$defs/handle"},replace:{type:"boolean"}}},{type:"object",additionalProperties:!1,required:["op","from"],properties:{op:{const:"disconnect"},from:{$ref:"#/$defs/existingId"},to:{$ref:"#/$defs/existingId"},handle:{$ref:"#/$defs/handle"}}},{type:"object",additionalProperties:!1,required:["op","id","position"],properties:{op:{const:"move_node"},id:{$ref:"#/$defs/existingId"},position:{$ref:"#/$defs/position"}}}]}}};function ce(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bn(e,t){return(Array.isArray(e)?e:[e]).some(r=>r==="null"?t===null:r==="string"?typeof t=="string":r==="boolean"?typeof t=="boolean":r==="integer"?typeof t=="number"&&Number.isInteger(t):r==="number"?typeof t=="number"&&Number.isFinite(t):r==="array"?Array.isArray(t):r==="object"?ce(t):!1)}function wn(e,t){if(!t.startsWith("#/"))return;let n=e;for(let r of t.slice(2).split("/")){let o=r.replace(/~1/g,"/").replace(/~0/g,"~");if(!ce(n)||!Object.prototype.hasOwnProperty.call(n,o))return;n=n[o]}return n}function ct(e,t,n=e){let r=[];return K(e,t,"",n,r,0),r}function K(e,t,n,r,o,i){if(i>48){o.push(`${n||"/"}: schema too deep`);return}let s=e;if(typeof s.$ref=="string"){let a=wn(r,s.$ref);if(!ce(a)){o.push(`${n||"/"}: unresolved ${s.$ref}`);return}K(a,t,n,r,o,i+1);return}if(s.not){let a=[];K(s.not,t,n,r,a,i+1),a.length===0&&o.push(`${n||"/"}: not`)}if(s.oneOf){let a=s.oneOf.filter(u=>{let d=[];return K(u,t,n,r,d,i+1),d.length===0}).length;a!==1&&o.push(`${n||"/"}: oneOf matched ${a}`)}if(s.anyOf&&(s.anyOf.some(u=>{let d=[];return K(u,t,n,r,d,i+1),d.length===0})||o.push(`${n||"/"}: anyOf`)),s.enum&&!s.enum.some(a=>Object.is(a,t))&&o.push(`${n||"/"}: enum`),"const"in s&&s.const!==void 0&&!Object.is(s.const,t)&&o.push(`${n||"/"}: const`),s.type!==void 0&&!bn(s.type,t)){o.push(`${n||"/"}: type`);return}if(typeof t=="string"&&(s.minLength!==void 0&&t.length<s.minLength&&o.push(`${n||"/"}: minLength`),s.maxLength!==void 0&&t.length>s.maxLength&&o.push(`${n||"/"}: maxLength`),s.pattern!==void 0&&!new RegExp(s.pattern).test(t)&&o.push(`${n||"/"}: pattern`)),typeof t=="number"&&(s.minimum!==void 0&&t<s.minimum&&o.push(`${n||"/"}: minimum`),s.maximum!==void 0&&t>s.maximum&&o.push(`${n||"/"}: maximum`)),Array.isArray(t)&&(s.minItems!==void 0&&t.length<s.minItems&&o.push(`${n||"/"}: minItems`),s.maxItems!==void 0&&t.length>s.maxItems&&o.push(`${n||"/"}: maxItems`),s.items&&t.forEach((a,u)=>K(s.items,a,`${n}/${u}`,r,o,i+1))),ce(t)){let a=s.properties??{},u=Object.keys(t);s.maxProperties!==void 0&&u.length>s.maxProperties&&o.push(`${n||"/"}: maxProperties`);for(let d of s.required??[])Object.prototype.hasOwnProperty.call(t,d)||o.push(`${n||"/"}: required ${d}`);for(let[d,c]of Object.entries(s.dependentRequired??{}))if(Object.prototype.hasOwnProperty.call(t,d))for(let l of c)Object.prototype.hasOwnProperty.call(t,l)||o.push(`${n||"/"}: dependentRequired ${l}`);if(s.additionalProperties===!1)for(let d of u)Object.prototype.hasOwnProperty.call(a,d)||o.push(`${n||"/"}: additionalProperty ${d}`);for(let d of u){let c=a[d];c?K(c,t[d],`${n}/${d}`,r,o,i+1):ce(s.additionalProperties)&&K(s.additionalProperties,t[d],`${n}/${d}`,r,o,i+1)}}}function _n(){let e=at.properties.ops;return{$defs:at.$defs,type:e.type,minItems:e.minItems,maxItems:e.maxItems,items:e.items}}function lt(e,t,n){return e.map(r=>{let o=r.match(/^\/(\d+)(?:\/(.*))?:/),i=n&&o?Number(o[1]):void 0,s=o?o[2]??"":r.replace(/:.*$/,"").replace(/^\//,"");return{code:t,severity:"error",message:r,...s?{field:s}:{},...i!==void 0?{op:i}:{}}})}function co(e){let t=ct(pn,e);if(t.length)return{ok:!1,issues:lt(t,"field_type",!1)};let n=structuredClone(e);return n.edges=n.edges.map(r=>({...r,id:r.id||`xy-edge__${r.source}${r.sourceHandle??""}-${r.target}`})),{ok:!0,graph:n}}function lo(e){let t=ct(_n(),e);return t.length?{ok:!1,issues:lt(t,"op_invalid",!0)}:{ok:!0,ops:structuredClone(e)}}var S={source:"all",limit:5,depth:2,render:!1,format:"markdown",includeSubdomains:!1,waitTimeoutMs:6e4,maxAgeS:86400,maxCharsPerPage:4e3},z={limit:50,depth:10,waitTimeoutMs:12e4,maxAgeS:604800,maxOutputBytes:256*1024};function le(e,t,n,r=0){return Math.min(n,Math.max(r,Math.floor(typeof e=="number"&&Number.isFinite(e)?e:t)))}function kn(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 o=e.format??S.format;return{url:r.href,source:e.source??S.source,limit:le(e.limit,S.limit,z.limit,1),depth:le(e.depth,S.depth,z.depth),render:e.render??S.render,formats:[o],...o==="json"?{jsonOptions:{...e.jsonPrompt!==void 0?{prompt:e.jsonPrompt}:{},...e.jsonSchema!==void 0?{response_format:e.jsonSchema}:{}}}:{},maxAge:le((n==null?void 0:n.maxAgeOverrideS)??e.maxAgeS,S.maxAgeS,z.maxAgeS),options:{includeExternalLinks:!1,includeSubdomains:e.includeSubdomains??S.includeSubdomains,includePatterns:e.includePatterns??[],excludePatterns:e.excludePatterns??[]}}}function Ne(e){return Array.isArray(e)?e.map(Ne):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Ne(n)])):e}async function po(e){let t=new TextEncoder().encode(JSON.stringify(Ne(e))),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}function xn(e,t){let n=t.split(/(\*\*|\*)/).map(r=>r==="**"?".*":r==="*"?"[^/]*":r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("");return new RegExp(`^${n}$`).test(e)}function ft(e,t,n){let r=(t==null?void 0:t.mode)??"pages",o=(t==null?void 0:t.fields)??["url","title",n],i=le(t==null?void 0:t.maxCharsPerPage,S.maxCharsPerPage,z.maxOutputBytes),s=e;if(r==="single"){let c=t==null?void 0:t.select,l=(c==null?void 0:c.url)!==void 0?e.find(p=>p.url===c.url):(c==null?void 0:c.pattern)!==void 0?e.find(p=>xn(p.url,c.pattern)):e[(c==null?void 0:c.index)??0];s=l?[l]:[]}let a=!1,u=s.map(c=>{let l={url:c.url,status:c.status};c.httpStatus!==void 0&&(l.httpStatus=c.httpStatus),o.includes("title")&&c.title!==void 0&&(l.title=c.title);let p=c.truncated??!1;if(o.includes("markdown")&&c.markdown!==void 0&&(l.markdown=c.markdown.slice(0,i),p||=l.markdown.length<c.markdown.length),o.includes("json")&&c.json!==void 0){let m=c.truncated&&typeof c.json=="string"?c.json:JSON.stringify(c.json);l.json=m.length>i?m.slice(0,i):c.json,p||=m.length>i}return p&&(l.truncated=!0),a||=p,l});if(r!=="concat")return{pages:u,truncated:a};let d=u.map(c=>o.map(l=>{let p=c[l];return p===void 0?"":typeof p=="string"?p:JSON.stringify(p)}).filter(Boolean).join(`
|
|
2
|
+
`)).join(`
|
|
3
|
+
|
|
4
|
+
`);return{pages:[],text:d,truncated:a}}var pt=e=>new TextEncoder().encode(JSON.stringify(e)).byteLength;async function mo(e,t,n){var P,R,U;let r=Date.now(),o=r+le(t.waitTimeoutMs,S.waitTimeoutMs,z.waitTimeoutMs),i=n.fetchImpl??fetch,s=n.sleep??(_=>new Promise(I=>setTimeout(I,_))),a=n.resumeJobId??null,u={status:"running"},d=[],c=!1,l=2,p=()=>Math.max(0,o-Date.now()),m=async _=>{if(!p())throw new Error("timeout");if(await s(Math.min(_,p())),!p())throw new Error("timeout")},w=async(_,I)=>{var k,x,b,M,E;for(let C=0;;C++){if(!p())throw new Error("timeout");let $=new AbortController,L,B=new Promise((T,oe)=>{L=setTimeout(()=>{$.abort(),oe(new Error("timeout"))},p())});try{let T=await Promise.race([i(_,{...I,signal:$.signal,headers:{Authorization:`Bearer ${e.apiToken}`,"Content-Type":"application/json"}}),B]);if(T.status===429&&C<2){let he=T.headers.get("Retry-After"),ze=he===null?NaN:Number(he),Je=Number.isFinite(ze)?Math.max(0,ze*1e3):he?Math.max(0,Date.parse(he)-Date.now()):2e3;await((k=T.body)==null?void 0:k.cancel()),clearTimeout(L),await m(Number.isFinite(Je)?Je:2e3);continue}let oe=await Promise.race([T.json(),B]);if(oe.success===!1)throw new Error(((b=(x=oe.errors)==null?void 0:x[0])==null?void 0:b.message)??"Crawl API error");if(!T.ok)throw new Error(((E=(M=oe.errors)==null?void 0:M[0])==null?void 0:E.message)??`Crawl API HTTP ${T.status}`);if(!p())throw new Error("timeout");return oe}catch(T){throw $.signal.aborted||!p()?new Error("timeout"):T}finally{clearTimeout(L)}}},O=(_,I)=>{let k=()=>ft(d.filter(M=>M.status==="completed"),t.output,t.format??"markdown"),x=k(),b={ok:_,error:I,data:a?{jobId:a,status:I==="timeout"?"running":u.status,total:u.total??0,finished:u.finished??0,browserSeconds:u.browserSecondsUsed??0,elapsedMs:Date.now()-r,...x,truncated:c||x.truncated}:null};for(;pt(b)>z.maxOutputBytes&&d.length;)d.pop(),x=k(),Object.assign(b.data,x,{truncated:!0});return{result:b,allPages:d}};try{if(!e.accountId||!e.apiToken)throw new Error("Crawl no configurado: faltan CF_ACCOUNT_ID / CF_BROWSER_RUN_TOKEN");let _=kn(t,n.url,n),I=`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(e.accountId)}/browser-run/crawl`;if(!a){let E=await w(I,{method:"POST",body:JSON.stringify(_)});if(typeof E.result!="string"||!E.result)throw new Error("Crawl API returned no jobId");a=E.result}let k=`${I}/${encodeURIComponent(a)}`,x=2e3;do{let E=await w(`${k}?limit=1`);if(!E.result||typeof E.result!="object"||!E.result.status)throw new Error("Crawl API returned no status");if(u=E.result,u.status!=="running")break;await m(x),x=Math.min(5e3,x+1e3)}while(p());let b,M=new Set;do{let E=b===void 0?"":`?cursor=${encodeURIComponent(b)}`,C=await w(`${k}${E}`);if(!C.result||typeof C.result!="object")throw new Error("Crawl API returned invalid results");u={...u,...C.result};for(let $ of C.result.records??[]){let L={url:$.url,status:$.status,...((P=$.metadata)==null?void 0:P.title)!==void 0?{title:$.metadata.title}:{},...((R=$.metadata)==null?void 0:R.status)!==void 0?{httpStatus:$.metadata.status}:{},...$.markdown!==void 0?{markdown:$.markdown}:{},...$.json!==void 0?{json:$.json}:{}},B=ft([L],{mode:"pages",maxCharsPerPage:(U=t.output)==null?void 0:U.maxCharsPerPage},t.format??"markdown").pages[0],T=pt(B)+1;if(l+T>z.maxOutputBytes){c=!0;break}d.push(B),l+=T}if(c)break;if(b=C.result.cursor,b!=null&&b!==""){if(M.has(String(b)))throw new Error("Crawl API repeated pagination cursor");M.add(String(b))}else b=void 0}while(b!==void 0);return O(u.status==="completed",u.status==="completed"?null:u.status)}catch(_){return O(!1,_ instanceof Error?_.message:String(_))}}var ve={timeoutMs:3e4},N={actions:50,timeoutMs:{min:1e3,max:12e4},waitMs:{min:0,max:3e4},fallbacks:5,headers:10,headerValueBytes:4096},mt=["goto","click","fill","select","check","wait","extract"],gt=["testId","role","label","placeholder","text","css"],ht=["text","value","attribute","html"],yt=["exact","startsWith","contains"],En=new Set(["click","fill","select","check","extract"]),bt=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/,wt=/^[A-Za-z0-9-]{1,64}$/,An=new Set(["host","cookie","user-agent","content-length","connection","origin","referer","forwarded","via","x-real-ip","true-client-ip","cf-connecting-ip"]);function J(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fe(e){return typeof e=="string"&&e.trim()!==""}function _t(e,t){return J(e)?gt.includes(e.by)?e.by==="role"?fe(e.role)?[]:[{code:"field_required",field:`${t}.role`,message:`${t}.role is required.`}]:fe(e.value)?[]:[{code:"field_required",field:`${t}.value`,message:`${t}.value is required.`}]:[{code:"field_enum",field:`${t}.by`,message:`${t}.by must be one of ${gt.join(", ")}.`}]:[{code:"field_type",field:t,message:`${t} must be an object.`}]}function Sn(e,t){if(!J(e))return[{code:"field_required",field:t,message:`${t} is required.`}];let n=_t(e.locator,`${t}.locator`);return e.fallbacks!==void 0&&(Array.isArray(e.fallbacks)?e.fallbacks.length>N.fallbacks?n.push({code:"field_range",field:`${t}.fallbacks`,message:`${t}.fallbacks allows at most ${N.fallbacks} locators.`}):e.fallbacks.forEach((r,o)=>n.push(..._t(r,`${t}.fallbacks.${o}`))):n.push({code:"field_type",field:`${t}.fallbacks`,message:`${t}.fallbacks must be an array.`})),n}function $n(e,t,n,r){let o=`actions.${t}`;if(!J(e))return[{code:"field_type",field:o,message:`${o} must be an object.`}];let i=[];fe(e.id)?n.has(e.id)?i.push({code:"field_type",field:`${o}.id`,message:`${o}.id duplicates another step.`}):n.add(e.id):i.push({code:"field_required",field:`${o}.id`,message:`${o}.id is required.`});let s=e.op;if(!mt.includes(s))return i.push({code:"field_enum",field:`${o}.op`,message:`${o}.op must be one of ${mt.join(", ")}.`}),i;switch((En.has(s)||s==="wait"&&e.target!==void 0)&&i.push(...Sn(e.target,`${o}.target`)),s){case"goto":fe(e.url)||i.push({code:"field_required",field:`${o}.url`,message:`${o}.url is required.`});break;case"fill":case"select":s==="select"&&e.match!==void 0&&!yt.includes(e.match)&&i.push({code:"field_enum",field:`${o}.match`,message:`${o}.match must be one of ${yt.join(", ")}.`}),typeof e.value!="string"&&i.push({code:"field_type",field:`${o}.value`,message:`${o}.value must be a string.`});break;case"check":typeof e.checked!="boolean"&&typeof e.checked!="string"&&i.push({code:"field_type",field:`${o}.checked`,message:`${o}.checked must be a boolean or a template.`});break;case"wait":{let a=e.ms;a!==void 0&&(!Number.isInteger(a)||a<N.waitMs.min||a>N.waitMs.max)&&i.push({code:"field_range",field:`${o}.ms`,message:`${o}.ms must be an integer between ${N.waitMs.min} and ${N.waitMs.max}.`}),a===void 0&&e.target===void 0&&i.push({code:"field_required",field:`${o}.target`,message:`${o} needs a target or ms.`});break}case"extract":ht.includes(e.as)?e.as==="attribute"&&!fe(e.attribute)&&i.push({code:"field_required",field:`${o}.attribute`,message:`${o}.attribute is required when as is attribute.`}):i.push({code:"field_enum",field:`${o}.as`,message:`${o}.as must be one of ${ht.join(", ")}.`}),typeof e.key!="string"||!bt.test(e.key)?i.push({code:"field_type",field:`${o}.key`,message:`${o}.key must match ${bt.source}.`}):r.has(e.key)?i.push({code:"field_type",field:`${o}.key`,message:`${o}.key duplicates another extract.`}):r.add(e.key);break;default:break}return i}function Nn(e){if(e===void 0)return[];if(!Array.isArray(e))return[{code:"field_type",field:"headers",message:"headers must be an array."}];if(e.length>N.headers)return[{code:"field_range",field:"headers",message:`headers allows at most ${N.headers} entries.`}];let t=[];return e.forEach((n,r)=>{let o=`headers.${r}`;if(!J(n)){t.push({code:"field_type",field:o,message:`${o} must be an object.`});return}let i=n.name;if(typeof i!="string"||!wt.test(i))t.push({code:"field_type",field:`${o}.name`,message:`${o}.name must match ${wt.source}.`});else{let s=i.toLowerCase();(An.has(s)||s.startsWith("sec-")||s.startsWith("proxy-")||s.startsWith("x-forwarded-"))&&t.push({code:"field_enum",field:`${o}.name`,message:`${o}.name is not allowed.`})}typeof n.value!="string"?t.push({code:"field_type",field:`${o}.value`,message:`${o}.value must be a string.`}):new TextEncoder().encode(n.value).byteLength>N.headerValueBytes&&t.push({code:"field_range",field:`${o}.value`,message:`${o}.value must be at most ${N.headerValueBytes} bytes.`})}),t}function xt(e){let t=[];t.push(...Nn(e.headers));let n=e.timeoutMs;if(n!==void 0){let{min:i,max:s}=N.timeoutMs;Number.isInteger(n)?(n<i||n>s)&&t.push({code:"field_range",field:"timeoutMs",message:`timeoutMs must be between ${i} and ${s}.`}):t.push({code:"field_type",field:"timeoutMs",message:"timeoutMs must be an integer."})}if(e.actions===void 0)return t;if(!Array.isArray(e.actions))return t.push({code:"field_type",field:"actions",message:"actions must be an array."}),t;e.actions.length>N.actions&&t.push({code:"field_range",field:"actions",message:`actions allows at most ${N.actions} steps.`});let r=new Set,o=new Set;return e.actions.forEach((i,s)=>t.push(...$n(i,s,r,o))),t.push(...vn(e.session,e.actions)),t}function kt(e,t,n=e.length){for(let r=Math.max(0,t);r<Math.min(n,e.length);r++)if(J(e[r])&&J(e[r].target))return r;return-1}function vn(e,t){if(e===void 0)return[];if(!J(e)||typeof e.enabled!="boolean")return[{code:"field_type",field:"session",message:"session must be { enabled: boolean, loginSteps: number }."}];if(e.generation!==void 0&&(!Number.isInteger(e.generation)||e.generation<0))return[{code:"field_type",field:"session.generation",message:"session.generation must be a non-negative integer."}];if(!e.enabled)return[];let n=e.loginSteps;if(!Number.isInteger(n)||n<1||n>=t.length)return[{code:"field_range",field:"session.loginSteps",message:"session.loginSteps must leave at least one login step and one step after it."}];let r=[];return kt(t,0,n)<0&&r.push({code:"field_required",field:"session.loginSteps",message:"The login block needs a step with an element (e.g. the user field)."}),kt(t,n)<0&&r.push({code:"field_required",field:"session.loginSteps",message:"A step with an element is needed after the login block to detect a valid session."}),r}var Et={startNode:{label:"Start",greeting:"",allow_images:!1,allow_documents:!1,inputs:[],memory_enabled:!1},classifierNode:{label:"Classifier",model:F.model,question:F.question,input:{message:F.input.message,historyTurns:F.input.historyTurns,vars:[...F.input.vars]},options:F.options.map(e=>({...e})),checks:[...F.checks],confidence:{...F.confidence}},memoNode:{label:"Knowledge",query_key:"user_input",topk:3},llmNode:{label:"AI Node",template:"",model:"gpt_5_nano",window_size:5,tools:[],attachments:[]},answerNode:{label:"Answer"},apiNode:{label:"API",method:"GET",headers:{},timeoutMs:5e3},toolNode:{label:"Tool",source:"http"},workerNode:{label:"Worker"},crawlNode:{label:"Crawl",url:"",source:S.source,limit:S.limit,depth:S.depth,render:S.render,format:S.format,includeSubdomains:S.includeSubdomains,output:{mode:"pages",maxCharsPerPage:S.maxCharsPerPage},waitTimeoutMs:S.waitTimeoutMs,maxAgeS:S.maxAgeS},webActionsNode:{label:"WebActions",url:"",actions:[],timeoutMs:ve.timeoutMs}},Rn={"startNode.user_input":"Text of the current user turn.","startNode.images":"Images attached to the turn. In scope only when allow_images is true.","startNode.files":"Document text attached to the turn. In scope only when allow_documents is true.","startNode.memory":"Capped memory string when memory is enabled.","classifierNode.classification":"Selected option id.","classifierNode.label":"Selected option label.","classifierNode.confidence":"Confidence of the selected option.","classifierNode.margin":"Gap between the top two probabilities.","classifierNode.probabilities":"Probability by option id.","classifierNode.route":"class, uncertain, blocked, or error.","classifierNode.checks":"Check scores keyed by check id.","memoNode.context":"Retrieved context string.","llmNode.output":"Model text output.","apiNode.ok":"Whether the HTTP call returned a 2xx status.","apiNode.status":"HTTP status code.","apiNode.data":"Response body.","toolNode.ok":"Whether the tool call succeeded.","toolNode.data":"Tool payload.","toolNode.error":"Tool error message, or null.","workerNode.ok":"Whether the child worker succeeded.","workerNode.data":"Structured output of the child Answer.","workerNode.error":"Child error message, or null.","crawlNode.ok":"Whether the crawl finished without an error.","crawlNode.data":"Crawl job summary and pages.","crawlNode.error":"Crawl error message, or null.","webActionsNode.ok":"Whether every step finished without an error.","webActionsNode.data":"Final url and title, extracted values keyed by extract key, and per-step results.","webActionsNode.error":"Error of the first failed step, or null."};function f(e,t,n){return{name:e,type:t,required:!1,persisted:!1,...n}}function In(e){return Xe(e).map(t=>({name:t.name,type:t.type,path:t.path??"",description:Rn[`${e}.${t.name}`]??t.name}))}function G(e,t){return{type:e,outputs:In(e),example:structuredClone(Et[e]),...t}}var Eo={startNode:G("startNode",{label:"Start",idPrefix:"start",summary:"Entry of the worker. Declares inputs, attachments, and memory.",handles:{target:!1,source:"single"},refFields:{templates:[],nestedTemplates:[],directRefs:[]},discovery:{model:"worker_models"},fields:[f("label","string",{persisted:!0,default:"Start",description:"Display label."}),f("greeting","string",{persisted:!0,default:"",description:"Opening message. Empty by default."}),f("allow_images","boolean",{persisted:!0,default:!1,description:"Puts images in scope when true."}),f("allow_documents","boolean",{persisted:!0,default:!1,description:"Puts files in scope when true."}),f("inputs","array",{persisted:!0,default:[],description:"Declarative inputs: name, type, required, default."}),f("memory_enabled","boolean",{persisted:!0,default:!1,description:"Injects capped memory into the turn."}),f("memory_model","string",{externalRef:"model",description:"Written only when memory is enabled. Default gpt_5_nano."}),f("memory_length","enum",{enum:["short","medium","long"],description:"Written only when memory is enabled. Default medium."}),f("user_input","string",{description:"Tolerated if present. The runtime does not read it from the node."}),f("outVars","array",{description:"Extra outputs, referenced as start.<name>."})]}),classifierNode:G("classifierNode",{label:"Classifier",idPrefix:"classifier",summary:"Clef classifier that routes through one source handle per option.",handles:{target:!0,source:"classifier"},refFields:{templates:[],nestedTemplates:[],directRefs:["input.message","input.vars","input_variable"]},discovery:{clefModel:"worker_models"},fields:[f("label","string",{persisted:!0,default:"Classifier",description:"Display label."}),f("model","enum",{required:!0,persisted:!0,default:"clef-omni",enum:["clef-omni","clef","clef-flash"],externalRef:"clefModel",description:"Clef model."}),f("question","string",{required:!0,persisted:!0,default:"",description:"Question shown to Clef, 1\u2013300 characters."}),f("input","object",{required:!0,persisted:!0,description:"message ref, historyTurns 0\u201310, and vars refs."}),f("options","array",{required:!0,persisted:!0,description:"2\u2013255 options with id, label, and criteria."}),f("checks","array",{required:!0,persisted:!0,default:[],description:"Up to 63 noul or score checks."}),f("confidence","object",{required:!0,persisted:!0,description:"threshold and margin, each between 0 and 1."}),f("outVars","array",{description:"Extra outputs."})]}),memoNode:G("memoNode",{label:"Knowledge",idPrefix:"memo",summary:"Vector search over one or more memos.",handles:{target:!0,source:"single"},refFields:{templates:[],nestedTemplates:[],directRefs:["query_key","input_variable"]},discovery:{memo:"worker_get_graph"},fields:[f("label","string",{persisted:!0,default:"Knowledge",description:"Display label."}),f("rag_id","string",{required:!0,externalRef:"memo",description:"Memo id or list of memo ids. Supplied by the agent."}),f("query_key","ref",{persisted:!0,default:"user_input",description:"Reference used as the search query."}),f("topk","integer",{persisted:!0,default:3,min:1,max:10,description:"Number of matches. Persisted as 3."}),f("outVars","array",{description:"Extra outputs."})]}),llmNode:G("llmNode",{label:"AI Node",idPrefix:"llm",summary:"Model call with templates, tools, and attachments.",handles:{target:!0,source:"single"},refFields:{templates:["template","user_template"],nestedTemplates:[],directRefs:["attachments","input_variable"]},discovery:{model:"worker_models",tool:"worker_tool_schema"},fields:[f("label","string",{persisted:!0,default:"AI Node",description:"Display label."}),f("template","template",{persisted:!0,default:"",description:"System template."}),f("user_template","template",{description:"User template. Empty uses the conversation history."}),f("model","string",{persisted:!0,default:"gpt_5_nano",externalRef:"model",description:"Model id. A one-item array is tolerated."}),f("window_size","integer",{persisted:!0,default:5,min:0,max:30,description:"History window."}),f("max_steps","integer",{min:1,max:30,description:"Tool-call steps. Not persisted; the runner defaults to 5, or 10 with skills."}),f("tools","array",{persisted:!0,default:[],description:"Tool entries: http, mcp, composio, builtin, or skill."}),f("attachments","ref[]",{persisted:!0,default:[],description:"Refs attached to the model call."}),f("reasoningEffort","enum",{enum:["none","minimal","low","medium","high","xhigh"],description:"Effort level, checked against the model in L3."}),f("generationPreset","enum",{enum:["precise","balanced","creative","custom"],description:"Generation preset metadata."}),f("outVars","array",{description:"Extra outputs."})]}),answerNode:G("answerNode",{label:"Answer",idPrefix:"answer",summary:"Ends a path and optionally maps structured output.",handles:{target:!0,source:"none"},refFields:{templates:[],nestedTemplates:[],directRefs:["outputMapping.from"]},discovery:{},fields:[f("label","string",{persisted:!0,default:"Answer",description:"Display label."}),f("outputMapping","array",{description:"Structured output rows: key, from, and optional default."})]}),apiNode:G("apiNode",{label:"API",idPrefix:"api",summary:"HTTP request. Object bodies are serialized before templates resolve.",handles:{target:!0,source:"single"},refFields:{templates:["url","body"],nestedTemplates:["headers","body"],directRefs:["input_variable"]},discovery:{secret:"secret_list"},fields:[f("label","string",{persisted:!0,default:"API",description:"Display label."}),f("url","template",{required:!0,description:"http(s) URL when it contains no template."}),f("method","enum",{persisted:!0,default:"GET",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"],description:"HTTP method. HEAD is valid."}),f("headers","object",{persisted:!0,default:{},description:"Header templates."}),f("body","object",{description:"String template or JSON value. Templates in object leaves are resolved."}),f("timeoutMs","integer",{persisted:!0,default:5e3,min:1,max:12e4,description:"Request timeout in milliseconds."}),f("outVars","array",{description:"Extra outputs, rooted at the response payload."})]}),toolNode:G("toolNode",{label:"Tool",idPrefix:"tool",summary:"Calls one http or composio tool row.",handles:{target:!0,source:"single"},refFields:{templates:[],nestedTemplates:["args"],directRefs:["input_variable"]},discovery:{tool:"worker_tool_schema",composioSlug:"worker_tool_schema"},fields:[f("label","string",{persisted:!0,default:"Tool",description:"Display label."}),f("source","enum",{persisted:!0,default:"http",enum:["http","composio"],description:"Tool source. catalog is rejected."}),f("toolId","string",{required:!0,externalRef:"tool",description:"Tool row id."}),f("toolSlug","string",{externalRef:"composioSlug",description:"Required when source is composio."}),f("toolVersion","string",{description:"Pinned Composio tool version."}),f("args","object",{description:"Arguments. String leaves are templates."}),f("inputSchema","object",{description:"Coercion schema. Not proof of access."}),f("argTypes","object",{description:"Alternate coercion map."}),f("outVars","array",{description:"Extra outputs, rooted at the tool payload."})]}),workerNode:G("workerNode",{label:"Worker",idPrefix:"worker",summary:"Runs another worker in this turn and reads its structured output.",handles:{target:!0,source:"single"},refFields:{templates:[],nestedTemplates:[],directRefs:["inputs.from"]},discovery:{worker:"worker_get_graph"},fields:[f("label","string",{persisted:!0,default:"Worker",description:"Display label. The canvas copies the child name."}),f("flowId","string",{required:!0,externalRef:"worker",description:"Child worker id. Must differ from this worker."}),f("inputs","array",{description:"Rows of key, optional from, and optional default."}),f("outVars","array",{description:"Extra outputs, including subpaths of data."})]}),crawlNode:G("crawlNode",{label:"Crawl",idPrefix:"crawl",summary:"Bounded site crawl. jsonPrompt is literal and is not interpolated.",handles:{target:!0,source:"single"},refFields:{templates:["url"],nestedTemplates:[],directRefs:["input_variable"]},discovery:{},fields:[f("label","string",{persisted:!0,default:"Crawl",description:"Display label."}),f("url","template",{persisted:!0,default:"",description:"Page URL. http(s) when it contains no template."}),f("source","enum",{persisted:!0,default:"all",enum:["all","sitemaps","links"],description:"Crawl source."}),f("limit","integer",{persisted:!0,default:5,min:1,max:50,description:"Maximum pages."}),f("depth","integer",{persisted:!0,default:2,min:0,max:10,description:"Link depth."}),f("render","boolean",{persisted:!0,default:!1,description:"Render pages in a browser."}),f("format","enum",{persisted:!0,default:"markdown",enum:["markdown","json"],description:"Page format."}),f("jsonPrompt","string",{description:"Literal prompt used only with format json. Mustaches are not resolved."}),f("jsonSchema","object",{description:"JSON schema used only with format json."}),f("includePatterns","array",{description:"URL patterns to keep."}),f("excludePatterns","array",{description:"URL patterns to drop."}),f("includeSubdomains","boolean",{persisted:!0,default:!1,description:"Follow subdomains."}),f("output","object",{persisted:!0,description:"mode pages, single, or concat, plus select, fields, and maxCharsPerPage."}),f("waitTimeoutMs","integer",{persisted:!0,default:6e4,min:0,max:12e4,description:"Wait timeout."}),f("maxAgeS","integer",{persisted:!0,default:86400,min:0,max:604800,description:"Cache max age."}),f("outVars","array",{description:"Extra outputs."})]}),webActionsNode:G("webActionsNode",{label:"WebActions",idPrefix:"web",summary:"Opens a page in a headless browser and runs ordered steps: goto, click, fill, select, check, wait, extract. String values in steps are templates.",handles:{target:!0,source:"single"},refFields:{templates:["url"],nestedTemplates:["actions","headers"],directRefs:[]},discovery:{secret:"secret_list"},fields:[f("label","string",{persisted:!0,default:"WebActions",description:"Display label."}),f("url","template",{persisted:!0,default:"",description:"Initial page. http(s) when it contains no template."}),f("actions","array",{persisted:!0,default:[],max:N.actions,description:"Ordered steps { id, op, target?, ... }. target is { locator, fallbacks?, hint? }; locator.by is testId, role, label, placeholder, text, or css. extract writes data.extracted[key]."}),f("timeoutMs","integer",{persisted:!0,default:ve.timeoutMs,min:N.timeoutMs.min,max:N.timeoutMs.max,description:"Budget for the whole node run."}),f("session","object",{persisted:!0,description:"Optional { enabled, loginSteps }. Steps [0, loginSteps) are the login; the browser state is saved per site and login values and the login is skipped while it still works. Both the login block and the steps after it need an element step."}),f("headers","array",{persisted:!0,max:N.headers,description:"Optional headers agreed with the site owner, { name, value }. value is a template. host, cookie, user-agent, content-length, connection, origin, referer, sec-* and proxy-* are rejected."}),f("outVars","array",{description:"Extra outputs, for example data.extracted.<key>."})]})};function Re(e){return structuredClone(Et[e])}var Z=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Y=e=>typeof e=="string"&&e.trim().length>0,Ie=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1;function be(e){if(!Z(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"),(!Y(e.question)||e.question.length>300)&&t.push("Classifier question is required and must be at most 300 characters"),(!Z(e.input)||!Y(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(Y))&&t.push("Classifier input requires message, historyTurns (0\u201310), and variable refs"),(!Z(e.confidence)||!Ie(e.confidence.threshold)||!Ie(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 n=new Set,r=(o,i)=>{typeof o!="string"||!/^[A-Za-z0-9_.-]{1,100}$/.test(o)||o.startsWith("__")?t.push("Classifier ids must use [A-Za-z0-9_.-], 1\u2013100 characters, without __ prefix"):n.has(o)||i&&o==="route"?t.push(`Classifier duplicate or reserved id: ${o}`):n.add(o)};for(let o of Array.isArray(e.options)?e.options:[]){if(!Z(o)){t.push("Classifier option must be an object");continue}r(o.id,!1),Object.hasOwn(o,"description")&&t.push("Classifier option uses criteria instead of description"),(!Y(o.label)||!Y(o.criteria))&&t.push("Classifier option requires label and criteria")}for(let o of Array.isArray(e.checks)?e.checks:[]){if(!Z(o)){t.push("Classifier check must be an object");continue}r(o.id,!0),Y(o.instructions)||t.push("Classifier check instructions are required"),o.type==="noul"?(o.guard!==void 0&&(!Z(o.guard)||!Ie(o.guard.threshold))&&t.push("Classifier guard threshold must be between 0 and 1"),o.criteria!==void 0&&(!Z(o.criteria)||!Object.values(o.criteria).every(i=>typeof i=="string")||Object.keys(o.criteria).some(i=>i!=="true"&&i!=="false"))&&t.push("Classifier noul criteria are invalid")):o.type==="score"?((!Array.isArray(o.levels)||o.levels.length<2||o.levels.length>10||!o.levels.every(Y))&&t.push("Classifier score requires 2\u201310 levels"),o.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 Tn={short:100,medium:250,long:1e3},Pn={short:2e3,medium:5e3,long:2e4},Te="medium",Pe="gpt_5_nano",At=4;function Cn(e){return e==="short"||e==="medium"||e==="long"?e:Te}function On(e=Te){return Pn[e]}function No(e=Te){return Tn[e]}function Mn(e){return e?Math.ceil(e.length/At):0}function Wn(e,t){if(!e)return{content:"",truncated:!1};if(Mn(e)<=t)return{content:e,truncated:!1};let n=Math.max(0,t*At);return{content:e.slice(0,n),truncated:!0}}function St(e){let t=e==null?void 0:e.memory_enabled;return t===!0||t==="true"||t===1}function $t(e){let t=e==null?void 0:e.memory_model;return typeof t=="string"&&t.trim()?t.trim():Pe}function vo(e){return Cn(e==null?void 0:e.memory_length)}function Ro(e,t){let n=On(e);return t&&t!=="none"?n+2048:n}var Nt=/^(user|assistant|usuario|asistente|u|a)\s*:/i,jn=/^(hola|hello|hi|hey|buenas|buen[oa]s?\s+d[ií]as?|qu[eé]\s+tal|qu[eé]\s+haces)[\s,.!¡¿?]*$/i;function Ln(e){let t=e.split(`
|
|
5
|
+
`).map(r=>r.replace(/^[-*]\s*/,"").trim()).filter(Boolean);if(t.length<2)return!1;let n=t.filter(r=>Nt.test(r));return n.length>=2&&n.length>=Math.ceil(t.length/2)}function Gn(e){let t=e.split(`
|
|
6
|
+
`).map(n=>n.trim()).filter(Boolean).filter(n=>n!=="(empty)"&&n!=="(none)").filter(n=>!Nt.test(n.replace(/^[-*]\s*/,"")));return Ln(t.join(`
|
|
7
|
+
`))?"":t.join(`
|
|
8
|
+
`)}function Io(e){let t=e.trim();if(!t||jn.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 o=t.match(/me gusta[n]?\s+([^,.!?]+)/i);if(o&&n.push(`Likes: ${o[1].trim()}`),/[?¿]/.test(t)||/^(pregunt|dime\b|cu[eé]nt)/i.test(t))return n;let s=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 s.length>=16&&n.push(s.slice(0,140)),n}function To(e,t,n){let o=[...Gn(e).split(`
|
|
9
|
+
`).map(i=>i.replace(/^[-*]\s*/,"").trim()).filter(Boolean)];for(let i of t){let s=i.replace(/^[-*]\s*/,"").trim();s&&(o.some(a=>a.toLowerCase()===s.toLowerCase())||o.push(s))}return o.length===0?"":Wn(o.map(i=>`- ${i}`).join(`
|
|
10
|
+
`),n).content}var It=["template","user_template","url","body"],Tt=["headers","args","body","actions"],Pt=["query_key","input_variable"];function W(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function We(e){let t=e.replace(/\\\{\{/g,"\0").replace(/\\\}\}/g,"\0"),n=[];for(let r of t.matchAll(/\{\{\s*([^}]+?)\s*\}\}/g)){let o=r[1]??"";try{n.push(ye(o).ref)}catch{n.push(o)}}return n}function Ce(e,t,n){if(typeof t=="string"){for(let r of We(t))e.push({field:n,ref:r});return}if(Array.isArray(t)){t.forEach((r,o)=>Ce(e,r,`${n}[${o}]`));return}if(W(t))for(let[r,o]of Object.entries(t))Ce(e,o,n?`${n}.${r}`:r)}function Ct(e){let t=W(e.data)?e.data:{},n=[];for(let o of It)if(!(o==="body"&&typeof t.body!="string")&&typeof t[o]=="string")for(let i of We(t[o]))n.push({field:o,ref:i});for(let o of Tt)o==="body"&&typeof t.body=="string"||t[o]!==void 0&&Ce(n,t[o],o);for(let o of Pt)typeof t[o]=="string"&&t[o]&&n.push({field:o,ref:t[o]});let r=t.input;return W(r)&&(typeof r.message=="string"&&r.message&&n.push({field:"input.message",ref:r.message}),Array.isArray(r.vars)&&r.vars.forEach((o,i)=>{typeof o=="string"&&o&&n.push({field:`input.vars[${i}]`,ref:o})})),Array.isArray(t.attachments)&&t.attachments.forEach((o,i)=>{typeof o=="string"&&o&&n.push({field:`attachments[${i}]`,ref:o})}),Array.isArray(t.outputMapping)&&t.outputMapping.forEach((o,i)=>{W(o)&&typeof o.from=="string"&&o.from&&n.push({field:`outputMapping[${i}].from`,ref:o.from})}),Array.isArray(t.inputs)&&t.inputs.forEach((o,i)=>{W(o)&&"from"in o&&typeof o.from=="string"&&o.from&&n.push({field:`inputs[${i}].from`,ref:o.from})}),n}function ie(e,t,n){return typeof e=="string"&&e.startsWith(`${t}.`)?`${n}${e.slice(t.length)}`:e}function Oe(e,t,n){return typeof e=="string"?$e(e,t,n):Array.isArray(e)?e.map(r=>Oe(r,t,n)):W(e)?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Oe(o,t,n)])):e}function Ot(e,t,n){let r=structuredClone(e);for(let o of It)o==="body"&&typeof r.body!="string"||typeof r[o]=="string"&&(r[o]=$e(r[o],t,n));for(let o of Tt)o==="body"&&typeof r.body=="string"||r[o]!==void 0&&(r[o]=Oe(r[o],t,n));for(let o of Pt)r[o]=ie(r[o],t,n);if(W(r.input)){let o={...r.input};o.message=ie(o.message,t,n),Array.isArray(o.vars)&&(o.vars=o.vars.map(i=>ie(i,t,n))),r.input=o}return Array.isArray(r.attachments)&&(r.attachments=r.attachments.map(o=>ie(o,t,n))),Array.isArray(r.outputMapping)&&(r.outputMapping=r.outputMapping.map(o=>W(o)?{...o,from:ie(o.from,t,n)}:o)),Array.isArray(r.inputs)&&(r.inputs=r.inputs.map(o=>W(o)&&"from"in o?{...o,from:ie(o.from,t,n)}:o)),r}function Me(e,t,n,r){for(let o of We(r)){if(!o.startsWith("secrets."))continue;let i=o.slice(8);i&&e.push({kind:"secret",id:i,nodeId:t,field:n})}}function pe(e,t,n,r){if(typeof n=="string"){Me(e,t,r,n);return}if(Array.isArray(n)){n.forEach((o,i)=>pe(e,t,o,`${r}[${i}]`));return}if(W(n))for(let[o,i]of Object.entries(n))pe(e,t,i,r?`${r}.${o}`:o)}function D(e,t,n,r,o,i){typeof n!="string"||!n.trim()||e.push({kind:t,id:n.trim(),nodeId:r,field:o,...i?{extra:i}:{}})}function Fn(e){let t=Array.isArray(e.model)?e.model[0]:e.model;return typeof t=="string"&&t.trim()?t.trim():Pe}function vt(e){let t=[];for(let n of e.nodes){let r=W(n.data)?n.data:{},o=n.type;if(o==="startNode"&&St(r)&&D(t,"model",$t(r),n.id,"memory_model"),o==="classifierNode"&&D(t,"clefModel",r.model,n.id,"model"),o==="llmNode"&&(D(t,"model",Fn(r),n.id,"model"),Array.isArray(r.tools)&&r.tools.forEach((i,s)=>{typeof i=="string"?D(t,"tool",i,n.id,`tools[${s}]`):W(i)&&typeof i.id=="string"&&D(t,"tool",i.id,n.id,`tools[${s}].id`,typeof i.kind=="string"?{kind:i.kind}:void 0)})),o==="memoNode"&&(Array.isArray(r.rag_id)?r.rag_id:[r.rag_id]).forEach((s,a)=>D(t,"memo",s,n.id,Array.isArray(r.rag_id)?`rag_id[${a}]`:"rag_id")),o==="toolNode"){D(t,"tool",r.toolId,n.id,"toolId",typeof r.source=="string"?{source:r.source}:void 0);let i=typeof r.toolId=="string"?r.toolId.trim():"";D(t,"composioSlug",r.toolSlug,n.id,"toolSlug",i?{toolId:i}:void 0)}o==="workerNode"&&D(t,"worker",r.flowId,n.id,"flowId");for(let i of["template","user_template","url"])typeof r[i]=="string"&&Me(t,n.id,i,r[i]);typeof r.body=="string"?Me(t,n.id,"body",r.body):r.body!==void 0&&pe(t,n.id,r.body,"body"),r.headers!==void 0&&pe(t,n.id,r.headers,"headers"),r.args!==void 0&&pe(t,n.id,r.args,"args")}return t}function Mo(e,t){let n=new Set((e?vt(e):[]).map(Rt));return vt(t).filter(r=>!n.has(Rt(r)))}function Rt(e){var n;let t=e.kind==="composioSlug"&&typeof((n=e.extra)==null?void 0:n.toolId)=="string"?e.extra.toolId:"";return`${e.kind}\0${e.nodeId}\0${e.field}\0${e.id}\0${t}`}var Dn=new Set(Object.values(Ze)),qn=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD"]),Hn=new Set(["http","mcp","composio","builtin","skill"]),Wt=["user_input","images","files","memory"],Un=["temperature","topP","topK","frequencyPenalty","presencePenalty"],Vn=["maxOutputTokens","seed","maxRetries"],Kn=new Set(["missing_state","schema_version","var_mapping","classifier_invalid","classifier_edge_missing","out_vars_invalid","start_count","answer_missing","dead_end"]),Bn={missing_state:"blocking",schema_version:"blocking",var_mapping:"blocking",classifier_invalid:"blocking",classifier_edge_missing:"blocking",out_vars_invalid:"blocking",start_count:"blocking",answer_missing:"blocking",dead_end:"blocking",unknown_node_type:"blocking",duplicate_node_id:"blocking",invalid_node_id:"blocking",node_id_collides_with_input:"blocking",edge_unknown_node:"blocking",edge_bad_handle:"blocking",edge_duplicate:"blocking",start_has_input:"blocking",answer_has_output:"blocking",multiple_outgoing:"blocking",field_type:"blocking",field_required:"blocking",field_range:"blocking",field_enum:"blocking",ref_syntax:"blocking",ref_unknown_node:"blocking",ref_out_of_scope:"blocking",ref_unknown_output:"blocking",ref_binary_not_allowed:"blocking",start_input_invalid:"blocking",answer_mapping_invalid:"blocking",worker_self_reference:"blocking",classifier_error_unrouted:"advisory",classifier_handle_inactive:"advisory",unreachable_node:"advisory",graph_cycle:"advisory",crawl_prompt_literal:"advisory",model_unknown:"blocking",param_unsupported:"advisory",reasoning_effort_unsupported:"advisory",tool_unavailable:"blocking",tool_kind_mismatch:"blocking",skill_unavailable:"blocking",builtin_unknown:"blocking",tool_args_invalid:"blocking",tool_args_unknown:"advisory",composio_slug_disabled:"blocking",composio_schema_missing:"advisory",memo_unavailable:"blocking",worker_unavailable:"blocking",worker_child_no_output:"blocking",worker_inputs_mismatch:"blocking",worker_child_inactive_forbidden:"blocking",worker_child_inactive:"advisory",secret_unknown:"advisory",secret_check_skipped:"advisory",inline_credential:"blocking",op_invalid:"blocking",op_unknown_node:"blocking",already_connected:"blocking",edge_not_found:"blocking",edge_ambiguous:"blocking",cannot_remove_start:"blocking"};function jt(e,t,n,r){return{code:e,severity:t,message:n,...r}}function y(e,t,n){return jt(e,"error",t,n)}function se(e,t,n){return jt(e,"warning",t,n)}function A(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Lt(e){return typeof e=="number"&&Number.isInteger(e)}function je(e,t){let n=new Set,r=[e];for(n.add(e);r.length>0;){let o=r.shift();for(let i of t.get(o)||[])n.has(i)||(n.add(i),r.push(i))}return n}function Ko(e){var i,s;let t=e;if(!t||!t.nodes||!t.edges||t.edges.length===0)return[y("missing_state","Flow is missing state, nodes, or edges.")];let n=[];t.schemaVersion!==3&&n.push(y("schema_version","Flow uses an unsupported variable schema. Recreate it in Agent Design 3.0."));for(let a of t.nodes){if(((i=a==null?void 0:a.data)==null?void 0:i.varMapping)!==void 0&&n.push(y("var_mapping",`Flow uses removed varMapping on node ${a.id}.`,{nodeId:a.id})),(a==null?void 0:a.type)==="classifierNode"){let d=be(a.data);if(d.length)n.push(y("classifier_invalid",d.join("; "),{nodeId:a.id}));else for(let c of a.data.options){let l=t.edges.find(p=>p.source===a.id&&p.sourceHandle===it("class",c.id));(!l||!t.nodes.some(p=>p.id===l.target))&&n.push(y("classifier_edge_missing",`Classifier ${a.id}: class ${c.id} has no connected edge`,{nodeId:a.id,ref:c.id}))}}let u=Qe(a);u.length>0&&u[0]&&n.push(y("out_vars_invalid",u[0],{nodeId:a.id}))}let r=t.nodes.filter(a=>(a==null?void 0:a.type)==="startNode");r.length!==1&&n.push(y("start_count",`Flow must include exactly one START node, found ${r.length}.`));let o=t.nodes.filter(a=>(a==null?void 0:a.type)==="answerNode");if(o.length===0&&n.push(y("answer_missing","Flow must include at least one ANSWER node.")),r.length===1&&o.length>0){let a=new Map,u=new Map;for(let p of t.edges)a.has(p.source)||a.set(p.source,[]),a.get(p.source).push(p.target),u.has(p.target)||u.set(p.target,[]),u.get(p.target).push(p.source);let d=je(r[0].id,a),c=new Set;for(let p of o)for(let m of je(p.id,u))c.add(m);let l=[];for(let p of d){if(c.has(p))continue;let m=t.nodes.find(w=>w.id===p);m&&l.push(`${p}(${((s=m.data)==null?void 0:s.label)||""},${m.type})`)}l.length>0&&n.push(y("dead_end",`The following nodes reachable from START do not lead to any ANSWER node: ${l.join(", ")}`))}return n}function h(e,t,n,r){return y(e,r,{nodeId:t,field:n})}function ae(e,t,n,r,o){let i=n[r];if(i===void 0||i===""){o&&e.push(h("field_required",t,r,`Field ${r} is required on node ${t}.`));return}if(typeof i!="string"){e.push(h("field_type",t,r,`Field ${r} on node ${t} must be a string.`));return}return i}function q(e,t,n,r,o,i){let s=n[r];if(s!==void 0){if(!Lt(s)){e.push(h("field_type",t,r,`Field ${r} on node ${t} must be an integer.`));return}(s<o||s>i)&&e.push(h("field_range",t,r,`Field ${r} on node ${t} must be between ${o} and ${i}.`))}}function X(e,t,n,r,o){let i=n[r];i!==void 0&&(typeof i!="string"||!o.has(i))&&e.push(h("field_enum",t,r,`Field ${r} on node ${t} must be one of ${[...o].join(", ")}.`))}function Le(e,t,n,r){if(!n){r&&e.push(h("field_required",t,"url",`Field url is required on node ${t}.`));return}if(!n.includes("{{")){try{let o=new URL(n);if(o.protocol==="http:"||o.protocol==="https:")return}catch{}e.push(h("field_type",t,"url",`Field url on node ${t} must be an http(s) URL when it is literal.`))}}function zn(e,t){let n=A(e.data)?e.data:{};switch(n.outVars!==void 0&&!Array.isArray(n.outVars)&&t.push(h("field_type",e.id,"outVars",`Field outVars on node ${e.id} must be an array.`)),e.type){case"startNode":Jn(e,n,t);break;case"memoNode":{let r=n.rag_id;r===void 0||r===""||Array.isArray(r)&&r.length===0?t.push(h("field_required",e.id,"rag_id",`Field rag_id is required on node ${e.id}.`)):typeof r!="string"&&!(Array.isArray(r)&&r.every(i=>typeof i=="string"&&i))&&t.push(h("field_type",e.id,"rag_id",`Field rag_id on node ${e.id} must be a string or a list of strings.`)),q(t,e.id,n,"topk",1,10);break}case"llmNode":Yn(e,n,t);break;case"answerNode":Xn(e,n,t);break;case"apiNode":Qn(e,n,t);break;case"toolNode":er(e,n,t);break;case"workerNode":{let r=ae(t,e.id,n,"flowId",!0);r!==void 0&&!r.trim()&&t.push(h("field_required",e.id,"flowId",`Field flowId is required on node ${e.id}.`)),n.inputs!==void 0&&!Array.isArray(n.inputs)&&t.push(h("field_type",e.id,"inputs",`Field inputs on node ${e.id} must be an array.`));break}case"crawlNode":nr(e,n,t);break;case"webActionsNode":tr(e,n,t);break;default:break}}function Jn(e,t,n){for(let i of["label","greeting","user_input"])t[i]!==void 0&&typeof t[i]!="string"&&n.push(h("field_type",e.id,i,`Field ${i} on node ${e.id} must be a string.`));for(let i of["allow_images","allow_documents","memory_enabled"])t[i]!==void 0&&typeof t[i]!="boolean"&&n.push(h("field_type",e.id,i,`Field ${i} on node ${e.id} must be a boolean.`));if(X(n,e.id,t,"memory_length",new Set(["short","medium","long"])),t.memory_model!==void 0&&typeof t.memory_model!="string"&&n.push(h("field_type",e.id,"memory_model",`Field memory_model on node ${e.id} must be a string.`)),t.inputs===void 0)return;if(!Array.isArray(t.inputs)){n.push(h("field_type",e.id,"inputs",`Field inputs on node ${e.id} must be an array.`));return}let r=new Set,o=new Set(Wt);if(Array.isArray(t.outVars))for(let i of t.outVars)A(i)&&typeof i.name=="string"&&o.add(i.name);t.inputs.forEach((i,s)=>{if(!A(i)){n.push(y("start_input_invalid",`Start input ${s} on node ${e.id} must be an object.`,{nodeId:e.id,field:`inputs[${s}]`}));return}let a=typeof i.name=="string"?i.name.trim():"",u=`inputs[${s}].name`;!Ye.test(a)||r.has(a)||o.has(a)?n.push(y("start_input_invalid",`Start input "${a||s}" on node ${e.id} is invalid or duplicated.`,{nodeId:e.id,field:u,ref:a})):r.add(a);let d=typeof i.type=="string"?i.type:"string";["string","number","boolean","json"].includes(d)?i.default!==void 0&&!Zn(d,i.default)&&n.push(y("start_input_invalid",`Start input "${a}" has a default that does not match ${d}.`,{nodeId:e.id,field:`inputs[${s}].default`})):n.push(y("start_input_invalid",`Start input "${a}" has an invalid type.`,{nodeId:e.id,field:`inputs[${s}].type`}))})}function Zn(e,t){return e==="string"?typeof t=="string":e==="number"?typeof t=="number"&&Number.isFinite(t):e==="boolean"?typeof t=="boolean":e==="json"?t===null||["string","number","boolean","object"].includes(typeof t):!1}function Yn(e,t,n){for(let r of["template","user_template"])t[r]!==void 0&&typeof t[r]!="string"&&n.push(h("field_type",e.id,r,`Field ${r} on node ${e.id} must be a string.`));t.model!==void 0&&typeof t.model!="string"&&!(Array.isArray(t.model)&&typeof t.model[0]=="string")&&n.push(h("field_type",e.id,"model",`Field model on node ${e.id} must be a string.`)),q(n,e.id,t,"window_size",0,30),q(n,e.id,t,"max_steps",1,30),X(n,e.id,t,"reasoningEffort",new Set(["none","minimal","low","medium","high","xhigh"])),X(n,e.id,t,"generationPreset",new Set(["precise","balanced","creative","custom"]));for(let r of Un)t[r]!==void 0&&(typeof t[r]!="number"||!Number.isFinite(t[r]))&&n.push(h("field_type",e.id,r,`Field ${r} on node ${e.id} must be a finite number.`));for(let r of Vn)t[r]!==void 0&&!Lt(t[r])&&n.push(h("field_type",e.id,r,`Field ${r} on node ${e.id} must be an integer.`));t.stopSequences!==void 0&&(!Array.isArray(t.stopSequences)||t.stopSequences.some(r=>typeof r!="string"))&&n.push(h("field_type",e.id,"stopSequences",`Field stopSequences on node ${e.id} must be a list of strings.`)),t.tools!==void 0&&!Array.isArray(t.tools)?n.push(h("field_type",e.id,"tools",`Field tools on node ${e.id} must be an array.`)):Array.isArray(t.tools)&&t.tools.forEach((r,o)=>{typeof r!="string"&&(!A(r)||typeof r.kind!="string"||!Hn.has(r.kind)||typeof r.id!="string"||!r.id)&&n.push(h("field_type",e.id,`tools[${o}]`,`Tool ${o} on node ${e.id} must be a string or a {kind, id} entry.`))}),t.attachments!==void 0&&!Array.isArray(t.attachments)&&n.push(h("field_type",e.id,"attachments",`Field attachments on node ${e.id} must be an array.`))}function Xn(e,t,n){if(t.outputMapping===void 0)return;if(!Array.isArray(t.outputMapping)){n.push(h("field_type",e.id,"outputMapping",`Field outputMapping on node ${e.id} must be an array.`));return}let r=new Set;t.outputMapping.forEach((o,i)=>{let s=A(o)&&typeof o.key=="string"?o.key:"",a=A(o)&&typeof o.from=="string"?o.from:"";(!s.trim()||r.has(s)||!a)&&n.push(y("answer_mapping_invalid",`Answer mapping ${i} on node ${e.id} needs a unique key and a from ref.`,{nodeId:e.id,field:`outputMapping[${i}]`})),s&&r.add(s)})}function Qn(e,t,n){let r=ae(n,e.id,t,"url",!0);if(r&&Le(n,e.id,r,!0),X(n,e.id,t,"method",qn),q(n,e.id,t,"timeoutMs",1,12e4),t.headers!==void 0&&!A(t.headers))n.push(h("field_type",e.id,"headers",`Field headers on node ${e.id} must be an object.`));else if(A(t.headers))for(let[o,i]of Object.entries(t.headers))typeof i!="string"&&n.push(h("field_type",e.id,`headers.${o}`,`Header ${o} on node ${e.id} must be a string.`));t.body!==void 0&&typeof t.body!="string"&&!A(t.body)&&!Array.isArray(t.body)&&n.push(h("field_type",e.id,"body",`Field body on node ${e.id} must be a string or a JSON value.`))}function er(e,t,n){ae(n,e.id,t,"toolId",!0),t.source!==void 0&&t.source!=="http"&&t.source!=="composio"&&n.push(h("field_enum",e.id,"source",`Field source on node ${e.id} must be http or composio.`)),t.source==="composio"&&ae(n,e.id,t,"toolSlug",!0),t.args!==void 0&&!A(t.args)&&n.push(h("field_type",e.id,"args",`Field args on node ${e.id} must be an object.`)),t.inputSchema!==void 0&&!A(t.inputSchema)&&n.push(h("field_type",e.id,"inputSchema",`Field inputSchema on node ${e.id} must be an object.`))}function tr(e,t,n){let r=ae(n,e.id,t,"url",!0);r&&Le(n,e.id,r,!0);for(let o of xt(t))n.push(h(o.code,e.id,o.field,`${o.message.replace(/\.$/,"")} on node ${e.id}.`))}function nr(e,t,n){let r=ae(n,e.id,t,"url",!0);r&&Le(n,e.id,r,!0),X(n,e.id,t,"source",new Set(["all","sitemaps","links"])),q(n,e.id,t,"limit",1,50),q(n,e.id,t,"depth",0,10),X(n,e.id,t,"format",new Set(["markdown","json"])),t.render!==void 0&&typeof t.render!="boolean"&&n.push(h("field_type",e.id,"render",`Field render on node ${e.id} must be a boolean.`)),t.includeSubdomains!==void 0&&typeof t.includeSubdomains!="boolean"&&n.push(h("field_type",e.id,"includeSubdomains",`Field includeSubdomains on node ${e.id} must be a boolean.`));for(let i of["includePatterns","excludePatterns"])t[i]!==void 0&&(!Array.isArray(t[i])||t[i].some(s=>typeof s!="string"))&&n.push(h("field_type",e.id,i,`Field ${i} on node ${e.id} must be a list of strings.`));!(t.format==="json")&&(t.jsonPrompt!==void 0||t.jsonSchema!==void 0)&&n.push(h("field_type",e.id,"jsonPrompt",`jsonPrompt and jsonSchema on node ${e.id} require format json.`)),t.jsonPrompt!==void 0&&typeof t.jsonPrompt!="string"&&n.push(h("field_type",e.id,"jsonPrompt",`Field jsonPrompt on node ${e.id} must be a string.`)),typeof t.jsonPrompt=="string"&&t.jsonPrompt.includes("{{")&&n.push(se("crawl_prompt_literal",`Crawl jsonPrompt on node ${e.id} is literal and is not interpolated.`,{nodeId:e.id,field:"jsonPrompt",hint:"Write the prompt as plain text. Templates are not resolved."})),t.jsonSchema!==void 0&&!A(t.jsonSchema)&&n.push(h("field_type",e.id,"jsonSchema",`Field jsonSchema on node ${e.id} must be an object.`)),t.output!==void 0&&!A(t.output)?n.push(h("field_type",e.id,"output",`Field output on node ${e.id} must be an object.`)):A(t.output)&&(X(n,e.id,t.output,"mode",new Set(["pages","single","concat"])),t.output.select!==void 0&&t.output.mode!=="single"&&n.push(h("field_type",e.id,"output.select",`output.select on node ${e.id} is only valid when mode is single.`)),t.output.fields!==void 0&&(!Array.isArray(t.output.fields)||t.output.fields.some(i=>!["url","title","markdown","json"].includes(String(i))))&&n.push(h("field_enum",e.id,"output.fields",`output.fields on node ${e.id} must use url, title, markdown, or json.`)),q(n,e.id,t.output,"maxCharsPerPage",0,262144)),q(n,e.id,t,"waitTimeoutMs",0,12e4),q(n,e.id,t,"maxAgeS",0,604800)}function rr(e){let t=new Set(["source-__uncertain","source-__blocked","source-__error"]),n=A(e.data)&&Array.isArray(e.data.options)?e.data.options:[];for(let r of n)A(r)&&typeof r.id=="string"&&t.add(`source-${r.id}`);return t}function or(e,t){let n=new Map(e.nodes.map(s=>[s.id,s])),r=new Set,o=new Map,i=new Map;for(let s of e.edges){let a=n.get(s.source),u=n.get(s.target);if(!a||!u){t.push(y("edge_unknown_node",`Edge ${s.id||`${s.source}->${s.target}`} references a missing node.`,{edgeId:s.id,nodeId:a?s.target:s.source}));continue}u.type==="startNode"&&t.push(y("start_has_input",`Start node ${u.id} cannot have an incoming edge.`,{nodeId:u.id,edgeId:s.id})),a.type==="answerNode"&&t.push(y("answer_has_output",`Answer node ${a.id} cannot have an outgoing edge.`,{nodeId:a.id,edgeId:s.id}));let d=typeof s.sourceHandle=="string"&&s.sourceHandle?s.sourceHandle:void 0;if("targetHandle"in s&&s.targetHandle!=null&&t.push(y("edge_bad_handle",`Edge ${s.id} cannot set targetHandle.`,{nodeId:a.id,edgeId:s.id,field:"targetHandle"})),a.type==="classifierNode"){let l=rr(a);(!d||!l.has(d))&&t.push(y("edge_bad_handle",`Classifier ${a.id} edge has an invalid handle.`,{nodeId:a.id,edgeId:s.id,field:"sourceHandle",ref:d}));let p=o.get(a.id)??new Set;d&&p.has(d)&&t.push(y("edge_bad_handle",`Classifier ${a.id} handle ${d} is duplicated.`,{nodeId:a.id,edgeId:s.id,ref:d})),d&&p.add(d),o.set(a.id,p)}else d&&t.push(y("edge_bad_handle",`Node ${a.id} cannot set a source handle.`,{nodeId:a.id,edgeId:s.id,field:"sourceHandle",ref:d}));let c=`${s.source}\0${s.target}\0${d??""}`;r.has(c)&&t.push(y("edge_duplicate",`Duplicate edge from ${s.source} to ${s.target}.`,{nodeId:a.id,edgeId:s.id,ref:d})),r.add(c),i.set(a.id,(i.get(a.id)??0)+1)}for(let[s,a]of i){let u=n.get(s);u&&u.type!=="classifierNode"&&a>1&&t.push(y("multiple_outgoing",`Node ${s} has multiple outgoing edges.`,{nodeId:s,field:"edges"}))}}function ir(e,t,n,r){var i;return(i=et(e,t,n).sort((s,a)=>a.ref.length-s.ref.length).find(s=>s.ref===r||r.startsWith(`${s.ref}.`)))==null?void 0:i.type}function sr(e,t,n){let r=e.nodes,o=e.edges;for(let i of Ct(t)){let s=i.ref;try{s=ye(i.ref).ref}catch{n.push(y("ref_syntax",`Reference in ${i.field} on node ${t.id} is invalid.`,{nodeId:t.id,field:i.field,ref:i.ref}));continue}if(s.startsWith("secrets.")||s.startsWith("auth."))continue;try{rt(s,{context:{},results:{},nodes:r,edges:o,currentNodeId:t.id})}catch(d){if(!(d instanceof nt))throw d;let c=d.code==="UNKNOWN_OUTPUT"?"ref_unknown_output":d.code==="OUT_OF_SCOPE"?"ref_out_of_scope":d.code==="UNKNOWN_CONTEXT_REF"?"ref_unknown_node":"ref_syntax";n.push(y(c,d.message,{nodeId:t.id,field:i.field,ref:s}));continue}let a=i.field.startsWith("outputMapping")||i.field==="input.message"||i.field.startsWith("input.vars"),u=ir(r,o,t.id,s);a&&u&&tt({type:u})&&n.push(y("ref_binary_not_allowed",`Reference ${s} on node ${t.id} points at a binary output.`,{nodeId:t.id,field:i.field,ref:s}))}}function ar(e,t){var r;for(let o of e.nodes){if(o.type!=="classifierNode")continue;let i=A(o.data)?o.data:{},s=e.edges.filter(c=>c.source===o.id);s.some(c=>c.sourceHandle==="source-__error")||t.push(se("classifier_error_unrouted",`Classifier ${o.id} has no source-__error edge.`,{nodeId:o.id,field:"sourceHandle",ref:"source-__error",hint:"Connect source-__error so Clef failures have a route."}));let a=A(i.confidence)?i.confidence:{},u=typeof a.threshold=="number"&&a.threshold>0||typeof a.margin=="number"&&a.margin>0,d=Array.isArray(i.checks)&&i.checks.some(c=>A(c)&&c.guard!==void 0);s.some(c=>c.sourceHandle==="source-__uncertain")&&!u&&t.push(se("classifier_handle_inactive",`Classifier ${o.id} connects source-__uncertain but threshold and margin are 0.`,{nodeId:o.id,ref:"source-__uncertain"})),s.some(c=>c.sourceHandle==="source-__blocked")&&!d&&t.push(se("classifier_handle_inactive",`Classifier ${o.id} connects source-__blocked but no check has a guard.`,{nodeId:o.id,ref:"source-__blocked"}))}let n=e.nodes.filter(o=>o.type==="startNode");if(n.length===1&&n[0]){let o=new Map;for(let s of e.nodes)o.set(s.id,[]);for(let s of e.edges)(r=o.get(s.source))==null||r.push(s.target);let i=je(n[0].id,o);for(let s of e.nodes)i.has(s.id)||t.push(se("unreachable_node",`Node ${s.id} is not reachable from Start.`,{nodeId:s.id}))}dr(e)&&t.push(se("graph_cycle","Graph contains a cycle."))}function dr(e){var o;let t=new Map,n=new Map(e.nodes.map(i=>[i.id,[]]));for(let i of e.edges)(o=n.get(i.source))==null||o.push(i.target);let r=i=>{let s=t.get(i)??0;if(s===1)return!0;if(s===2)return!1;t.set(i,1);for(let a of n.get(i)??[])if(r(a))return!0;return t.set(i,2),!1};return e.nodes.some(i=>r(i.id))}function ur(e,t){var i,s;let n=new Set,r=new Set(Wt);for(let a of e.nodes)if(!(a.type!=="startNode"||!Array.isArray((i=a.data)==null?void 0:i.inputs)))for(let u of a.data.inputs)A(u)&&typeof u.name=="string"&&u.name.trim()&&r.add(u.name.trim());for(let a of e.nodes)Dn.has(a.type)||t.push(y("unknown_node_type",`Node ${a.id} has an unknown type.`,{nodeId:a.id,field:"type"})),n.has(a.id)&&t.push(y("duplicate_node_id",`Duplicate node id ${a.id}.`,{nodeId:a.id})),n.add(a.id),(typeof a.id!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(a.id))&&t.push(y("invalid_node_id",`Node id ${a.id} is invalid.`,{nodeId:a.id})),r.has(a.id)&&t.push(y("node_id_collides_with_input",`Node id ${a.id} collides with a Start input or output.`,{nodeId:a.id}));let o=new Set(e.nodes.map(a=>a.id));for(let a of e.nodes)if(!(a.type!=="startNode"||!Array.isArray((s=a.data)==null?void 0:s.inputs)))for(let u of a.data.inputs)!A(u)||typeof u.name!="string"||o.has(u.name)&&t.push(y("start_input_invalid",`Start input "${u.name}" collides with a node id.`,{nodeId:a.id,field:"inputs",ref:u.name}))}function Bo(e){let t=[];ur(e,t),or(e,t);for(let n of e.nodes)zn(n,t),sr(e,n,t);return ar(e,t),t}function Mt(e){return[e.code,e.nodeId??"",e.field??"",e.ref??"",e.kind??""].join("")}function zo(e,t,n={}){let r=new Set(e.map(Mt)),o=[],i=[];for(let s of t){let a=r.has(Mt(s)),u;Kn.has(s.code)?u="error":s.code==="inline_credential"?u=!a&&!n.acknowledgeInlineCredentials?"error":"warning":Bn[s.code]==="advisory"?u="warning":u=a?"warning":"error";let d={...s,severity:u};(u==="error"?o:i).push(d)}return{errors:o,warnings:i}}var Ge=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,cr=new Set(["source-__uncertain","source-__blocked","source-__error"]);function we(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ft(e,t,n){return`xy-edge__${e}${n??""}-${t}`}function Dt(e,t){let n=t.replace(/Node$/,""),r=new Set(e.nodes.map(i=>i.id)),o=1;for(;r.has(`${n}-${o}`);)o+=1;return`${n}-${o}`}function xe(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return structuredClone(t);let n=we(e)?{...e}:{};for(let[r,o]of Object.entries(t))o===null?delete n[r]:n[r]=xe(n[r],o);return n}function _e(e){return Array.isArray(e)?e.map(_e):we(e)?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t<n?-1:t>n?1:0).map(([t,n])=>[t,_e(n)])):e}function Xo(e){let t=_e(e);return Array.isArray(t.nodes)&&t.nodes.sort((n,r)=>String(n.id).localeCompare(String(r.id))),Array.isArray(t.edges)&&t.edges.sort((n,r)=>String((n==null?void 0:n.id)??"").localeCompare(String((r==null?void 0:r.id)??""))),t}function Gt(e){return JSON.stringify(_e({type:e.type,position:e.position,data:e.data}))}function lr(e,t){let n=new Map(e.nodes.map(s=>[s.id,s])),r=new Map(t.nodes.map(s=>[s.id,s])),o=new Set(e.edges.map(s=>s.id)),i=new Set(t.edges.map(s=>s.id));return{nodesAdded:t.nodes.filter(s=>!n.has(s.id)).map(s=>s.id),nodesRemoved:e.nodes.filter(s=>!r.has(s.id)).map(s=>s.id),nodesChanged:t.nodes.filter(s=>{let a=n.get(s.id);return a?Gt(a)!==Gt(s):!1}).map(s=>s.id),edgesAdded:t.edges.filter(s=>!o.has(s.id)).map(s=>s.id),edgesRemoved:e.edges.filter(s=>!i.has(s.id)).map(s=>s.id)}}function g(e,t,n,r){return{code:e,severity:"error",message:t,op:n,...r}}function v(e,t){return e.nodes.find(n=>n.id===t)}function H(e){return e.startsWith("source-")?e:`source-${e}`}function qt(e){let t=new Set(cr),n=we(e.data)&&Array.isArray(e.data.options)?e.data.options:[];for(let r of n)we(r)&&typeof r.id=="string"&&r.id&&t.add(`source-${r.id}`);return t}function me(e){let t=e==null?void 0:e.position;return{x:typeof(t==null?void 0:t.x)=="number"?t.x:0,y:typeof(t==null?void 0:t.y)=="number"?t.y:0}}function fr(e,t){if(t.position)return{...t.position};if(t.from){let o=v(e,t.from.node),i=e.edges.filter(a=>{var u;return a.source===((u=t.from)==null?void 0:u.node)}).length,s=me(o);return{x:s.x+320,y:s.y+140*i}}if(t.to){let o=me(v(e,t.to.node));return{x:o.x-320,y:o.y}}let n=e.nodes.map(o=>me(o).x),r=e.nodes.map(o=>me(o).y);return{x:(n.length?Math.max(...n):0)+320,y:r.length?Math.min(...r):0}}function de(e,t,n){return{id:Ft(e,t,n),source:e,target:t,...n?{sourceHandle:n}:{}}}function ke(e,t){return e.edges.filter(n=>n.source===t)}function Ht(e,t,n,r){if(e.type==="classifierNode"){if(!t)return g("op_invalid","handle is required when the source is a classifier.",n,{nodeId:e.id,field:r});let o=H(t);return qt(e).has(o)?void 0:g("op_invalid",`Classifier ${e.id} has no handle ${o}.`,n,{nodeId:e.id,field:r,ref:o})}if(t)return g("op_invalid","handle is only valid when the source is a classifier.",n,{nodeId:e.id,field:r})}function pr(e,t,n){switch(t.op){case"add_node":return mr(e,t,n);case"insert_node":return gr(e,t,n);case"update_node":return hr(e,t,n);case"rename_node":return yr(e,t,n);case"remove_node":return br(e,t,n);case"connect":return wr(e,t,n);case"disconnect":return _r(e,t,n);case"move_node":return kr(e,t,n);default:return g("op_invalid","Unknown op.",n)}}function mr(e,t,n){var u,d,c;if(t.type==="startNode"&&e.nodes.some(l=>l.type==="startNode"))return g("op_invalid","A worker can include only one Start node.",n);let r=t.id??Dt(e,t.type);if(!Ge.test(r))return g("op_invalid",`Node id ${r} is not a valid new id.`,n,{field:"id"});if(v(e,r))return g("op_invalid",`Node id ${r} already exists.`,n,{nodeId:r});let o=t.from?v(e,t.from.node):void 0,i=t.to?v(e,t.to.node):void 0;if(t.from&&!o)return g("op_unknown_node",`Node ${t.from.node} does not exist.`,n,{nodeId:t.from.node});if(t.to&&!i)return g("op_unknown_node",`Node ${t.to.node} does not exist.`,n,{nodeId:t.to.node});if((i==null?void 0:i.type)==="startNode")return g("op_invalid","An edge cannot target the Start node.",n,{nodeId:i.id});if((o==null?void 0:o.type)==="answerNode")return g("op_invalid","An edge cannot leave an Answer node.",n,{nodeId:o.id});if(o){let l=Ht(o,(u=t.from)==null?void 0:u.handle,n,"from.handle");if(l)return l;if(o.type!=="classifierNode"&&ke(e,o.id).length>0)return g("already_connected",`Node ${o.id} already has an outgoing edge.`,n,{nodeId:o.id});if(o.type==="classifierNode"&&((d=t.from)!=null&&d.handle)){let p=H(t.from.handle);if(ke(e,o.id).some(m=>m.sourceHandle===p))return g("already_connected",`Handle ${p} is already connected.`,n,{nodeId:o.id,ref:p})}}let s=xe(Re(t.type),t.data??{}),a={id:r,type:t.type,position:fr(e,t),data:s};if((c=t.to)!=null&&c.handle){if(t.type!=="classifierNode")return g("op_invalid","to.handle is only valid when the new node is a classifier.",n,{field:"to.handle"});if(!qt(a).has(H(t.to.handle)))return g("op_invalid","to.handle must be an option or reserved handle of the new classifier.",n,{field:"to.handle",ref:H(t.to.handle)})}else if(t.to&&t.type==="classifierNode")return g("op_invalid","to.handle is required when the new node is a classifier.",n,{field:"to.handle"});if(e.nodes.push(a),o&&t.from){let l=o.type==="classifierNode"&&t.from.handle?H(t.from.handle):void 0;e.edges.push(de(o.id,r,l))}if(i&&t.to){let l=t.type==="classifierNode"&&t.to.handle?H(t.to.handle):void 0;e.edges.push(de(r,i.id,l))}}function gr(e,t,n){if(t.type==="classifierNode"||t.type==="startNode"||t.type==="answerNode")return g("op_invalid",`insert_node does not accept ${t.type}.`,n,{field:"type"});let r=t.id??Dt(e,t.type);if(!Ge.test(r))return g("op_invalid",`Node id ${r} is not a valid new id.`,n,{field:"id"});if(v(e,r))return g("op_invalid",`Node id ${r} already exists.`,n,{nodeId:r});let o=v(e,t.between.from),i=v(e,t.between.to);if(!o)return g("op_unknown_node",`Node ${t.between.from} does not exist.`,n,{nodeId:t.between.from});if(!i)return g("op_unknown_node",`Node ${t.between.to} does not exist.`,n,{nodeId:t.between.to});let s=t.between.handle?H(t.between.handle):void 0,a=e.edges.filter(l=>l.source===o.id&&l.target===i.id&&(s===void 0||l.sourceHandle===s||l.sourceHandle===t.between.handle));if(a.length===0)return g("edge_not_found",`No edge from ${o.id} to ${i.id}.`,n);if(a.length>1)return g("edge_ambiguous",`Multiple edges from ${o.id} to ${i.id}; pass handle.`,n,{ref:s});let[u]=a;if(!u)return g("edge_not_found",`No edge from ${o.id} to ${i.id}.`,n);e.edges=e.edges.filter(l=>l.id!==u.id);let d=xe(Re(t.type),t.data??{}),c=me(o);e.nodes.push({id:r,type:t.type,position:{x:c.x+320,y:c.y},data:d}),e.edges.push(de(o.id,r,u.sourceHandle)),e.edges.push(de(r,i.id))}function hr(e,t,n){let r=v(e,t.id);if(!r)return g("op_unknown_node",`Node ${t.id} does not exist.`,n,{nodeId:t.id});r.data=xe(r.data,t.data)}function yr(e,t,n){let r=v(e,t.id);if(!r)return g("op_unknown_node",`Node ${t.id} does not exist.`,n,{nodeId:t.id});if(r.type==="startNode")return g("op_invalid","The Start node cannot be renamed.",n,{nodeId:r.id});if(!Ge.test(t.newId))return g("op_invalid",`Node id ${t.newId} is not a valid new id.`,n,{field:"newId"});if(v(e,t.newId))return g("op_invalid",`Node id ${t.newId} already exists.`,n,{nodeId:t.newId});for(let o of e.nodes)o.data=Ot(o.data,t.id,t.newId);r.id=t.newId,e.edges=e.edges.map(o=>{let i=o.source===t.id?t.newId:o.source,s=o.target===t.id?t.newId:o.target;return{...o,source:i,target:s,id:Ft(i,s,o.sourceHandle)}})}function br(e,t,n){var s;let r=v(e,t.id);if(!r)return g("op_unknown_node",`Node ${t.id} does not exist.`,n,{nodeId:t.id});if(r.type==="startNode")return g("cannot_remove_start","The Start node cannot be removed.",n,{nodeId:r.id});let o=e.edges.filter(a=>a.target===r.id),i=e.edges.filter(a=>a.source===r.id);if(t.reconnect){if(r.type==="classifierNode"||o.length!==1||i.length!==1)return g("op_invalid","reconnect requires exactly one incoming and one outgoing edge on a non-classifier node.",n,{nodeId:r.id});let a=o[0],u=i[0];if(!a||!u)return g("op_invalid","reconnect requires exactly one incoming and one outgoing edge.",n,{nodeId:r.id});if(((s=v(e,u.target))==null?void 0:s.type)==="startNode")return g("op_invalid","An edge cannot target the Start node.",n);e.edges=e.edges.filter(d=>d.source!==r.id&&d.target!==r.id),e.edges.push(de(a.source,u.target,a.sourceHandle))}else e.edges=e.edges.filter(a=>a.source!==r.id&&a.target!==r.id);e.nodes=e.nodes.filter(a=>a.id!==r.id)}function wr(e,t,n){if(t.from===t.to)return g("op_invalid","An edge cannot connect a node to itself.",n,{nodeId:t.from});let r=v(e,t.from),o=v(e,t.to);if(!r)return g("op_unknown_node",`Node ${t.from} does not exist.`,n,{nodeId:t.from});if(!o)return g("op_unknown_node",`Node ${t.to} does not exist.`,n,{nodeId:t.to});if(o.type==="startNode")return g("op_invalid","An edge cannot target the Start node.",n,{nodeId:o.id});if(r.type==="answerNode")return g("op_invalid","An edge cannot leave an Answer node.",n,{nodeId:r.id});let i=Ht(r,t.handle,n,"handle");if(i)return i;let s=r.type==="classifierNode"&&t.handle?H(t.handle):void 0;if(e.edges.some(u=>u.source===r.id&&u.target===o.id&&(u.sourceHandle??void 0)===s))return g("edge_duplicate","An identical edge already exists.",n,{nodeId:r.id,ref:s});if(r.type==="classifierNode"){let u=ke(e,r.id).find(d=>d.sourceHandle===s);if(u&&!t.replace)return g("already_connected",`Handle ${s} is already connected.`,n,{nodeId:r.id,ref:s});u&&t.replace&&(e.edges=e.edges.filter(d=>d.id!==u.id))}else if(ke(e,r.id).length>0){if(!t.replace)return g("already_connected",`Node ${r.id} already has an outgoing edge.`,n,{nodeId:r.id});e.edges=e.edges.filter(u=>u.source!==r.id)}e.edges.push(de(r.id,o.id,s))}function _r(e,t,n){let r=v(e,t.from);if(!r)return g("op_unknown_node",`Node ${t.from} does not exist.`,n,{nodeId:t.from});if(t.to&&!v(e,t.to))return g("op_unknown_node",`Node ${t.to} does not exist.`,n,{nodeId:t.to});let o=t.handle?H(t.handle):void 0,i=e.edges.filter(a=>!(a.source!==r.id||t.to!==void 0&&a.target!==t.to||o!==void 0&&a.sourceHandle!==o));if(i.length===0)return g("edge_not_found","No edge matches.",n,{nodeId:r.id,ref:o});let s=new Set(i.map(a=>a.id));e.edges=e.edges.filter(a=>!s.has(a.id))}function kr(e,t,n){let r=v(e,t.id);if(!r)return g("op_unknown_node",`Node ${t.id} does not exist.`,n,{nodeId:t.id});r.position={x:t.position.x,y:t.position.y}}function Qo(e,t){let n=structuredClone(e);for(let r=0;r<t.length;r+=1){let o=t[r];if(!o)continue;let i=pr(n,o,r);if(i)return{ok:!1,issue:i}}return{ok:!0,graph:n,changes:lr(e,n)}}var xr=[/sk-[A-Za-z0-9_-]{20,}/,/sk-ant-/,/sk_live_/,/rk_live_/,/gh[pousr]_[A-Za-z0-9]{30,}/,/github_pat_/,/glpat-/,/xox[abprs]-/,/AKIA[0-9A-Z]{16}/,/AIza[0-9A-Za-z_-]{35}/,/eyJ[\w-]+\.eyJ[\w-]+\.[\w-]+/,/-----BEGIN [A-Z ]*PRIVATE KEY-----/],Er=new Set(["authorization","proxy-authorization","x-api-key","api-key","apikey","x-auth-token","x-access-token","cookie"]),Ar=new Set(["key","api_key","apikey","token","access_token","secret","password","sig","signature"]),Sr=new Set(["password","secret","token","api_key","apikey","client_secret","private_key"]),$r="Store it with `secret_set` and replace the value with `{{ secrets.NAME }}`.";function Q(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ee(e){return e.replace(/\{\{\s*(?:secrets|auth)\.[^}]*\}\}/g,"")}function ue(e){return xr.some(t=>t.test(e))}function Nr(e){if(!e)return 0;let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);let n=0;for(let r of t.values()){let o=r/e.length;n-=o*Math.log2(o)}return n}function Ut(e){return e.length>=32&&/^[A-Za-z0-9+/_=-]+$/.test(e)&&Nr(e)>3.5}function vr(e){let t=e.toLowerCase();return Er.has(t)||t.includes("token")||t.includes("secret")||t.includes("key")}function Rr(e,t){let n=`${e}_${t}`.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_+/g,"_");return/^[A-Z]/.test(n)?n:`S_${n||"SECRET"}`}function te(e,t,n){return{code:"inline_credential",severity:"warning",message:`Inline credential in ${t}.`,nodeId:e,field:t,kind:n,suggestedSecret:Rr(e,t),hint:$r}}function Ir(e,t){if(/^bearer\s+\S/i.test(t))return"bearer_token";if(/^basic\s+\S/i.test(t))return"basic_auth";if(vr(e)&&t.trim())return Ut(t)?"high_entropy":"sensitive_key"}function De(e,t,n=""){if(typeof e=="string"){t(n,e);return}if(Array.isArray(e)){e.forEach((r,o)=>De(r,t,`${n}[${o}]`));return}if(Q(e))for(let[r,o]of Object.entries(e))r!=="label"&&De(o,t,n?`${n}.${r}`:r)}function Tr(e){if(typeof e!="string")return e;let t=e.trim();if(!(!t.startsWith("{")&&!t.startsWith("[")))try{return JSON.parse(t)}catch{return}}function Pr(e,t){let n=ee(t).trim();if(!n||n.includes("{{"))return[];let r;try{r=new URL(n)}catch{return[]}let o=[];(r.username||r.password)&&o.push(te(e,"url","url_userinfo"));for(let[i,s]of r.searchParams){if(!Ar.has(i.toLowerCase()))continue;let a=ee(s).trim();!a||a.includes("{{")||o.push(te(e,"url",ue(a)?"known_token":"url_query"))}return o}function Fe(e,t,n){let r=[],o=(s,a,u)=>{if(!Sr.has(u.toLowerCase()))return;let d=ee(a).trim();d.length<8||d.includes("{{")||ue(d)||r.push(te(e,s||t,Ut(d)?"high_entropy":"sensitive_key"))},i=(s,a)=>{if(typeof s!="string"){if(Array.isArray(s)){s.forEach((u,d)=>i(u,`${a}[${d}]`));return}if(Q(s))for(let[u,d]of Object.entries(s)){let c=a?`${a}.${u}`:u;typeof d=="string"?o(c,d,u):i(d,c)}}};return i(n,t),r}function ti(e){let t=[];for(let r of e.nodes){let o=Q(r.data)?r.data:{};if(De(o,(i,s)=>{i&&ue(ee(s))&&t.push(te(r.id,i,"known_token"))}),r.type==="apiNode"&&Q(o.headers))for(let[i,s]of Object.entries(o.headers)){if(typeof s!="string")continue;let a=ee(s).trim();if(!a.replace(/^(bearer|basic)\s+/i,"").trim()||ue(a))continue;let d=Ir(i,a);d&&t.push(te(r.id,`headers.${i}`,d))}if((r.type==="apiNode"||r.type==="crawlNode"||r.type==="webActionsNode")&&typeof o.url=="string"){let i=Pr(r.id,o.url);ue(ee(o.url))&&!i.some(s=>s.kind==="known_token")&&t.push(te(r.id,"url","known_token")),t.push(...i)}if(r.type==="apiNode"&&o.body!==void 0){let i=Tr(o.body);Q(i)||Array.isArray(i)?t.push(...Fe(r.id,"body",i)):Q(o.body)||Array.isArray(o.body)?t.push(...Fe(r.id,"body",o.body)):typeof o.body=="string"&&ue(ee(o.body))&&t.push(te(r.id,"body","known_token"))}r.type==="toolNode"&&(Q(o.args)||Array.isArray(o.args))&&t.push(...Fe(r.id,"args",o.args))}let n=new Set;return t.filter(r=>{let o=`${r.nodeId}\0${r.field}\0${r.kind}`;return n.has(o)?!1:(n.add(o),!0)})}function qe(e,t,n,r){return{id:e,type:t,position:{x:r,y:0},data:n}}function Vt(e,t){return{id:`xy-edge__${e}-${t}`,source:e,target:t}}var Cr={label:"Start",greeting:"",allow_images:!1,allow_documents:!1,inputs:[],memory_enabled:!1},Or={label:"AI Node",template:"",model:"gpt_5_nano",window_size:5,tools:[],attachments:[]};function Kt(e){return{schemaVersion:3,nodes:[qe("start","startNode",{...Cr,...e!=null&&e.inputs?{inputs:e.inputs}:{}},0),qe("llm-1","llmNode",{...Or,...(e==null?void 0:e.template)!==void 0?{template:e.template}:{}},320),qe("answer-1","answerNode",{label:"Answer",outputMapping:[{key:(e==null?void 0:e.key)??"reply",from:"llm-1.output"}]},640)],edges:[Vt("start","llm-1"),Vt("llm-1","answer-1")]}}var ri={chat:Kt(),extract:Kt({inputs:[{name:"document_text",type:"string",required:!0}],template:"Extrae los datos que pide el usuario a partir de {{ document_text }}. Responde solo con el extracto, sin pre\xE1mbulo.",key:"extracted"})};function ii(e,t){let n=new Set(t),r=e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9_.-]+/g,"_").replace(/_+/g,"_").replace(/^[_.-]+|[_.-]+$/g,"").replace(/^__+/,""),o=(r&&r!=="route"?r:"option").slice(0,100),i=o,s=2;for(;n.has(i)||i==="route"||i.startsWith("__")||!/^[a-z0-9_.-]{1,100}$/.test(i);){let a=`_${s++}`;if(i=`${o.slice(0,Math.max(1,100-a.length))}${a}`,s>400)return`option_${s}`}return i}var Mr=[{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."}],Wr=Mr.reduce((e,t)=>(e[t.id]=t,e),{});var _i=2e4,ki=8192;function jr(e,t){if(e==null)return e;let n=r=>{for(let o of t)o&&(r=r.split(o).join("[redacted]").split(encodeURIComponent(o)).join("[redacted]"));return r};return JSON.parse(JSON.stringify(e),(r,o)=>typeof o=="string"?n(o):o&&typeof o=="object"&&!Array.isArray(o)?Object.fromEntries(Object.entries(o).map(([i,s])=>[n(i),s])):o)}function xi(e){if(e==null)return{value:e,truncated:!1};let t=new TextEncoder().encode(JSON.stringify(e));return t.byteLength<=8192?{value:e,truncated:!1}:{value:new TextDecoder().decode(t.slice(0,8192)),truncated:!0}}function Lr(e){let t;try{t=new URL(e)}catch{throw new Error("URL inv\xE1lida")}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("URL no permitida: solo http(s)")}function He(e,{allowPrivate:t=!1}={}){if(Lr(e),t)return;let n=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,""),r=n.split(".").map(Number),o=/^\d+\.\d+\.\d+\.\d+$/.test(n)&&(r[0]===0||r[0]===127||r[0]===10||r[0]===172&&r[1]>=16&&r[1]<=31||r[0]===192&&r[1]===168||r[0]===169&&r[1]===254||r[0]===100&&r[1]>=64&&r[1]<=127);if(n==="localhost"||n.endsWith(".localhost")||o||n==="::1"||n==="::"||/^f[cd][0-9a-f]{2}:/.test(n)||/^fe[89ab][0-9a-f]:/.test(n)||n.startsWith("::ffff:"))throw new Error("URL no permitida: destino privado")}async function Ei(e,t,n){await j(e.route("**/*",async r=>{if(r.request().isNavigationRequest())try{He(r.request().url(),t)}catch{await r.abort("blockedbyclient");return}await r.continue()}),n)}function Ai(e,t){try{let n=jr(new URL(e).host,t);return typeof n=="string"&&n?n:"unknown"}catch{return"unknown"}}function ge(e){let t=e-Date.now();if(t<=0)throw new Error("timeout");return Math.max(1,t)}function Bt(e){return e instanceof Error?e.message==="timeout"||/Timeout \d+ms exceeded/i.test(e.message)?new Error("timeout"):e:new Error(String(e))}function zt(e){return e===null?null:e.length>2e4?e.slice(0,2e4):e}function Ue(e,t){switch(t.by){case"testId":return e.getByTestId(t.value);case"role":return e.getByRole(t.role,{...t.name!==void 0?{name:t.name}:{},...t.exact!==void 0?{exact:t.exact}:{}});case"label":return e.getByLabel(t.value,t.exact!==void 0?{exact:t.exact}:void 0);case"placeholder":return e.getByPlaceholder(t.value,t.exact!==void 0?{exact:t.exact}:void 0);case"text":return e.getByText(t.value,t.exact!==void 0?{exact:t.exact}:void 0);case"css":return e.locator(t.value);default:{let n=t;throw new Error(`locator no soportado: ${JSON.stringify(n)}`)}}}var Gr=250;async function Jt(e,t,n,r){let o=[t.locator,...t.fallbacks??[]];for(;;){let i;for(let a of o){let u=Ue(e,a);if(Date.now()>=n)throw new Error("elemento no encontrado");let d=await j(u.count(),n);if(d===1)return u;d>1&&!i&&(i={locator:u,count:d})}if(i)return r(i.count),i.locator.first();let s=n-Date.now();if(s<=0)throw new Error("elemento no encontrado");await e.waitForTimeout(Math.min(Gr,s))}}async function j(e,t){let n;try{return await Promise.race([e,new Promise((r,o)=>{n=setTimeout(()=>o(new Error("timeout")),ge(t))})])}finally{n!==void 0&&clearTimeout(n)}}var Fr=new Set(["websocket","eventsource"]);function Zt(e,{quietMs:t=300}={}){let n=e,r=new Set,o=Date.now(),i=d=>{var c;try{return((c=d.resourceType)==null?void 0:c.call(d))??""}catch{return""}},s=d=>{Fr.has(i(d))||(r.add(d),o=Date.now())},a=d=>{r.delete(d)&&(o=Date.now())},u=[["request",s],["requestfinished",a],["requestfailed",a]];if(typeof n.on=="function")for(let[d,c]of u)n.on(d,c);return{async settle(d,c){if(typeof n.on!="function")return;let l=Math.min(d-50,Date.now()+c);for(await new Promise(p=>setTimeout(p,Math.max(0,Math.min(100,l-Date.now()))));Date.now()<l;){if(r.size===0&&Date.now()-o>=t)return;await new Promise(p=>setTimeout(p,Math.max(0,Math.min(50,l-Date.now()))))}},dispose(){if(typeof n.off=="function")for(let[d,c]of u)n.off(d,c);r.clear()}}}var Dr=2e3;async function Yt(e,t){try{let n=await j(e.title(),t),r=e.url(),o="";try{let i=Math.min(1e3,ge(t));o=(await j(e.locator("body").innerText({timeout:i}),t)).slice(0,Dr)}catch{o=""}return qr(n,r,o)}catch{return null}}function qr(e,t,n){let r=`${e}
|
|
11
|
+
${t}
|
|
12
|
+
${n}`.toLowerCase();return r.includes("just a moment")||r.includes("cf-browser-verification")||r.includes("checking your browser")||r.includes("challenges.cloudflare.com")?{vendor:"cloudflare",kind:"challenge"}:r.includes("attention required")||r.includes("sorry, you have been blocked")?{vendor:"cloudflare",kind:"block"}:r.includes("datadome")||r.includes("captcha-delivery.com")?{vendor:"datadome",kind:r.includes("captcha")||r.includes("captcha-delivery.com")?"challenge":"block"}:r.includes("press & hold")||r.includes("press and hold")||r.includes("perimeterx")||r.includes("px-captcha")?{vendor:"perimeterx",kind:"challenge"}:r.includes("incapsula")||r.includes("imperva")?{vendor:"imperva",kind:"block"}:r.includes("shieldsquare")||r.includes("radware")||r.includes("access denied")&&r.includes("validate")?{vendor:"radware",kind:"block"}:r.includes("akamai")||r.includes("edgesuite")||r.includes("access denied")&&r.includes("reference #")||/^access denied!?$/.test(e.trim().toLowerCase())?{vendor:"akamai",kind:"block"}:null}var Hr=[[/^(?:__cf_bm|cf_clearance|__cflb|cf_chl.*)$/i,"cloudflare"],[/^datadome$/i,"datadome"],[/^(?:_px.*|pxcts)$/i,"perimeterx"],[/^(?:visid_incap_|incap_ses_|nlbi_)/i,"imperva"],[/^(?:ak_bmsc|bm_sz|bm_sv|_abck)$/i,"akamai"],[/^(?:rbzid|rbzsessionid)$/i,"radware"]];function Ni(e){for(let t of e)for(let[n,r]of Hr)if(n.test(t))return r;return null}var Ur=2e3,Vr=new Set(["goto","click","select","check"]);async function Ti(e,t,n){let{deadline:r,resolve:o,onAmbiguous:i}=n,s=n.sensitive??[],a=[],u={},d=n.activity??Zt(e),c=n.settleMs??Ur;try{for(let m=0;m<t.length;m++){let w=t[m],O=Date.now();try{await j(l(w,e,r,u,s,P=>i==null?void 0:i(P,w)),r),Vr.has(w.op)&&await d.settle(r,c),a.push({id:w.id,op:w.op,ok:!0,ms:Date.now()-O})}catch(P){let R=Bt(P).message,U;if(R==="elemento no encontrado"||R==="timeout"){let _=await Yt(e,r).catch(()=>null);_&&(U=_,R=`el sitio bloque\xF3 el acceso automatizado (${_.vendor}); se requiere autorizaci\xF3n del sitio`)}return a.push({id:w.id,op:w.op,ok:!1,ms:Date.now()-O,error:R,...U?{blocked:U}:{}}),{steps:a,extracted:u,error:`Paso ${m+1+(n.indexOffset??0)} (${w.op}): ${R}`}}}return{steps:a,extracted:u,error:null}}finally{n.activity||d.dispose()}async function l(m,w,O,P,R,U){let _=()=>ge(O),I=()=>Jt(w,"target"in m?m.target:{locator:{by:"css",value:""}},O,U);switch(m.op){case"goto":{let k=o(m.url);He(k,n),await w.goto(k,{waitUntil:"domcontentloaded",timeout:_()});return}case"click":{let k=await I(),x=_();m.waitForNavigation?await Promise.all([w.waitForNavigation({timeout:x}),k.click({timeout:x})]):await k.click({timeout:x});return}case"fill":{let k=o(m.value);R.push(k),await(await I()).fill(k,{timeout:_()});return}case"select":{let k=o(m.value);R.push(k);let x=await I(),b=[];for(;!b.length;)b=await j(x.evaluate(E=>{if(!(E instanceof HTMLSelectElement))throw new Error("el elemento no es select");return Array.from(E.options).map(C=>({value:C.value,label:C.label}))}),O),b.length||await j(w.waitForTimeout(Math.min(100,_())),O);let M=b.find(E=>E.value===k)??b.find(E=>E.label.trim()===k.trim());if(!M&&m.match&&m.match!=="exact"){let E=L=>L.trim().replace(/\s+/g," ").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""),C=E(k),$=b.filter(L=>[L.value,L.label].some(B=>{let T=E(B);return m.match==="startsWith"?T.startsWith(C):T.includes(C)}));if($.length>1)throw new Error(`varias opciones coinciden (${$.length})`);M=$[0]}if(!M)throw new Error("opci\xF3n no encontrada");await x.selectOption({value:M.value},{timeout:_()});return}case"check":{await(await I()).setChecked(await p(m.checked),{timeout:_()});return}case"wait":{if(m.ms!==void 0){if(m.ms>_())throw new Error("timeout");await w.waitForTimeout(m.ms)}m.target&&await(await I()).waitFor({state:"visible",timeout:_()});return}case"extract":{let k=await I(),x=_(),b;switch(m.as){case"text":b=await k.innerText({timeout:x});break;case"value":b=await k.inputValue({timeout:x});break;case"attribute":b=await k.getAttribute(m.attribute??"",{timeout:x});break;case"html":b=await k.innerHTML({timeout:x});break;default:b=null}P[m.key]=zt(b);return}default:return}}async function p(m){if(typeof m=="boolean")return m;let w=o(m);if(w==="true")return!0;if(w==="false")return!1;throw new Error("checked debe ser true o false")}}var Kr=250;async function Oi(e,t,n,r=0){let o=JSON.stringify([e,new URL(t).origin,...n,...r>0?[`#${r}`]:[]]),i=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o));return Array.from(new Uint8Array(i),s=>s.toString(16).padStart(2,"0")).join("")}async function Xt(e,t,n){for(let r of[t.locator,...t.fallbacks??[]])try{if(await j(Ue(e,r).count(),n)>0)return!0}catch{}return!1}async function Mi(e,t,n,r){for(;;){if(await Xt(e,t,r))return"login";if(await Xt(e,n,r))return"session";let o=r-Date.now();if(o<=0)throw new Error("no se encontr\xF3 ni el login ni la p\xE1gina posterior al login");await e.waitForTimeout(Math.min(Kr,o))}}function Qt(e,t){let n=JSON.stringify(e).slice(1,-1),r=new TextEncoder,o=[...n.matchAll(/([A-Za-z\u00C0-\u024F]+)(\s*)/g)].filter(d=>d[1].length>=3&&d[2].length>0).map(d=>({start:d.index,end:d.index+d[0].length,bytes:r.encode(d[0]).length})),i=[{end:0,encodedEnd:0,bytes:0}];for(let d of e){let c=i[i.length-1],l=JSON.stringify(d).slice(1,-1);i.push({end:c.end+d.length,encodedEnd:c.encodedEnd+l.length,bytes:c.bytes+r.encode(l).length})}let s=[],a=0,u=0;for(let d=0;d<i.length;d++){let c=i[d];for(;a<o.length&&o[a].end<=c.encodedEnd;)u+=o[a++].bytes;let l=o[a];l&&l.start<c.encodedEnd&&c.encodedEnd<l.end||s.push({index:d,hundredths:c.bytes*93-u*(93-(t==="clef-omni"?23:20))})}return{boundaries:i,cuts:s}}var Ve=Symbol("clefTruncationWarning");function Di(e,t){let n=be(e);if(n.length)throw new Error(n.join("; "));let r={model:e.model,state:{message:t.message,history:t.history.map(o=>({role:o.role,text:o.text})),vars:Object.fromEntries(Object.entries(t.vars))},questions:Object.fromEntries([["route",{type:"choice",instructions:e.question,criteria:Object.fromEntries(e.options.map(o=>[o.id,o.criteria]))}],...e.checks.map(o=>[o.id,o.type==="score"?{type:o.type,instructions:o.instructions,criteria:o.levels}:{type:o.type,instructions:o.instructions,...o.criteria?{criteria:o.criteria}:{}}])])};return nn(r,Math.floor(V[e.model].contextWindow*.9))}function nn(e,t){e.state={message:e.state.message,history:e.state.history.slice(),vars:Object.fromEntries(Object.entries(e.state.vars))};let n=ne(e);if(n<=t)return e;let r={...e,state:{message:"",history:[],vars:{}}};if(ne(r)>t)throw new Error("Classifier questions exceed the Clef context budget");let o=()=>ne(e)<=t,i=0,s=0,a=!1,u=e.state.history;if(u.length){let l=0,p=u.length;for(;l<p;){let m=Math.floor((l+p)/2);e.state.history=u.slice(m),o()?p=m:l=m+1}i=l,e.state.history=u.slice(i)}let d=Object.entries(e.state.vars).sort((l,p)=>(JSON.stringify(p[1])??"").length-(JSON.stringify(l[1])??"").length);for(let[l,p]of d){if(o())break;s++,typeof p=="string"?(e.state.vars[l]="",o()?e.state.vars[l]=en(p,e.model,t,ne(e)):delete e.state.vars[l]):delete e.state.vars[l]}if(!o()){let l=e.state.message;e.state.message="",e.state.message=en(l,e.model,t,ne(e)),a=e.state.message!==l}if(!o())throw new Error("Classifier request exceeds the Clef context budget");let c=`Classifier: context trimmed for ${e.model} (${V[e.model].contextWindow} token limit, budget ${t}); history removed: ${i}; vars shortened/removed: ${s}; message tail shortened: ${a}; estimated tokens ${n} -> ${ne(e)}`;return rn(e,c),e}function en(e,t,n,r){let{boundaries:o,cuts:i}=Qt(e,t),s=l=>r+Math.ceil(l/100)<=n,a=0,u=i.length-1;for(;a<u;){let l=Math.ceil((a+u)/2);s(i[l].hundredths)?a=l:u=l-1}let d=i[a],c=d.index;if(a+1<i.length){let l=d.index,p=i[a+1].index-1;for(;l<p;){let m=Math.ceil((l+p)/2),w=d.hundredths+(o[m].bytes-o[d.index].bytes)*93;s(w)?l=m:p=m-1}c=l}return e.slice(0,o[c].end)}function ne(e){let t=JSON.stringify({model:e.model,state:e.state,questions:e.questions}),n=new TextEncoder,r=n.encode(t).length,o=0;for(let a of t.matchAll(/([A-Za-z\u00C0-\u024F]+)(\s*)/g))a[1].length>=3&&a[2].length>0&&(o+=n.encode(a[0]).length);let i=Object.values(e.questions),s=0;for(let a of i)Array.isArray(a==null?void 0:a.criteria)?s+=a.criteria.length:a!=null&&a.criteria&&typeof a.criteria=="object"&&(s+=Object.keys(a.criteria).length);return Math.ceil(o*(e.model==="clef-omni"?.23:.2)+(r-o)*.93+i.length*45+s*11)+256}function rn(e,t){Object.defineProperty(e,Ve,{value:[e[Ve],t].filter(Boolean).join("; "),configurable:!0})}function Br(e){var i;let t=e&&typeof e=="object"?e:void 0,n=typeof(t==null?void 0:t.message)=="string"?t.message:typeof e=="string"?e:"",r=Number((t==null?void 0:t.code)??((i=n.match(/code[\s:="']*(3030|5021)\b/i))==null?void 0:i[1])),o=n.match(/Request requires (\d+) tokens; the maximum is (\d+)/i)??n.match(/tokens\s*\((\d+)\).*context window limit\s*\((\d+)\)/i);if(!(r!==5021&&!(r===3030&&o))){if(o){let s=Number(o[1]),a=Number(o[2]);if(Number.isFinite(s)&&Number.isFinite(a)&&s>a&&a>0)return a/s}return r===5021?.5:void 0}}function qi(e){return e[Ve]}async function Hi(e,t,n,{timeoutMs:r=3e4}={}){if(!Number.isFinite(r)||r<=0)throw new Error("Invalid Clef timeout");let o,i=new AbortController,s=()=>e.run(V[t].id,{model:n.model,state:n.state,questions:n.questions},{signal:i.signal}),a=async()=>{try{return await s()}catch(u){let d=Br(u);if(d===void 0||i.signal.aborted)throw u;let c=Math.floor(Math.min(V[t].contextWindow*.9,ne(n)*d*.9));if(rn(n,`Classifier: context retry 1/1; scaled budget ${c}`),nn(n,c),i.signal.aborted)throw new Error("Clef timeout");return await s()}};try{return await Promise.race([a(),new Promise((u,d)=>{o=setTimeout(()=>{d(new Error("Clef timeout")),i.abort()},r)})])}finally{o!==void 0&&clearTimeout(o)}}function re(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Clef response object");return e}function Ee(e){if(typeof e!="number"||!Number.isFinite(e)||e<0||e>1)throw new Error("Invalid Clef probability");return e}function tn(e,t){let n=re(e);if(Object.keys(n).length!==t.length||t.some(i=>!Object.hasOwn(n,i)))throw new Error("Invalid Clef probability options");let r=Object.fromEntries(t.map(i=>[i,Ee(n[i])])),o=Object.values(r).reduce((i,s)=>i+s,0);if(Math.abs(o-1)>.02)throw new Error("Invalid Clef probability sum");return r}function Ui(e,t){let n=re(e),r=re(n.answers),o=re(r.route);if(o.type!=="choice"||typeof o.choice!="string"||!t.options.some(c=>c.id===o.choice))throw new Error("Invalid Clef route choice");let i=tn(o.probabilities,t.options.map(c=>c.id)),s=Object.values(i).sort((c,l)=>l-c);if(i[o.choice]!==s[0])throw new Error("Clef choice is not the highest probability");let a={classification:o.choice,label:t.options.find(c=>c.id===o.choice).label,confidence:Ee(o.confidence),margin:s[0]-s[1],probabilities:i,route:"class",checks:Object.fromEntries(t.checks.map(c=>{if(!Object.hasOwn(r,c.id))throw new Error(`Missing Clef answer: ${c.id}`);let l=re(r[c.id]);if(l.type!==c.type)throw new Error(`Invalid Clef answer type: ${c.id}`);if(c.type==="noul")return[c.id,Ee(l.noul)];let p=re(l.legend),m=c.levels.map((P,R)=>String(R));if(m.some(P=>typeof p[P]!="string"))throw new Error("Invalid Clef score legend");let w=tn(l.probabilities,m);if(typeof l.score!="number"||!Number.isFinite(l.score)||l.score<0||l.score>c.levels.length-1)throw new Error("Invalid Clef score");let O=m.reduce((P,R)=>w[P]>=w[R]?P:R);return[c.id,{score:l.score,level:c.levels[Number(O)],confidence:Ee(l.confidence),probabilities:w}]}))};t.checks.some(c=>c.type==="noul"&&c.guard&&Number(a.checks[c.id])>c.guard.threshold)?a.route="blocked":(a.confidence<t.confidence.threshold||a.margin<t.confidence.margin)&&(a.route="uncertain");let d=re(n.usage).input_tokens;if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error("Invalid Clef input usage");return{result:a,usage:{promptTokens:d,completionTokens:0,totalTokens:d}}}function Vi(){return{classification:"",label:"",confidence:0,margin:0,probabilities:{},route:"error",checks:{}}}function Ki(e,t,n){var s,a;let r=e.filter(u=>u.type==="text"&&typeof u.content=="string"&&(u.role==="user"||u.role==="assistant"));((s=r.at(-1))==null?void 0:s.role)==="user"&&((a=r.at(-1))==null?void 0:a.content)===n&&r.pop();let o=r.length,i=0;for(let u=r.length-1;u>=0&&t>0&&!(r[u].role==="user"&&(o=u,++i===t));u--);return r.slice(o).map(u=>({role:u.role,text:u.content}))}var Be=["temperature","topP","topK","frequencyPenalty","presencePenalty","maxOutputTokens","seed","stopSequences","maxRetries"],on=["temperature","topP","topK","frequencyPenalty","presencePenalty"],sn={precise:{temperature:.3,topP:.9,topK:30},balanced:{temperature:.8,topP:1,topK:50},creative:{temperature:1.1,topP:.95,topK:80}},zr=1e-6,Ke={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 Jr(e){return/^gpt-5/i.test(e)}function Ae(e){let t=e.contextWindow??128e3;return e.provider==="openai"?Jr(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}}:{...Ke,maxOutputTokens:{max:t}}:e.provider==="xai"?{...Ke,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}}:{...Ke,maxOutputTokens:{max:t}}}function Se(e,t){if(e==="maxRetries")return!0;let n=t[e];return n===!1?!1:e==="seed"?n===!0:n!==void 0}function Zr(e,t,n){return Math.min(n,Math.max(t,e))}function Yr(e,t){return e===void 0&&t===void 0?!0:e===void 0||t===void 0?!1:Math.abs(e-t)<zr}function zi(e,t){for(let n of["precise","balanced","creative"]){let r=sn[n],o=!0;for(let i of on){if(t&&!Se(i,t))continue;let s=r[i],a=e[i];if(s!==void 0){if(typeof s=="number"&&typeof a=="number"){if(!Yr(a,s)){o=!1;break}}else if(a!==s){o=!1;break}}}if(o)return n}return"custom"}function Ji(e,t){let n=sn[e],r={};for(let o of on){if(t&&!Se(o,t))continue;let i=n[o];i!==void 0&&(r[o]=i)}return r}function Zi(e){if(!e)return{};let t={};for(let n of Be){let r=e[n];r!==void 0&&(n==="stopSequences"?Array.isArray(r)&&(t.stopSequences=r.filter(o=>typeof o=="string")):n==="maxRetries"?typeof r=="number"&&(t.maxRetries=r):typeof r=="number"&&(t[n]=r))}return t}function Yi(e,t,n){var s;let r={...e,...t},o=[],i={};for(let a of Be){let u=r[a];if(u===void 0)continue;if(a==="maxRetries"){i.maxRetries=u;continue}if(!Se(a,n)){o.push({key:a,action:"stripped",detail:"unsupported by model"});continue}if(a==="stopSequences"){let c=u,l=((s=n.stopSequences)==null?void 0:s.max)??c.length;c.length>l?(i.stopSequences=c.slice(0,l),o.push({key:a,action:"clamped",detail:`truncated to ${l} sequences`})):i.stopSequences=c;continue}if(a==="seed"){i.seed=u;continue}let d=n[a];if(d&&typeof d=="object"&&"min"in d){let c=u,l=Zr(c,d.min,d.max);i[a]=l,l!==c&&o.push({key:a,action:"clamped",detail:`clamped from ${c} to ${l}`})}else if(a==="maxOutputTokens"){let c=u,l=n.maxOutputTokens.max,p=Math.min(c,l);i.maxOutputTokens=p,p!==c&&o.push({key:a,action:"clamped",detail:`clamped from ${c} to ${p}`})}}return{effectiveParams:i,adjustments:o}}function Xi(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 Qi(e=128e3){return Ae({provider:"openai",providerModel:"gpt-4.1",contextWindow:e})}function es(e=2e6){return Ae({provider:"openai",providerModel:"gpt-5-nano",contextWindow:e})}function ts(e=256e3){return Ae({provider:"xai",providerModel:"grok-4-fast",contextWindow:e})}function ns(e=128e3){return Ae({provider:"cloudflare",providerModel:"@cf/meta/llama-3.2-3b-instruct",contextWindow:e})}function rs(e,t){let n={...e};for(let r of Be)r==="maxRetries"||n[r]===void 0||Se(r,t)||delete n[r];return n}var Xr=["none","minimal","low","medium","high","xhigh"],Qr=e=>typeof e=="string"&&Xr.includes(e);function is(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 eo(e){return e.kind!=="effort"?[]:e.levels??[]}var to=e=>e===!0||e==="true";function ss(e){return e.kind==="tag"?!0:e.kind==="effort"?to(e.exposesReasoning):!1}function as(e,t){if(e.kind!=="effort")return;let n=eo(e);if(Qr(t)&&n.includes(t))return t;if(e.defaultLevel&&n.includes(e.defaultLevel))return e.defaultLevel}function ds(e,t){let{effort:n,exposeReasoning:r,maxTokens:o}=t;if(e==="openai"){let i={};return n&&(i.reasoningEffort=n),r&&(i.reasoningSummary="auto"),Object.keys(i).length?{openai:i}:void 0}if(e==="xai")return n?{xai:{reasoningEffort:n}}:void 0;if(e==="openrouter"){if(!o&&!n)return;let i={};return r!==void 0&&(i.exclude=!r),o?{openrouter:{reasoning:{...i,max_tokens:o}}}:{openrouter:{reasoning:{...i,effort:n}}}}if(e==="anthropic"){let i={};return(n||r)&&(i.thinking={type:"adaptive",...r?{display:"summarized"}:{}}),n&&(i.effort=n),Object.keys(i).length?{anthropic:i}:void 0}}export{no as a,oo as b,an as c,io as d,so as e,V as f,F as g,ot as h,it as i,fn as j,pn as k,at as l,ct as m,co as n,lo as o,S as p,z as q,kn as r,po as s,ft as t,mo as u,ve as v,N as w,mt as x,gt as y,ht as z,yt as A,xt as B,kt as C,Eo as D,Re as E,be as F,Tn as G,Pn as H,Te as I,Pe as J,Cn as K,On as L,No as M,Mn as N,Wn as O,St as P,$t as Q,vo as R,Ro as S,Ln as T,Gn as U,Io as V,To as W,Ct as X,Ot as Y,vt as Z,Mo as _,Bn as $,Ko as aa,Bo as ba,Mt as ca,zo as da,Ft as ea,Dt as fa,Xo as ga,lr as ha,Qo as ia,ti as ja,ri as ka,ii as la,Wr as ma,_i as na,ki as oa,jr as pa,xi as qa,Lr as ra,He as sa,Ei as ta,Ai as ua,ge as va,Bt as wa,zt as xa,Ue as ya,Jt as za,j as Aa,Zt as Ba,Yt as Ca,qr as Da,Ni as Ea,Ti as Fa,Oi as Ga,Xt as Ha,Mi as Ia,Di as Ja,ne as Ka,qi as La,Hi as Ma,Ui as Na,Vi as Oa,Ki as Pa,Be as Qa,on as Ra,sn as Sa,Ae as Ta,zi as Ua,Ji as Va,Zi as Wa,Yi as Xa,Xi as Ya,Qi as Za,es as _a,ts as $a,ns as ab,rs as bb,Xr as cb,is as db,eo as eb,ss as fb,as as gb,ds as hb};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Aa as I,ya as D}from"./chunk-G73VSMK7.js";var Y={};function F(x){}var j={};function U(x,b){let w=Object.hasOwn(j,x)?j[x]:void 0;return w===void 0||!!b&&w.includes(b)}async function ee(x,{deadline:b,maxElements:w=120}){let W=Math.max(0,Math.floor(w)),_=await I(x.evaluate(({limit:h,deadline:T})=>{let a=[],q="input:not([type=hidden]),textarea,select,button,a[href],[role=button],[role=link],[role=checkbox],[role=radio],[role=combobox],[role=listbox],[role=textbox],[role=tab],[role=menuitem],[role=option],[contenteditable=true]",l=r=>(r??"").replace(/\s+/g," ").trim(),K=r=>{let i=n=>{if(!n||!n.checkVisibility()||["input","textarea","select","button"].includes(n.localName)||["combobox","listbox"].includes(n.getAttribute("role")??""))return"";let d=getComputedStyle(n);return d.display==="none"||d.visibility==="hidden"||d.visibility==="collapse"||Number(d.opacity)===0?"":l(n.innerText).slice(0,60).replace(/[\s*:]+$/g,"")},t=i(r.previousElementSibling);if(t)return t;let e=r.closest("td, th"),o=e==null?void 0:e.previousElementSibling;return o&&["td","th"].includes(o.localName)&&o.parentElement===(e==null?void 0:e.parentElement)?i(o):""},v=r=>{let i=[],t=r;for(;t;){let e=t.parentElement,o=Array.from(e?e.children:t.getRootNode().children).filter(d=>d.tagName===t.tagName);if(i.unshift(`${t.localName}:nth-of-type(${o.indexOf(t)+1})`),e){t=e;continue}let n=t.getRootNode();return n instanceof ShadowRoot?`${v(n.host)} >> ${i.join(" > ")}`:i.join(" > ")}return i.join(" > ")},L=r=>{let i=getComputedStyle(r),t=r.getBoundingClientRect();return!(i.visibility==="hidden"||i.visibility==="collapse"||i.display==="none"||Number(i.opacity)===0||t.width<=0||t.height<=0||t.bottom<=0||t.right<=0||t.top>=innerHeight||t.left>=innerWidth||!r.checkVisibility())},R=r=>{var i,t;for(let e of r.querySelectorAll("*")){if(a.length>=h||Date.now()>=T)return;if(e.matches(q)){let o=e.localName,n=l(e.getAttribute("type")).toLowerCase()||(o==="input"?"text":""),y=o==="input"&&["radio","checkbox"].includes(n)&&!L(e)?Array.from(e.labels??[]).find(L)??null:null;if(!y&&!L(e))continue;let p=(y??e).getBoundingClientRect(),J=o==="button"?"button":o==="a"?"link":o==="select"?e instanceof HTMLSelectElement&&e.multiple?"listbox":"combobox":o==="textarea"?"textbox":o==="input"?["checkbox","radio"].includes(n)?n:["button","submit","reset"].includes(n)?"button":n==="number"?"spinbutton":n==="search"?"searchbox":n==="password"?"":"textbox":"",c=l(e.getAttribute("role"))||J,m=o==="select"?"select":["checkbox","radio"].includes(c)||["button","link"].includes(c)?c:o==="textarea"||e.getAttribute("contenteditable")==="true"||c==="textbox"||o==="input"&&["text","email","password","number","search","tel","url"].includes(n)?"text":"other",H=e.labels,f=l(H?Array.from(H).map(u=>u.innerText).join(" "):"")||l((i=e.closest("label"))==null?void 0:i.textContent),g=l(e.getAttribute("placeholder")),k=o==="select"||c==="combobox"||c==="listbox",N=k&&!(e instanceof HTMLSelectElement)?e.querySelector("[role=option][aria-selected=true]")??r.getElementById(e.getAttribute("aria-activedescendant")??""):null,E=(k?e instanceof HTMLSelectElement?l((t=e.selectedOptions[0])==null?void 0:t.label):l(N==null?void 0:N.innerText):l(e.innerText)).slice(0,80),V=l((e.getAttribute("aria-labelledby")??"").split(/\s+/).map(u=>{var P;return((P=r.getElementById(u))==null?void 0:P.textContent)??""}).join(" ")),M=l(e.getAttribute("title")),O=(k||m==="text")&&!f?K(e):"",A=l(e.getAttribute("aria-label"))||V||f||(k?M||O:(m==="text"?M||O:"")||g||E||M||(m==="button"?l(e.value):"")),s=[];if(y){e.id&&s.push({by:"css",value:`label[for=${JSON.stringify(e.id)}]`});let u=l(y.innerText);u&&s.push({by:"text",value:u,exact:!0}),s.push({by:"css",value:v(y)}),a.push({kind:m,tag:o,type:n,role:c,name:A,label:f,placeholder:g,text:E,checked:e.checked,box:{x:p.x,y:p.y,width:p.width,height:p.height},candidates:s});continue}let C=e.getAttribute("data-testid");C&&s.push({by:"testId",value:C}),c&&A&&s.push({by:"role",role:c,name:A,exact:!0}),f&&s.push({by:"label",value:f,exact:!0}),g&&s.push({by:"placeholder",value:g,exact:!0}),E&&(m==="button"||m==="link")&&s.push({by:"text",value:E,exact:!0}),e.id&&!/[0-9]{4,}|[a-f0-9]{8,}|[:]/i.test(e.id)&&r.querySelectorAll(`#${CSS.escape(e.id)}`).length===1&&s.push({by:"css",value:`#${CSS.escape(e.id)}`});let $=e.getAttribute("name");$&&s.push({by:"css",value:`${o}[name=${JSON.stringify($)}]`}),s.push({by:"css",value:v(e)}),a.push({kind:m,tag:o,...n?{type:n}:{},...c?{role:c}:{},name:A,label:f,placeholder:g,text:E,...e instanceof HTMLSelectElement?{options:Array.from(e.options).slice(0,50).map(u=>({value:u.value,label:u.label}))}:{},...["checkbox","radio"].includes(m)?{checked:e.checked??e.getAttribute("aria-checked")==="true"}:{},box:{x:p.x,y:p.y,width:p.width,height:p.height},candidates:s})}e.shadowRoot&&R(e.shadowRoot)}};return R(document),a},{limit:W,deadline:b}),b),B={text:["fill","click","extract","wait"],select:["select","extract","wait"],checkbox:["check","click","wait"],radio:["check","click","wait"],button:["click","extract","wait"],link:["click","extract","wait"],other:["extract","wait"]},S=[];for(let h of _.slice(0,W)){if(Date.now()>=b)break;let T=(await Promise.all(h.candidates.map(async a=>{try{return await I(D(x,a).count(),b)===1?a:null}catch{return null}}))).filter(a=>a!==null);T.length&&S.push({...h,id:`e${S.length+1}`,candidates:T,ops:B[h.kind]})}return{elements:S}}export{Y as a,F as b,j as c,U as d,ee as e};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var g=(u=>(u.START_NODE="startNode",u.CLASSIFIER_NODE="classifierNode",u.MEMO_NODE="memoNode",u.LLM_NODE="llmNode",u.ANSWER_NODE="answerNode",u.API_NODE="apiNode",u.TOOL_NODE="toolNode",u.WORKER_NODE="workerNode",u.CRAWL_NODE="crawlNode",u.WEB_ACTIONS_NODE="webActionsNode",u))(g||{});var F=/^[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||!F.test(s)||r.has(s))continue;r.add(s);let i=C.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 T(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],c=T(i)?s.default:i;if(T(c)){s.required&&r.push(`"${s.label||s.name}" is required`);continue}let{value:l,error:a}=P(s,c);a?r.push(a):n[s.name]=l}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 C=["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":case"webActionsNode":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 R(e){return e.type!=="startNode"?[]:m(e.data).map(t=>({name:t.name,path:t.name,type:t.type==="json"?"object":t.type}))}function $(e){var o;let t=[...N(e.type),...R(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),...R(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 c=e.find(l=>l.id===i);if(c)for(let l of L(c,d(c))){let a=c.type==="startNode"&&l.source==="default"?l.name:`${c.id}.${l.name}`;s.has(a)||(s.add(a),o.push({...l,ref:a,nodeId:c.id}))}}return o}function ae(e,t,n){return new Set(j(e,t,n).map(r=>r.ref))}function I(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 v(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"]),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 B=new Set(["apiNode","toolNode","workerNode"]);function J(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&&B.has(n)){let o=w(J(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 X(e,t){var r,o,s,i,c,l,a;if(Object.prototype.hasOwnProperty.call(t.refOverrides??{},e))return{value:t.refOverrides[e]};let n=t.nodes.find(u=>u.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"&&((c=n==null?void 0:n.data)==null?void 0:c.allow_documents)===!0)return{value:(l=t.context)==null?void 0:l.files};if(n&&m(n.data).some(u=>u.name===e))return{value:(a=t.context)==null?void 0:a[e]}}function A(e,t){var S;let n=e.trim();if(!n)throw new f("INVALID_EXPRESSION","Variable reference is empty");let r=n.includes(".")?void 0:X(n,t);if(r)return r;if(!n.includes("."))throw new f("UNKNOWN_CONTEXT_REF",`Unknown run-context variable "${n}"`);let o=I(n,t);if(!o)throw new f("OUT_OF_SCOPE",`Variable "${n}" is not in this node's connection scope`);let s=v(n,o.id),[i,...c]=s.split("."),l=d(o).find(D=>D.name===i);if(!l)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=(S=t.results)==null?void 0:S[o.id];if(a==null)return{value:void 0,missing:"ancestor_not_executed"};let u=b(a,l,o.type),p=c.length>0?w(u,c.join(".")):u;return p==null?{value:void 0,missing:"path_not_found"}:{value:p}}function Ee(e,t){return A(e,t).value}function q(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 K(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 V(e){let{ref:t,rawDefault:n}=q(e.trim());if(!t)throw new f("INVALID_EXPRESSION","Template expression is missing a variable reference");return{ref:t,...n===void 0?{}:{defaultValue:K(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(V(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,(c,l)=>{try{let a=V(l);if(a.ref.startsWith("secrets.")){let p=a.ref.slice(8);if(!Object.prototype.hasOwnProperty.call(n.secrets??{},p))throw new f("MISSING_SECRET",`Secret "${p}" is not defined for this tenant`);return _(n.secrets[p],o)}let u=A(a.ref,n);if(u.missing){if(a.defaultValue!==void 0)return _(a.defaultValue,o);let p=u.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(u.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",p)}return _(u.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,F as b,m as c,Z as d,G as e,O as f,N as g,$ as h,d as i,x as j,j as k,ae as l,I as m,v as n,ue as o,U as p,E as q,le as r,f as s,w as t,b as u,Ne as v,A as w,Ee as x,V as y,_e as z,ye as A,he as B};
|