@hugex/ai 3.4.0 → 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
package/dist/chunk-YXG3ZEUP.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{A as we,a as De,b as qe,g as He,h as Ue,k as Ke,o as Ve,s as ze,w as Je,y as ce}from"./chunk-KKJW6HJA.js";var yr={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 _r(e){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t}catch{}return{text:e}}var Gt=256;function br(e){if(typeof e!="string")return null;let t=e.trim();return t?t.slice(0,Gt):null}function wr(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 W={"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}},v={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}},Ze={uncertain:"source-__uncertain",blocked:"source-__blocked",error:"source-__error"};function Be(e,t){return e==="class"&&t!==void 0?`source-${t}`:Object.hasOwn(Ze,e)?Ze[e]:`source-${e}`}var Qe={enum:["startNode","classifierNode","memoNode","llmNode","answerNode","apiNode","toolNode","workerNode","crawlNode"]},Wt={type:"string",pattern:"^[A-Za-z0-9_-]{1,128}$"},et={type:"object",additionalProperties:!1,required:["x","y"],properties:{x:{type:"number"},y:{type:"number"}}},Ft={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}}},Lt={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}$"}}},Dt={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"}}}},qt={nodeType:Qe,nodeId:Wt,position:et,node:Ft,edge:Lt,graph:Dt},Ht={$schema:"https://json-schema.org/draft/2020-12/schema",$defs:qt,$ref:"#/$defs/graph"},Ut={type:"string",pattern:"^[A-Za-z0-9_-]{1,128}$"},Kt={type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,63}$"},Vt={type:"string",pattern:"^(source-)?[A-Za-z0-9_.-]{1,100}$"},zt={type:"object",maxProperties:100},Ye={type:"object",additionalProperties:!1,required:["node"],properties:{node:{$ref:"#/$defs/existingId"},handle:{$ref:"#/$defs/handle"}}},Xe={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:Qe,existingId:Ut,newId:Kt,handle:Vt,position:et,data:zt,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:Ye,to:Ye}},{type:"object",additionalProperties:!1,required:["op","type","between"],properties:{op:{const:"insert_node"},type:{enum:["memoNode","llmNode","apiNode","toolNode","workerNode","crawlNode"]},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 oe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Jt(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"?oe(t):!1)}function Zt(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(!oe(n)||!Object.prototype.hasOwnProperty.call(n,o))return;n=n[o]}return n}function tt(e,t,n=e){let r=[];return F(e,t,"",n,r,0),r}function F(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=Zt(r,s.$ref);if(!oe(a)){o.push(`${n||"/"}: unresolved ${s.$ref}`);return}F(a,t,n,r,o,i+1);return}if(s.not){let a=[];F(s.not,t,n,r,a,i+1),a.length===0&&o.push(`${n||"/"}: not`)}if(s.oneOf){let a=s.oneOf.filter(d=>{let u=[];return F(d,t,n,r,u,i+1),u.length===0}).length;a!==1&&o.push(`${n||"/"}: oneOf matched ${a}`)}if(s.anyOf&&(s.anyOf.some(d=>{let u=[];return F(d,t,n,r,u,i+1),u.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&&!Jt(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,d)=>F(s.items,a,`${n}/${d}`,r,o,i+1))),oe(t)){let a=s.properties??{},d=Object.keys(t);s.maxProperties!==void 0&&d.length>s.maxProperties&&o.push(`${n||"/"}: maxProperties`);for(let u of s.required??[])Object.prototype.hasOwnProperty.call(t,u)||o.push(`${n||"/"}: required ${u}`);for(let[u,l]of Object.entries(s.dependentRequired??{}))if(Object.prototype.hasOwnProperty.call(t,u))for(let c of l)Object.prototype.hasOwnProperty.call(t,c)||o.push(`${n||"/"}: dependentRequired ${c}`);if(s.additionalProperties===!1)for(let u of d)Object.prototype.hasOwnProperty.call(a,u)||o.push(`${n||"/"}: additionalProperty ${u}`);for(let u of d){let l=a[u];l?F(l,t[u],`${n}/${u}`,r,o,i+1):oe(s.additionalProperties)&&F(s.additionalProperties,t[u],`${n}/${u}`,r,o,i+1)}}}function Bt(){let e=Xe.properties.ops;return{$defs:Xe.$defs,type:e.type,minItems:e.minItems,maxItems:e.maxItems,items:e.items}}function nt(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 Er(e){let t=tt(Ht,e);if(t.length)return{ok:!1,issues:nt(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 Nr(e){let t=tt(Bt(),e);return t.length?{ok:!1,issues:nt(t,"op_invalid",!0)}:{ok:!0,ops:structuredClone(e)}}var b={source:"all",limit:5,depth:2,render:!1,format:"markdown",includeSubdomains:!1,waitTimeoutMs:6e4,maxAgeS:86400,maxCharsPerPage:4e3},q={limit:50,depth:10,waitTimeoutMs:12e4,maxAgeS:604800,maxOutputBytes:256*1024};function ie(e,t,n,r=0){return Math.min(n,Math.max(r,Math.floor(typeof e=="number"&&Number.isFinite(e)?e:t)))}function Yt(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??b.format;return{url:r.href,source:e.source??b.source,limit:ie(e.limit,b.limit,q.limit,1),depth:ie(e.depth,b.depth,q.depth),render:e.render??b.render,formats:[o],...o==="json"?{jsonOptions:{...e.jsonPrompt!==void 0?{prompt:e.jsonPrompt}:{},...e.jsonSchema!==void 0?{response_format:e.jsonSchema}:{}}}:{},maxAge:ie((n==null?void 0:n.maxAgeOverrideS)??e.maxAgeS,b.maxAgeS,q.maxAgeS),options:{includeExternalLinks:!1,includeSubdomains:e.includeSubdomains??b.includeSubdomains,includePatterns:e.includePatterns??[],excludePatterns:e.excludePatterns??[]}}}function ke(e){return Array.isArray(e)?e.map(ke):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,ke(n)])):e}async function Ar(e){let t=new TextEncoder().encode(JSON.stringify(ke(e))),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}function Xt(e,t){let n=t.split(/(\*\*|\*)/).map(r=>r==="**"?".*":r==="*"?"[^/]*":r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("");return new RegExp(`^${n}$`).test(e)}function rt(e,t,n){let r=(t==null?void 0:t.mode)??"pages",o=(t==null?void 0:t.fields)??["url","title",n],i=ie(t==null?void 0:t.maxCharsPerPage,b.maxCharsPerPage,q.maxOutputBytes),s=e;if(r==="single"){let l=t==null?void 0:t.select,c=(l==null?void 0:l.url)!==void 0?e.find(p=>p.url===l.url):(l==null?void 0:l.pattern)!==void 0?e.find(p=>Xt(p.url,l.pattern)):e[(l==null?void 0:l.index)??0];s=c?[c]:[]}let a=!1,d=s.map(l=>{let c={url:l.url,status:l.status};l.httpStatus!==void 0&&(c.httpStatus=l.httpStatus),o.includes("title")&&l.title!==void 0&&(c.title=l.title);let p=l.truncated??!1;if(o.includes("markdown")&&l.markdown!==void 0&&(c.markdown=l.markdown.slice(0,i),p||=c.markdown.length<l.markdown.length),o.includes("json")&&l.json!==void 0){let h=l.truncated&&typeof l.json=="string"?l.json:JSON.stringify(l.json);c.json=h.length>i?h.slice(0,i):l.json,p||=h.length>i}return p&&(c.truncated=!0),a||=p,c});if(r!=="concat")return{pages:d,truncated:a};let u=d.map(l=>o.map(c=>{let p=l[c];return p===void 0?"":typeof p=="string"?p:JSON.stringify(p)}).filter(Boolean).join(`
|
|
2
|
-
`)).join(`
|
|
3
|
-
|
|
4
|
-
`);return{pages:[],text:u,truncated:a}}var ot=e=>new TextEncoder().encode(JSON.stringify(e)).byteLength;async function $r(e,t,n){var j,L,We;let r=Date.now(),o=r+ie(t.waitTimeoutMs,b.waitTimeoutMs,q.waitTimeoutMs),i=n.fetchImpl??fetch,s=n.sleep??(E=>new Promise(I=>setTimeout(I,E))),a=n.resumeJobId??null,d={status:"running"},u=[],l=!1,c=2,p=()=>Math.max(0,o-Date.now()),h=async E=>{if(!p())throw new Error("timeout");if(await s(Math.min(E,p())),!p())throw new Error("timeout")},$=async(E,I)=>{var M,R,k,D,N;for(let G=0;;G++){if(!p())throw new Error("timeout");let x=new AbortController,ne,re=new Promise((S,Y)=>{ne=setTimeout(()=>{x.abort(),Y(new Error("timeout"))},p())});try{let S=await Promise.race([i(E,{...I,signal:x.signal,headers:{Authorization:`Bearer ${e.apiToken}`,"Content-Type":"application/json"}}),re]);if(S.status===429&&G<2){let le=S.headers.get("Retry-After"),Fe=le===null?NaN:Number(le),Le=Number.isFinite(Fe)?Math.max(0,Fe*1e3):le?Math.max(0,Date.parse(le)-Date.now()):2e3;await((M=S.body)==null?void 0:M.cancel()),clearTimeout(ne),await h(Number.isFinite(Le)?Le:2e3);continue}let Y=await Promise.race([S.json(),re]);if(Y.success===!1)throw new Error(((k=(R=Y.errors)==null?void 0:R[0])==null?void 0:k.message)??"Crawl API error");if(!S.ok)throw new Error(((N=(D=Y.errors)==null?void 0:D[0])==null?void 0:N.message)??`Crawl API HTTP ${S.status}`);if(!p())throw new Error("timeout");return Y}catch(S){throw x.signal.aborted||!p()?new Error("timeout"):S}finally{clearTimeout(ne)}}},ue=(E,I)=>{let M=()=>rt(u.filter(D=>D.status==="completed"),t.output,t.format??"markdown"),R=M(),k={ok:E,error:I,data:a?{jobId:a,status:I==="timeout"?"running":d.status,total:d.total??0,finished:d.finished??0,browserSeconds:d.browserSecondsUsed??0,elapsedMs:Date.now()-r,...R,truncated:l||R.truncated}:null};for(;ot(k)>q.maxOutputBytes&&u.length;)u.pop(),R=M(),Object.assign(k.data,R,{truncated:!0});return{result:k,allPages:u}};try{if(!e.accountId||!e.apiToken)throw new Error("Crawl no configurado: faltan CF_ACCOUNT_ID / CF_BROWSER_RUN_TOKEN");let E=Yt(t,n.url,n),I=`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(e.accountId)}/browser-run/crawl`;if(!a){let N=await $(I,{method:"POST",body:JSON.stringify(E)});if(typeof N.result!="string"||!N.result)throw new Error("Crawl API returned no jobId");a=N.result}let M=`${I}/${encodeURIComponent(a)}`,R=2e3;do{let N=await $(`${M}?limit=1`);if(!N.result||typeof N.result!="object"||!N.result.status)throw new Error("Crawl API returned no status");if(d=N.result,d.status!=="running")break;await h(R),R=Math.min(5e3,R+1e3)}while(p());let k,D=new Set;do{let N=k===void 0?"":`?cursor=${encodeURIComponent(k)}`,G=await $(`${M}${N}`);if(!G.result||typeof G.result!="object")throw new Error("Crawl API returned invalid results");d={...d,...G.result};for(let x of G.result.records??[]){let ne={url:x.url,status:x.status,...((j=x.metadata)==null?void 0:j.title)!==void 0?{title:x.metadata.title}:{},...((L=x.metadata)==null?void 0:L.status)!==void 0?{httpStatus:x.metadata.status}:{},...x.markdown!==void 0?{markdown:x.markdown}:{},...x.json!==void 0?{json:x.json}:{}},re=rt([ne],{mode:"pages",maxCharsPerPage:(We=t.output)==null?void 0:We.maxCharsPerPage},t.format??"markdown").pages[0],S=ot(re)+1;if(c+S>q.maxOutputBytes){l=!0;break}u.push(re),c+=S}if(l)break;if(k=G.result.cursor,k!=null&&k!==""){if(D.has(String(k)))throw new Error("Crawl API repeated pagination cursor");D.add(String(k))}else k=void 0}while(k!==void 0);return ue(d.status==="completed",d.status==="completed"?null:d.status)}catch(E){return ue(!1,E instanceof Error?E.message:String(E))}}var it={startNode:{label:"Start",greeting:"",allow_images:!1,allow_documents:!1,inputs:[],memory_enabled:!1},classifierNode:{label:"Classifier",model:v.model,question:v.question,input:{message:v.input.message,historyTurns:v.input.historyTurns,vars:[...v.input.vars]},options:v.options.map(e=>({...e})),checks:[...v.checks],confidence:{...v.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:b.source,limit:b.limit,depth:b.depth,render:b.render,format:b.format,includeSubdomains:b.includeSubdomains,output:{mode:"pages",maxCharsPerPage:b.maxCharsPerPage},waitTimeoutMs:b.waitTimeoutMs,maxAgeS:b.maxAgeS}},Qt={"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."};function f(e,t,n){return{name:e,type:t,required:!1,persisted:!1,...n}}function en(e){return He(e).map(t=>({name:t.name,type:t.type,path:t.path??"",description:Qt[`${e}.${t.name}`]??t.name}))}function P(e,t){return{type:e,outputs:en(e),example:structuredClone(it[e]),...t}}var Or={startNode:P("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:P("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:P("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:P("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:P("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:P("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:P("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:P("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:P("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."})]})};function xe(e){return structuredClone(it[e])}var H=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),U=e=>typeof e=="string"&&e.trim().length>0,Ee=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1;function fe(e){if(!H(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(W,e.model))&&t.push("Classifier model is invalid"),(!U(e.question)||e.question.length>300)&&t.push("Classifier question is required and must be at most 300 characters"),(!H(e.input)||!U(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(U))&&t.push("Classifier input requires message, historyTurns (0\u201310), and variable refs"),(!H(e.confidence)||!Ee(e.confidence.threshold)||!Ee(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(!H(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"),(!U(o.label)||!U(o.criteria))&&t.push("Classifier option requires label and criteria")}for(let o of Array.isArray(e.checks)?e.checks:[]){if(!H(o)){t.push("Classifier check must be an object");continue}r(o.id,!0),U(o.instructions)||t.push("Classifier check instructions are required"),o.type==="noul"?(o.guard!==void 0&&(!H(o.guard)||!Ee(o.guard.threshold))&&t.push("Classifier guard threshold must be between 0 and 1"),o.criteria!==void 0&&(!H(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(U))&&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},nn={short:2e3,medium:5e3,long:2e4},Ne="medium",Se="gpt_5_nano",st=4;function rn(e){return e==="short"||e==="medium"||e==="long"?e:Ne}function on(e=Ne){return nn[e]}function Wr(e=Ne){return tn[e]}function sn(e){return e?Math.ceil(e.length/st):0}function an(e,t){if(!e)return{content:"",truncated:!1};if(sn(e)<=t)return{content:e,truncated:!1};let n=Math.max(0,t*st);return{content:e.slice(0,n),truncated:!0}}function at(e){let t=e==null?void 0:e.memory_enabled;return t===!0||t==="true"||t===1}function dt(e){let t=e==null?void 0:e.memory_model;return typeof t=="string"&&t.trim()?t.trim():Se}function Fr(e){return rn(e==null?void 0:e.memory_length)}function Lr(e,t){let n=on(e);return t&&t!=="none"?n+2048:n}var ut=/^(user|assistant|usuario|asistente|u|a)\s*:/i,dn=/^(hola|hello|hi|hey|buenas|buen[oa]s?\s+d[ií]as?|qu[eé]\s+tal|qu[eé]\s+haces)[\s,.!¡¿?]*$/i;function un(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=>ut.test(r));return n.length>=2&&n.length>=Math.ceil(t.length/2)}function ln(e){let t=e.split(`
|
|
6
|
-
`).map(n=>n.trim()).filter(Boolean).filter(n=>n!=="(empty)"&&n!=="(none)").filter(n=>!ut.test(n.replace(/^[-*]\s*/,"")));return un(t.join(`
|
|
7
|
-
`))?"":t.join(`
|
|
8
|
-
`)}function Dr(e){let t=e.trim();if(!t||dn.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 qr(e,t,n){let o=[...ln(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?"":an(o.map(i=>`- ${i}`).join(`
|
|
10
|
-
`),n).content}var ft=["template","user_template","url","body"],pt=["headers","args","body"],mt=["query_key","input_variable"];function A(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ie(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(ce(o).ref)}catch{n.push(o)}}return n}function Ae(e,t,n){if(typeof t=="string"){for(let r of Ie(t))e.push({field:n,ref:r});return}if(Array.isArray(t)){t.forEach((r,o)=>Ae(e,r,`${n}[${o}]`));return}if(A(t))for(let[r,o]of Object.entries(t))Ae(e,o,n?`${n}.${r}`:r)}function gt(e){let t=A(e.data)?e.data:{},n=[];for(let o of ft)if(!(o==="body"&&typeof t.body!="string")&&typeof t[o]=="string")for(let i of Ie(t[o]))n.push({field:o,ref:i});for(let o of pt)o==="body"&&typeof t.body=="string"||t[o]!==void 0&&Ae(n,t[o],o);for(let o of mt)typeof t[o]=="string"&&t[o]&&n.push({field:o,ref:t[o]});let r=t.input;return A(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)=>{A(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)=>{A(o)&&"from"in o&&typeof o.from=="string"&&o.from&&n.push({field:`inputs[${i}].from`,ref:o.from})}),n}function X(e,t,n){return typeof e=="string"&&e.startsWith(`${t}.`)?`${n}${e.slice(t.length)}`:e}function $e(e,t,n){return typeof e=="string"?we(e,t,n):Array.isArray(e)?e.map(r=>$e(r,t,n)):A(e)?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,$e(o,t,n)])):e}function yt(e,t,n){let r=structuredClone(e);for(let o of ft)o==="body"&&typeof r.body!="string"||typeof r[o]=="string"&&(r[o]=we(r[o],t,n));for(let o of pt)o==="body"&&typeof r.body=="string"||r[o]!==void 0&&(r[o]=$e(r[o],t,n));for(let o of mt)r[o]=X(r[o],t,n);if(A(r.input)){let o={...r.input};o.message=X(o.message,t,n),Array.isArray(o.vars)&&(o.vars=o.vars.map(i=>X(i,t,n))),r.input=o}return Array.isArray(r.attachments)&&(r.attachments=r.attachments.map(o=>X(o,t,n))),Array.isArray(r.outputMapping)&&(r.outputMapping=r.outputMapping.map(o=>A(o)?{...o,from:X(o.from,t,n)}:o)),Array.isArray(r.inputs)&&(r.inputs=r.inputs.map(o=>A(o)&&"from"in o?{...o,from:X(o.from,t,n)}:o)),r}function Re(e,t,n,r){for(let o of Ie(r)){if(!o.startsWith("secrets."))continue;let i=o.slice(8);i&&e.push({kind:"secret",id:i,nodeId:t,field:n})}}function se(e,t,n,r){if(typeof n=="string"){Re(e,t,r,n);return}if(Array.isArray(n)){n.forEach((o,i)=>se(e,t,o,`${r}[${i}]`));return}if(A(n))for(let[o,i]of Object.entries(n))se(e,t,i,r?`${r}.${o}`:o)}function C(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 cn(e){let t=Array.isArray(e.model)?e.model[0]:e.model;return typeof t=="string"&&t.trim()?t.trim():Se}function lt(e){let t=[];for(let n of e.nodes){let r=A(n.data)?n.data:{},o=n.type;if(o==="startNode"&&at(r)&&C(t,"model",dt(r),n.id,"memory_model"),o==="classifierNode"&&C(t,"clefModel",r.model,n.id,"model"),o==="llmNode"&&(C(t,"model",cn(r),n.id,"model"),Array.isArray(r.tools)&&r.tools.forEach((i,s)=>{typeof i=="string"?C(t,"tool",i,n.id,`tools[${s}]`):A(i)&&typeof i.id=="string"&&C(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)=>C(t,"memo",s,n.id,Array.isArray(r.rag_id)?`rag_id[${a}]`:"rag_id")),o==="toolNode"){C(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():"";C(t,"composioSlug",r.toolSlug,n.id,"toolSlug",i?{toolId:i}:void 0)}o==="workerNode"&&C(t,"worker",r.flowId,n.id,"flowId");for(let i of["template","user_template","url"])typeof r[i]=="string"&&Re(t,n.id,i,r[i]);typeof r.body=="string"?Re(t,n.id,"body",r.body):r.body!==void 0&&se(t,n.id,r.body,"body"),r.headers!==void 0&&se(t,n.id,r.headers,"headers"),r.args!==void 0&&se(t,n.id,r.args,"args")}return t}function Vr(e,t){let n=new Set((e?lt(e):[]).map(ct));return lt(t).filter(r=>!n.has(ct(r)))}function ct(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 fn=new Set(Object.values(De)),pn=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD"]),mn=new Set(["http","mcp","composio","builtin","skill"]),_t=["user_input","images","files","memory"],gn=["temperature","topP","topK","frequencyPenalty","presencePenalty"],yn=["maxOutputTokens","seed","maxRetries"],hn=new Set(["missing_state","schema_version","var_mapping","classifier_invalid","classifier_edge_missing","out_vars_invalid","start_count","answer_missing","dead_end"]),_n={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 bt(e,t,n,r){return{code:e,severity:t,message:n,...r}}function y(e,t,n){return bt(e,"error",t,n)}function Q(e,t,n){return bt(e,"warning",t,n)}function _(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function wt(e){return typeof e=="number"&&Number.isInteger(e)}function ve(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 no(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 u=fe(a.data);if(u.length)n.push(y("classifier_invalid",u.join("; "),{nodeId:a.id}));else for(let l of a.data.options){let c=t.edges.find(p=>p.source===a.id&&p.sourceHandle===Be("class",l.id));(!c||!t.nodes.some(p=>p.id===c.target))&&n.push(y("classifier_edge_missing",`Classifier ${a.id}: class ${l.id} has no connected edge`,{nodeId:a.id,ref:l.id}))}}let d=Ue(a);d.length>0&&d[0]&&n.push(y("out_vars_invalid",d[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,d=new Map;for(let p of t.edges)a.has(p.source)||a.set(p.source,[]),a.get(p.source).push(p.target),d.has(p.target)||d.set(p.target,[]),d.get(p.target).push(p.source);let u=ve(r[0].id,a),l=new Set;for(let p of o)for(let h of ve(p.id,d))l.add(h);let c=[];for(let p of u){if(l.has(p))continue;let h=t.nodes.find($=>$.id===p);h&&c.push(`${p}(${((s=h.data)==null?void 0:s.label)||""},${h.type})`)}c.length>0&&n.push(y("dead_end",`The following nodes reachable from START do not lead to any ANSWER node: ${c.join(", ")}`))}return n}function g(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(g("field_required",t,r,`Field ${r} is required on node ${t}.`));return}if(typeof i!="string"){e.push(g("field_type",t,r,`Field ${r} on node ${t} must be a string.`));return}return i}function T(e,t,n,r,o,i){let s=n[r];if(s!==void 0){if(!wt(s)){e.push(g("field_type",t,r,`Field ${r} on node ${t} must be an integer.`));return}(s<o||s>i)&&e.push(g("field_range",t,r,`Field ${r} on node ${t} must be between ${o} and ${i}.`))}}function K(e,t,n,r,o){let i=n[r];i!==void 0&&(typeof i!="string"||!o.has(i))&&e.push(g("field_enum",t,r,`Field ${r} on node ${t} must be one of ${[...o].join(", ")}.`))}function kt(e,t,n,r){if(!n){r&&e.push(g("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(g("field_type",t,"url",`Field url on node ${t} must be an http(s) URL when it is literal.`))}}function bn(e,t){let n=_(e.data)?e.data:{};switch(n.outVars!==void 0&&!Array.isArray(n.outVars)&&t.push(g("field_type",e.id,"outVars",`Field outVars on node ${e.id} must be an array.`)),e.type){case"startNode":wn(e,n,t);break;case"memoNode":{let r=n.rag_id;r===void 0||r===""||Array.isArray(r)&&r.length===0?t.push(g("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(g("field_type",e.id,"rag_id",`Field rag_id on node ${e.id} must be a string or a list of strings.`)),T(t,e.id,n,"topk",1,10);break}case"llmNode":xn(e,n,t);break;case"answerNode":En(e,n,t);break;case"apiNode":Nn(e,n,t);break;case"toolNode":Sn(e,n,t);break;case"workerNode":{let r=ae(t,e.id,n,"flowId",!0);r!==void 0&&!r.trim()&&t.push(g("field_required",e.id,"flowId",`Field flowId is required on node ${e.id}.`)),n.inputs!==void 0&&!Array.isArray(n.inputs)&&t.push(g("field_type",e.id,"inputs",`Field inputs on node ${e.id} must be an array.`));break}case"crawlNode":An(e,n,t);break;default:break}}function wn(e,t,n){for(let i of["label","greeting","user_input"])t[i]!==void 0&&typeof t[i]!="string"&&n.push(g("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(g("field_type",e.id,i,`Field ${i} on node ${e.id} must be a boolean.`));if(K(n,e.id,t,"memory_length",new Set(["short","medium","long"])),t.memory_model!==void 0&&typeof t.memory_model!="string"&&n.push(g("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(g("field_type",e.id,"inputs",`Field inputs on node ${e.id} must be an array.`));return}let r=new Set,o=new Set(_t);if(Array.isArray(t.outVars))for(let i of t.outVars)_(i)&&typeof i.name=="string"&&o.add(i.name);t.inputs.forEach((i,s)=>{if(!_(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():"",d=`inputs[${s}].name`;!qe.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:d,ref:a})):r.add(a);let u=typeof i.type=="string"?i.type:"string";["string","number","boolean","json"].includes(u)?i.default!==void 0&&!kn(u,i.default)&&n.push(y("start_input_invalid",`Start input "${a}" has a default that does not match ${u}.`,{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 kn(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 xn(e,t,n){for(let r of["template","user_template"])t[r]!==void 0&&typeof t[r]!="string"&&n.push(g("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(g("field_type",e.id,"model",`Field model on node ${e.id} must be a string.`)),T(n,e.id,t,"window_size",0,30),T(n,e.id,t,"max_steps",1,30),K(n,e.id,t,"reasoningEffort",new Set(["none","minimal","low","medium","high","xhigh"])),K(n,e.id,t,"generationPreset",new Set(["precise","balanced","creative","custom"]));for(let r of gn)t[r]!==void 0&&(typeof t[r]!="number"||!Number.isFinite(t[r]))&&n.push(g("field_type",e.id,r,`Field ${r} on node ${e.id} must be a finite number.`));for(let r of yn)t[r]!==void 0&&!wt(t[r])&&n.push(g("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(g("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(g("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"&&(!_(r)||typeof r.kind!="string"||!mn.has(r.kind)||typeof r.id!="string"||!r.id)&&n.push(g("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(g("field_type",e.id,"attachments",`Field attachments on node ${e.id} must be an array.`))}function En(e,t,n){if(t.outputMapping===void 0)return;if(!Array.isArray(t.outputMapping)){n.push(g("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=_(o)&&typeof o.key=="string"?o.key:"",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 Nn(e,t,n){let r=ae(n,e.id,t,"url",!0);if(r&&kt(n,e.id,r,!0),K(n,e.id,t,"method",pn),T(n,e.id,t,"timeoutMs",1,12e4),t.headers!==void 0&&!_(t.headers))n.push(g("field_type",e.id,"headers",`Field headers on node ${e.id} must be an object.`));else if(_(t.headers))for(let[o,i]of Object.entries(t.headers))typeof i!="string"&&n.push(g("field_type",e.id,`headers.${o}`,`Header ${o} on node ${e.id} must be a string.`));t.body!==void 0&&typeof t.body!="string"&&!_(t.body)&&!Array.isArray(t.body)&&n.push(g("field_type",e.id,"body",`Field body on node ${e.id} must be a string or a JSON value.`))}function Sn(e,t,n){ae(n,e.id,t,"toolId",!0),t.source!==void 0&&t.source!=="http"&&t.source!=="composio"&&n.push(g("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&&!_(t.args)&&n.push(g("field_type",e.id,"args",`Field args on node ${e.id} must be an object.`)),t.inputSchema!==void 0&&!_(t.inputSchema)&&n.push(g("field_type",e.id,"inputSchema",`Field inputSchema on node ${e.id} must be an object.`))}function An(e,t,n){let r=ae(n,e.id,t,"url",!0);r&&kt(n,e.id,r,!0),K(n,e.id,t,"source",new Set(["all","sitemaps","links"])),T(n,e.id,t,"limit",1,50),T(n,e.id,t,"depth",0,10),K(n,e.id,t,"format",new Set(["markdown","json"])),t.render!==void 0&&typeof t.render!="boolean"&&n.push(g("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(g("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(g("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(g("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(g("field_type",e.id,"jsonPrompt",`Field jsonPrompt on node ${e.id} must be a string.`)),typeof t.jsonPrompt=="string"&&t.jsonPrompt.includes("{{")&&n.push(Q("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&&!_(t.jsonSchema)&&n.push(g("field_type",e.id,"jsonSchema",`Field jsonSchema on node ${e.id} must be an object.`)),t.output!==void 0&&!_(t.output)?n.push(g("field_type",e.id,"output",`Field output on node ${e.id} must be an object.`)):_(t.output)&&(K(n,e.id,t.output,"mode",new Set(["pages","single","concat"])),t.output.select!==void 0&&t.output.mode!=="single"&&n.push(g("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(g("field_enum",e.id,"output.fields",`output.fields on node ${e.id} must use url, title, markdown, or json.`)),T(n,e.id,t.output,"maxCharsPerPage",0,262144)),T(n,e.id,t,"waitTimeoutMs",0,12e4),T(n,e.id,t,"maxAgeS",0,604800)}function $n(e){let t=new Set(["source-__uncertain","source-__blocked","source-__error"]),n=_(e.data)&&Array.isArray(e.data.options)?e.data.options:[];for(let r of n)_(r)&&typeof r.id=="string"&&t.add(`source-${r.id}`);return t}function Rn(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),d=n.get(s.target);if(!a||!d){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}d.type==="startNode"&&t.push(y("start_has_input",`Start node ${d.id} cannot have an incoming edge.`,{nodeId:d.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 u=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 c=$n(a);(!u||!c.has(u))&&t.push(y("edge_bad_handle",`Classifier ${a.id} edge has an invalid handle.`,{nodeId:a.id,edgeId:s.id,field:"sourceHandle",ref:u}));let p=o.get(a.id)??new Set;u&&p.has(u)&&t.push(y("edge_bad_handle",`Classifier ${a.id} handle ${u} is duplicated.`,{nodeId:a.id,edgeId:s.id,ref:u})),u&&p.add(u),o.set(a.id,p)}else u&&t.push(y("edge_bad_handle",`Node ${a.id} cannot set a source handle.`,{nodeId:a.id,edgeId:s.id,field:"sourceHandle",ref:u}));let l=`${s.source}\0${s.target}\0${u??""}`;r.has(l)&&t.push(y("edge_duplicate",`Duplicate edge from ${s.source} to ${s.target}.`,{nodeId:a.id,edgeId:s.id,ref:u})),r.add(l),i.set(a.id,(i.get(a.id)??0)+1)}for(let[s,a]of i){let d=n.get(s);d&&d.type!=="classifierNode"&&a>1&&t.push(y("multiple_outgoing",`Node ${s} has multiple outgoing edges.`,{nodeId:s,field:"edges"}))}}function In(e,t,n,r){var i;return(i=Ke(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 vn(e,t,n){let r=e.nodes,o=e.edges;for(let i of gt(t)){let s=i.ref;try{s=ce(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{Je(s,{context:{},results:{},nodes:r,edges:o,currentNodeId:t.id})}catch(u){if(!(u instanceof ze))throw u;let l=u.code==="UNKNOWN_OUTPUT"?"ref_unknown_output":u.code==="OUT_OF_SCOPE"?"ref_out_of_scope":u.code==="UNKNOWN_CONTEXT_REF"?"ref_unknown_node":"ref_syntax";n.push(y(l,u.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"),d=In(r,o,t.id,s);a&&d&&Ve({type:d})&&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 Pn(e,t){var r;for(let o of e.nodes){if(o.type!=="classifierNode")continue;let i=_(o.data)?o.data:{},s=e.edges.filter(l=>l.source===o.id);s.some(l=>l.sourceHandle==="source-__error")||t.push(Q("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=_(i.confidence)?i.confidence:{},d=typeof a.threshold=="number"&&a.threshold>0||typeof a.margin=="number"&&a.margin>0,u=Array.isArray(i.checks)&&i.checks.some(l=>_(l)&&l.guard!==void 0);s.some(l=>l.sourceHandle==="source-__uncertain")&&!d&&t.push(Q("classifier_handle_inactive",`Classifier ${o.id} connects source-__uncertain but threshold and margin are 0.`,{nodeId:o.id,ref:"source-__uncertain"})),s.some(l=>l.sourceHandle==="source-__blocked")&&!u&&t.push(Q("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=ve(n[0].id,o);for(let s of e.nodes)i.has(s.id)||t.push(Q("unreachable_node",`Node ${s.id} is not reachable from Start.`,{nodeId:s.id}))}Cn(e)&&t.push(Q("graph_cycle","Graph contains a cycle."))}function Cn(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 Tn(e,t){var i,s;let n=new Set,r=new Set(_t);for(let a of e.nodes)if(!(a.type!=="startNode"||!Array.isArray((i=a.data)==null?void 0:i.inputs)))for(let d of a.data.inputs)_(d)&&typeof d.name=="string"&&d.name.trim()&&r.add(d.name.trim());for(let a of e.nodes)fn.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 d of a.data.inputs)!_(d)||typeof d.name!="string"||o.has(d.name)&&t.push(y("start_input_invalid",`Start input "${d.name}" collides with a node id.`,{nodeId:a.id,field:"inputs",ref:d.name}))}function ro(e){let t=[];Tn(e,t),Rn(e,t);for(let n of e.nodes)bn(n,t),vn(e,n,t);return Pn(e,t),t}function ht(e){return[e.code,e.nodeId??"",e.field??"",e.ref??"",e.kind??""].join("")}function oo(e,t,n={}){let r=new Set(e.map(ht)),o=[],i=[];for(let s of t){let a=r.has(ht(s)),d;hn.has(s.code)?d="error":s.code==="inline_credential"?d=!a&&!n.acknowledgeInlineCredentials?"error":"warning":_n[s.code]==="advisory"?d="warning":d=a?"warning":"error";let u={...s,severity:d};(d==="error"?o:i).push(u)}return{errors:o,warnings:i}}var Pe=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,On=new Set(["source-__uncertain","source-__blocked","source-__error"]);function pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Et(e,t,n){return`xy-edge__${e}${n??""}-${t}`}function Nt(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 ye(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return structuredClone(t);let n=pe(e)?{...e}:{};for(let[r,o]of Object.entries(t))o===null?delete n[r]:n[r]=ye(n[r],o);return n}function me(e){return Array.isArray(e)?e.map(me):pe(e)?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t<n?-1:t>n?1:0).map(([t,n])=>[t,me(n)])):e}function uo(e){let t=me(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 xt(e){return JSON.stringify(me({type:e.type,position:e.position,data:e.data}))}function jn(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?xt(a)!==xt(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 m(e,t,n,r){return{code:e,severity:"error",message:t,op:n,...r}}function w(e,t){return e.nodes.find(n=>n.id===t)}function O(e){return e.startsWith("source-")?e:`source-${e}`}function St(e){let t=new Set(On),n=pe(e.data)&&Array.isArray(e.data.options)?e.data.options:[];for(let r of n)pe(r)&&typeof r.id=="string"&&r.id&&t.add(`source-${r.id}`);return t}function de(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 Mn(e,t){if(t.position)return{...t.position};if(t.from){let o=w(e,t.from.node),i=e.edges.filter(a=>{var d;return a.source===((d=t.from)==null?void 0:d.node)}).length,s=de(o);return{x:s.x+320,y:s.y+140*i}}if(t.to){let o=de(w(e,t.to.node));return{x:o.x-320,y:o.y}}let n=e.nodes.map(o=>de(o).x),r=e.nodes.map(o=>de(o).y);return{x:(n.length?Math.max(...n):0)+320,y:r.length?Math.min(...r):0}}function ee(e,t,n){return{id:Et(e,t,n),source:e,target:t,...n?{sourceHandle:n}:{}}}function ge(e,t){return e.edges.filter(n=>n.source===t)}function At(e,t,n,r){if(e.type==="classifierNode"){if(!t)return m("op_invalid","handle is required when the source is a classifier.",n,{nodeId:e.id,field:r});let o=O(t);return St(e).has(o)?void 0:m("op_invalid",`Classifier ${e.id} has no handle ${o}.`,n,{nodeId:e.id,field:r,ref:o})}if(t)return m("op_invalid","handle is only valid when the source is a classifier.",n,{nodeId:e.id,field:r})}function Gn(e,t,n){switch(t.op){case"add_node":return Wn(e,t,n);case"insert_node":return Fn(e,t,n);case"update_node":return Ln(e,t,n);case"rename_node":return Dn(e,t,n);case"remove_node":return qn(e,t,n);case"connect":return Hn(e,t,n);case"disconnect":return Un(e,t,n);case"move_node":return Kn(e,t,n);default:return m("op_invalid","Unknown op.",n)}}function Wn(e,t,n){var d,u,l;if(t.type==="startNode"&&e.nodes.some(c=>c.type==="startNode"))return m("op_invalid","A worker can include only one Start node.",n);let r=t.id??Nt(e,t.type);if(!Pe.test(r))return m("op_invalid",`Node id ${r} is not a valid new id.`,n,{field:"id"});if(w(e,r))return m("op_invalid",`Node id ${r} already exists.`,n,{nodeId:r});let o=t.from?w(e,t.from.node):void 0,i=t.to?w(e,t.to.node):void 0;if(t.from&&!o)return m("op_unknown_node",`Node ${t.from.node} does not exist.`,n,{nodeId:t.from.node});if(t.to&&!i)return m("op_unknown_node",`Node ${t.to.node} does not exist.`,n,{nodeId:t.to.node});if((i==null?void 0:i.type)==="startNode")return m("op_invalid","An edge cannot target the Start node.",n,{nodeId:i.id});if((o==null?void 0:o.type)==="answerNode")return m("op_invalid","An edge cannot leave an Answer node.",n,{nodeId:o.id});if(o){let c=At(o,(d=t.from)==null?void 0:d.handle,n,"from.handle");if(c)return c;if(o.type!=="classifierNode"&&ge(e,o.id).length>0)return m("already_connected",`Node ${o.id} already has an outgoing edge.`,n,{nodeId:o.id});if(o.type==="classifierNode"&&((u=t.from)!=null&&u.handle)){let p=O(t.from.handle);if(ge(e,o.id).some(h=>h.sourceHandle===p))return m("already_connected",`Handle ${p} is already connected.`,n,{nodeId:o.id,ref:p})}}let s=ye(xe(t.type),t.data??{}),a={id:r,type:t.type,position:Mn(e,t),data:s};if((l=t.to)!=null&&l.handle){if(t.type!=="classifierNode")return m("op_invalid","to.handle is only valid when the new node is a classifier.",n,{field:"to.handle"});if(!St(a).has(O(t.to.handle)))return m("op_invalid","to.handle must be an option or reserved handle of the new classifier.",n,{field:"to.handle",ref:O(t.to.handle)})}else if(t.to&&t.type==="classifierNode")return m("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 c=o.type==="classifierNode"&&t.from.handle?O(t.from.handle):void 0;e.edges.push(ee(o.id,r,c))}if(i&&t.to){let c=t.type==="classifierNode"&&t.to.handle?O(t.to.handle):void 0;e.edges.push(ee(r,i.id,c))}}function Fn(e,t,n){if(t.type==="classifierNode"||t.type==="startNode"||t.type==="answerNode")return m("op_invalid",`insert_node does not accept ${t.type}.`,n,{field:"type"});let r=t.id??Nt(e,t.type);if(!Pe.test(r))return m("op_invalid",`Node id ${r} is not a valid new id.`,n,{field:"id"});if(w(e,r))return m("op_invalid",`Node id ${r} already exists.`,n,{nodeId:r});let o=w(e,t.between.from),i=w(e,t.between.to);if(!o)return m("op_unknown_node",`Node ${t.between.from} does not exist.`,n,{nodeId:t.between.from});if(!i)return m("op_unknown_node",`Node ${t.between.to} does not exist.`,n,{nodeId:t.between.to});let s=t.between.handle?O(t.between.handle):void 0,a=e.edges.filter(c=>c.source===o.id&&c.target===i.id&&(s===void 0||c.sourceHandle===s||c.sourceHandle===t.between.handle));if(a.length===0)return m("edge_not_found",`No edge from ${o.id} to ${i.id}.`,n);if(a.length>1)return m("edge_ambiguous",`Multiple edges from ${o.id} to ${i.id}; pass handle.`,n,{ref:s});let[d]=a;if(!d)return m("edge_not_found",`No edge from ${o.id} to ${i.id}.`,n);e.edges=e.edges.filter(c=>c.id!==d.id);let u=ye(xe(t.type),t.data??{}),l=de(o);e.nodes.push({id:r,type:t.type,position:{x:l.x+320,y:l.y},data:u}),e.edges.push(ee(o.id,r,d.sourceHandle)),e.edges.push(ee(r,i.id))}function Ln(e,t,n){let r=w(e,t.id);if(!r)return m("op_unknown_node",`Node ${t.id} does not exist.`,n,{nodeId:t.id});r.data=ye(r.data,t.data)}function Dn(e,t,n){let r=w(e,t.id);if(!r)return m("op_unknown_node",`Node ${t.id} does not exist.`,n,{nodeId:t.id});if(r.type==="startNode")return m("op_invalid","The Start node cannot be renamed.",n,{nodeId:r.id});if(!Pe.test(t.newId))return m("op_invalid",`Node id ${t.newId} is not a valid new id.`,n,{field:"newId"});if(w(e,t.newId))return m("op_invalid",`Node id ${t.newId} already exists.`,n,{nodeId:t.newId});for(let o of e.nodes)o.data=yt(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:Et(i,s,o.sourceHandle)}})}function qn(e,t,n){var s;let r=w(e,t.id);if(!r)return m("op_unknown_node",`Node ${t.id} does not exist.`,n,{nodeId:t.id});if(r.type==="startNode")return m("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 m("op_invalid","reconnect requires exactly one incoming and one outgoing edge on a non-classifier node.",n,{nodeId:r.id});let a=o[0],d=i[0];if(!a||!d)return m("op_invalid","reconnect requires exactly one incoming and one outgoing edge.",n,{nodeId:r.id});if(((s=w(e,d.target))==null?void 0:s.type)==="startNode")return m("op_invalid","An edge cannot target the Start node.",n);e.edges=e.edges.filter(u=>u.source!==r.id&&u.target!==r.id),e.edges.push(ee(a.source,d.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 Hn(e,t,n){if(t.from===t.to)return m("op_invalid","An edge cannot connect a node to itself.",n,{nodeId:t.from});let r=w(e,t.from),o=w(e,t.to);if(!r)return m("op_unknown_node",`Node ${t.from} does not exist.`,n,{nodeId:t.from});if(!o)return m("op_unknown_node",`Node ${t.to} does not exist.`,n,{nodeId:t.to});if(o.type==="startNode")return m("op_invalid","An edge cannot target the Start node.",n,{nodeId:o.id});if(r.type==="answerNode")return m("op_invalid","An edge cannot leave an Answer node.",n,{nodeId:r.id});let i=At(r,t.handle,n,"handle");if(i)return i;let s=r.type==="classifierNode"&&t.handle?O(t.handle):void 0;if(e.edges.some(d=>d.source===r.id&&d.target===o.id&&(d.sourceHandle??void 0)===s))return m("edge_duplicate","An identical edge already exists.",n,{nodeId:r.id,ref:s});if(r.type==="classifierNode"){let d=ge(e,r.id).find(u=>u.sourceHandle===s);if(d&&!t.replace)return m("already_connected",`Handle ${s} is already connected.`,n,{nodeId:r.id,ref:s});d&&t.replace&&(e.edges=e.edges.filter(u=>u.id!==d.id))}else if(ge(e,r.id).length>0){if(!t.replace)return m("already_connected",`Node ${r.id} already has an outgoing edge.`,n,{nodeId:r.id});e.edges=e.edges.filter(d=>d.source!==r.id)}e.edges.push(ee(r.id,o.id,s))}function Un(e,t,n){let r=w(e,t.from);if(!r)return m("op_unknown_node",`Node ${t.from} does not exist.`,n,{nodeId:t.from});if(t.to&&!w(e,t.to))return m("op_unknown_node",`Node ${t.to} does not exist.`,n,{nodeId:t.to});let o=t.handle?O(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 m("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 Kn(e,t,n){let r=w(e,t.id);if(!r)return m("op_unknown_node",`Node ${t.id} does not exist.`,n,{nodeId:t.id});r.position={x:t.position.x,y:t.position.y}}function lo(e,t){let n=structuredClone(e);for(let r=0;r<t.length;r+=1){let o=t[r];if(!o)continue;let i=Gn(n,o,r);if(i)return{ok:!1,issue:i}}return{ok:!0,graph:n,changes:jn(e,n)}}var Vn=[/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-----/],zn=new Set(["authorization","proxy-authorization","x-api-key","api-key","apikey","x-auth-token","x-access-token","cookie"]),Jn=new Set(["key","api_key","apikey","token","access_token","secret","password","sig","signature"]),Zn=new Set(["password","secret","token","api_key","apikey","client_secret","private_key"]),Bn="Store it with `secret_set` and replace the value with `{{ secrets.NAME }}`.";function V(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function z(e){return e.replace(/\{\{\s*(?:secrets|auth)\.[^}]*\}\}/g,"")}function te(e){return Vn.some(t=>t.test(e))}function Yn(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 $t(e){return e.length>=32&&/^[A-Za-z0-9+/_=-]+$/.test(e)&&Yn(e)>3.5}function Xn(e){let t=e.toLowerCase();return zn.has(t)||t.includes("token")||t.includes("secret")||t.includes("key")}function Qn(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 J(e,t,n){return{code:"inline_credential",severity:"warning",message:`Inline credential in ${t}.`,nodeId:e,field:t,kind:n,suggestedSecret:Qn(e,t),hint:Bn}}function er(e,t){if(/^bearer\s+\S/i.test(t))return"bearer_token";if(/^basic\s+\S/i.test(t))return"basic_auth";if(Xn(e)&&t.trim())return $t(t)?"high_entropy":"sensitive_key"}function Te(e,t,n=""){if(typeof e=="string"){t(n,e);return}if(Array.isArray(e)){e.forEach((r,o)=>Te(r,t,`${n}[${o}]`));return}if(V(e))for(let[r,o]of Object.entries(e))r!=="label"&&Te(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 nr(e,t){let n=z(t).trim();if(!n||n.includes("{{"))return[];let r;try{r=new URL(n)}catch{return[]}let o=[];(r.username||r.password)&&o.push(J(e,"url","url_userinfo"));for(let[i,s]of r.searchParams){if(!Jn.has(i.toLowerCase()))continue;let a=z(s).trim();!a||a.includes("{{")||o.push(J(e,"url",te(a)?"known_token":"url_query"))}return o}function Ce(e,t,n){let r=[],o=(s,a,d)=>{if(!Zn.has(d.toLowerCase()))return;let u=z(a).trim();u.length<8||u.includes("{{")||te(u)||r.push(J(e,s||t,$t(u)?"high_entropy":"sensitive_key"))},i=(s,a)=>{if(typeof s!="string"){if(Array.isArray(s)){s.forEach((d,u)=>i(d,`${a}[${u}]`));return}if(V(s))for(let[d,u]of Object.entries(s)){let l=a?`${a}.${d}`:d;typeof u=="string"?o(l,u,d):i(u,l)}}};return i(n,t),r}function fo(e){let t=[];for(let r of e.nodes){let o=V(r.data)?r.data:{};if(Te(o,(i,s)=>{i&&te(z(s))&&t.push(J(r.id,i,"known_token"))}),r.type==="apiNode"&&V(o.headers))for(let[i,s]of Object.entries(o.headers)){if(typeof s!="string")continue;let a=z(s).trim();if(!a.replace(/^(bearer|basic)\s+/i,"").trim()||te(a))continue;let u=er(i,a);u&&t.push(J(r.id,`headers.${i}`,u))}if((r.type==="apiNode"||r.type==="crawlNode")&&typeof o.url=="string"){let i=nr(r.id,o.url);te(z(o.url))&&!i.some(s=>s.kind==="known_token")&&t.push(J(r.id,"url","known_token")),t.push(...i)}if(r.type==="apiNode"&&o.body!==void 0){let i=tr(o.body);V(i)||Array.isArray(i)?t.push(...Ce(r.id,"body",i)):V(o.body)||Array.isArray(o.body)?t.push(...Ce(r.id,"body",o.body)):typeof o.body=="string"&&te(z(o.body))&&t.push(J(r.id,"body","known_token"))}r.type==="toolNode"&&(V(o.args)||Array.isArray(o.args))&&t.push(...Ce(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 Oe(e,t,n,r){return{id:e,type:t,position:{x:r,y:0},data:n}}function Rt(e,t){return{id:`xy-edge__${e}-${t}`,source:e,target:t}}var rr={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 It(e){return{schemaVersion:3,nodes:[Oe("start","startNode",{...rr,...e!=null&&e.inputs?{inputs:e.inputs}:{}},0),Oe("llm-1","llmNode",{...or,...(e==null?void 0:e.template)!==void 0?{template:e.template}:{}},320),Oe("answer-1","answerNode",{label:"Answer",outputMapping:[{key:(e==null?void 0:e.key)??"reply",from:"llm-1.output"}]},640)],edges:[Rt("start","llm-1"),Rt("llm-1","answer-1")]}}var mo={chat:It(),extract:It({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 yo(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 ir=[{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."}],sr=ir.reduce((e,t)=>(e[t.id]=t,e),{});function vt(e,t){let n=JSON.stringify(e).slice(1,-1),r=new TextEncoder,o=[...n.matchAll(/([A-Za-z\u00C0-\u024F]+)(\s*)/g)].filter(u=>u[1].length>=3&&u[2].length>0).map(u=>({start:u.index,end:u.index+u[0].length,bytes:r.encode(u[0]).length})),i=[{end:0,encodedEnd:0,bytes:0}];for(let u of e){let l=i[i.length-1],c=JSON.stringify(u).slice(1,-1);i.push({end:l.end+u.length,encodedEnd:l.encodedEnd+c.length,bytes:l.bytes+r.encode(c).length})}let s=[],a=0,d=0;for(let u=0;u<i.length;u++){let l=i[u];for(;a<o.length&&o[a].end<=l.encodedEnd;)d+=o[a++].bytes;let c=o[a];c&&c.start<l.encodedEnd&&l.encodedEnd<c.end||s.push({index:u,hundredths:l.bytes*93-d*(93-(t==="clef-omni"?23:20))})}return{boundaries:i,cuts:s}}var je=Symbol("clefTruncationWarning");function jo(e,t){let n=fe(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 Tt(r,Math.floor(W[e.model].contextWindow*.9))}function Tt(e,t){e.state={message:e.state.message,history:e.state.history.slice(),vars:Object.fromEntries(Object.entries(e.state.vars))};let n=Z(e);if(n<=t)return e;let r={...e,state:{message:"",history:[],vars:{}}};if(Z(r)>t)throw new Error("Classifier questions exceed the Clef context budget");let o=()=>Z(e)<=t,i=0,s=0,a=!1,d=e.state.history;if(d.length){let c=0,p=d.length;for(;c<p;){let h=Math.floor((c+p)/2);e.state.history=d.slice(h),o()?p=h:c=h+1}i=c,e.state.history=d.slice(i)}let u=Object.entries(e.state.vars).sort((c,p)=>(JSON.stringify(p[1])??"").length-(JSON.stringify(c[1])??"").length);for(let[c,p]of u){if(o())break;s++,typeof p=="string"?(e.state.vars[c]="",o()?e.state.vars[c]=Pt(p,e.model,t,Z(e)):delete e.state.vars[c]):delete e.state.vars[c]}if(!o()){let c=e.state.message;e.state.message="",e.state.message=Pt(c,e.model,t,Z(e)),a=e.state.message!==c}if(!o())throw new Error("Classifier request exceeds the Clef context budget");let l=`Classifier: context trimmed for ${e.model} (${W[e.model].contextWindow} token limit, budget ${t}); history removed: ${i}; vars shortened/removed: ${s}; message tail shortened: ${a}; estimated tokens ${n} -> ${Z(e)}`;return Ot(e,l),e}function Pt(e,t,n,r){let{boundaries:o,cuts:i}=vt(e,t),s=c=>r+Math.ceil(c/100)<=n,a=0,d=i.length-1;for(;a<d;){let c=Math.ceil((a+d)/2);s(i[c].hundredths)?a=c:d=c-1}let u=i[a],l=u.index;if(a+1<i.length){let c=u.index,p=i[a+1].index-1;for(;c<p;){let h=Math.ceil((c+p)/2),$=u.hundredths+(o[h].bytes-o[u.index].bytes)*93;s($)?c=h:p=h-1}l=c}return e.slice(0,o[l].end)}function Z(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 Ot(e,t){Object.defineProperty(e,je,{value:[e[je],t].filter(Boolean).join("; "),configurable:!0})}function ar(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 Mo(e){return e[je]}async function Go(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(W[t].id,{model:n.model,state:n.state,questions:n.questions},{signal:i.signal}),a=async()=>{try{return await s()}catch(d){let u=ar(d);if(u===void 0||i.signal.aborted)throw d;let l=Math.floor(Math.min(W[t].contextWindow*.9,Z(n)*u*.9));if(Ot(n,`Classifier: context retry 1/1; scaled budget ${l}`),Tt(n,l),i.signal.aborted)throw new Error("Clef timeout");return await s()}};try{return await Promise.race([a(),new Promise((d,u)=>{o=setTimeout(()=>{u(new Error("Clef timeout")),i.abort()},r)})])}finally{o!==void 0&&clearTimeout(o)}}function B(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Clef response object");return e}function he(e){if(typeof e!="number"||!Number.isFinite(e)||e<0||e>1)throw new Error("Invalid Clef probability");return e}function Ct(e,t){let n=B(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,he(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 Wo(e,t){let n=B(e),r=B(n.answers),o=B(r.route);if(o.type!=="choice"||typeof o.choice!="string"||!t.options.some(l=>l.id===o.choice))throw new Error("Invalid Clef route choice");let i=Ct(o.probabilities,t.options.map(l=>l.id)),s=Object.values(i).sort((l,c)=>c-l);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(l=>l.id===o.choice).label,confidence:he(o.confidence),margin:s[0]-s[1],probabilities:i,route:"class",checks:Object.fromEntries(t.checks.map(l=>{if(!Object.hasOwn(r,l.id))throw new Error(`Missing Clef answer: ${l.id}`);let c=B(r[l.id]);if(c.type!==l.type)throw new Error(`Invalid Clef answer type: ${l.id}`);if(l.type==="noul")return[l.id,he(c.noul)];let p=B(c.legend),h=l.levels.map((j,L)=>String(L));if(h.some(j=>typeof p[j]!="string"))throw new Error("Invalid Clef score legend");let $=Ct(c.probabilities,h);if(typeof c.score!="number"||!Number.isFinite(c.score)||c.score<0||c.score>l.levels.length-1)throw new Error("Invalid Clef score");let ue=h.reduce((j,L)=>$[j]>=$[L]?j:L);return[l.id,{score:c.score,level:l.levels[Number(ue)],confidence:he(c.confidence),probabilities:$}]}))};t.checks.some(l=>l.type==="noul"&&l.guard&&Number(a.checks[l.id])>l.guard.threshold)?a.route="blocked":(a.confidence<t.confidence.threshold||a.margin<t.confidence.margin)&&(a.route="uncertain");let u=B(n.usage).input_tokens;if(typeof u!="number"||!Number.isInteger(u)||u<0)throw new Error("Invalid Clef input usage");return{result:a,usage:{promptTokens:u,completionTokens:0,totalTokens:u}}}function Fo(){return{classification:"",label:"",confidence:0,margin:0,probabilities:{},route:"error",checks:{}}}function Lo(e,t,n){var s,a;let r=e.filter(d=>d.type==="text"&&typeof d.content=="string"&&(d.role==="user"||d.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 d=r.length-1;d>=0&&t>0&&!(r[d].role==="user"&&(o=d,++i===t));d--);return r.slice(o).map(d=>({role:d.role,text:d.content}))}var Ge=["temperature","topP","topK","frequencyPenalty","presencePenalty","maxOutputTokens","seed","stopSequences","maxRetries"],jt=["temperature","topP","topK","frequencyPenalty","presencePenalty"],Mt={precise:{temperature:.3,topP:.9,topK:30},balanced:{temperature:.8,topP:1,topK:50},creative:{temperature:1.1,topP:.95,topK:80}},dr=1e-6,Me={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 ur(e){return/^gpt-5/i.test(e)}function _e(e){let t=e.contextWindow??128e3;return e.provider==="openai"?ur(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}}:{...Me,maxOutputTokens:{max:t}}:e.provider==="xai"?{...Me,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}}:{...Me,maxOutputTokens:{max:t}}}function be(e,t){if(e==="maxRetries")return!0;let n=t[e];return n===!1?!1:e==="seed"?n===!0:n!==void 0}function lr(e,t,n){return Math.min(n,Math.max(t,e))}function cr(e,t){return e===void 0&&t===void 0?!0:e===void 0||t===void 0?!1:Math.abs(e-t)<dr}function qo(e,t){for(let n of["precise","balanced","creative"]){let r=Mt[n],o=!0;for(let i of jt){if(t&&!be(i,t))continue;let s=r[i],a=e[i];if(s!==void 0){if(typeof s=="number"&&typeof a=="number"){if(!cr(a,s)){o=!1;break}}else if(a!==s){o=!1;break}}}if(o)return n}return"custom"}function Ho(e,t){let n=Mt[e],r={};for(let o of jt){if(t&&!be(o,t))continue;let i=n[o];i!==void 0&&(r[o]=i)}return r}function Uo(e){if(!e)return{};let t={};for(let n of Ge){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 Ko(e,t,n){var s;let r={...e,...t},o=[],i={};for(let a of Ge){let d=r[a];if(d===void 0)continue;if(a==="maxRetries"){i.maxRetries=d;continue}if(!be(a,n)){o.push({key:a,action:"stripped",detail:"unsupported by model"});continue}if(a==="stopSequences"){let l=d,c=((s=n.stopSequences)==null?void 0:s.max)??l.length;l.length>c?(i.stopSequences=l.slice(0,c),o.push({key:a,action:"clamped",detail:`truncated to ${c} sequences`})):i.stopSequences=l;continue}if(a==="seed"){i.seed=d;continue}let u=n[a];if(u&&typeof u=="object"&&"min"in u){let l=d,c=lr(l,u.min,u.max);i[a]=c,c!==l&&o.push({key:a,action:"clamped",detail:`clamped from ${l} to ${c}`})}else if(a==="maxOutputTokens"){let l=d,c=n.maxOutputTokens.max,p=Math.min(l,c);i.maxOutputTokens=p,p!==l&&o.push({key:a,action:"clamped",detail:`clamped from ${l} to ${p}`})}}return{effectiveParams:i,adjustments:o}}function Vo(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 zo(e=128e3){return _e({provider:"openai",providerModel:"gpt-4.1",contextWindow:e})}function Jo(e=2e6){return _e({provider:"openai",providerModel:"gpt-5-nano",contextWindow:e})}function Zo(e=256e3){return _e({provider:"xai",providerModel:"grok-4-fast",contextWindow:e})}function Bo(e=128e3){return _e({provider:"cloudflare",providerModel:"@cf/meta/llama-3.2-3b-instruct",contextWindow:e})}function Yo(e,t){let n={...e};for(let r of Ge)r==="maxRetries"||n[r]===void 0||be(r,t)||delete n[r];return n}var fr=["none","minimal","low","medium","high","xhigh"],pr=e=>typeof e=="string"&&fr.includes(e);function Qo(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 mr(e){return e.kind!=="effort"?[]:e.levels??[]}var gr=e=>e===!0||e==="true";function ei(e){return e.kind==="tag"?!0:e.kind==="effort"?gr(e.exposesReasoning):!1}function ti(e,t){if(e.kind!=="effort")return;let n=mr(e);if(pr(t)&&n.includes(t))return t;if(e.defaultLevel&&n.includes(e.defaultLevel))return e.defaultLevel}function ni(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{yr as a,_r as b,Gt as c,br as d,wr as e,W as f,v as g,Ze as h,Be as i,qt as j,Ht as k,Xe as l,tt as m,Er as n,Nr as o,b as p,q,Yt as r,Ar as s,rt as t,$r as u,Or as v,xe as w,fe as x,tn as y,nn as z,Ne as A,Se as B,rn as C,on as D,Wr as E,sn as F,an as G,at as H,dt as I,Fr as J,Lr as K,un as L,ln as M,Dr as N,qr as O,gt as P,yt as Q,lt as R,Vr as S,_n as T,no as U,ro as V,ht as W,oo as X,Et as Y,Nt as Z,uo as _,jn as $,lo as aa,fo as ba,mo as ca,yo as da,sr as ea,jo as fa,Z as ga,Mo as ha,Go as ia,Wo as ja,Fo as ka,Lo as la,Ge as ma,jt as na,Mt as oa,_e as pa,qo as qa,Ho as ra,Uo as sa,Ko as ta,Vo as ua,zo as va,Jo as wa,Zo as xa,Bo as ya,Yo as za,fr as Aa,Qo as Ba,mr as Ca,ei as Da,ti as Ea,ni as Fa};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as a,e as b}from"./chunk-Z4CYLB7J.js";import"./chunk-KKJW6HJA.js";import"./chunk-V6JSMX5A.js";import"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{a as customHttpTool,b as default};
|