@hugex/ai 2.9.13 → 2.9.14
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/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as dt,b as Zt,c as ee,d as oe}from"./chunk-TK4TFAI5.js";import{a as ne,b as re}from"./chunk-4FUIFBZO.js";import{a as se}from"./chunk-YHXUBVN2.js";import{a as
|
|
1
|
+
import{a as dt,b as Zt,c as ee,d as oe}from"./chunk-TK4TFAI5.js";import{a as ne,b as re}from"./chunk-4FUIFBZO.js";import{a as se}from"./chunk-YHXUBVN2.js";import{a as os,b as ct,c as ss,d as lt,e as xt,f as St,g as Gt,h as zt,i as Wt,j as Yt,k as It,l as Bt}from"./chunk-57TCP6J4.js";import{a as U,b as at,c as qo,d as tt,e as Ht,f as vt,g as is,h as as}from"./chunk-76OHKISD.js";import{a as W,b as Ho,c as Y,d as jt,e as Et,f as ns,g as rs,h as B,i as Q,j as Qt}from"./chunk-C2HAGFXJ.js";import{a as Ko,b as Xo,c as Vo,d as Jo,e as So,f as Go,g as qt,h as zo,i as Kt,j as Wo,k as Yo,l as Bo,m as Qo,n as Zo,o as vo,p as ts,q as es,r as Xt,s as Vt,t as Jt}from"./chunk-GRZ6ZRHM.js";import{a as Do}from"./chunk-RYHQGPX5.js";import{a as Uo}from"./chunk-R6EKV3WR.js";import{a as Lo}from"./chunk-6HY7QUMP.js";import{a as ko,b as bo}from"./chunk-V6JSMX5A.js";import{a as V,b as z,c as jo,d as Lt,e as Eo}from"./chunk-G3SGJ7XJ.js";import{a as te}from"./chunk-4WAWR4LB.js";import{a as it}from"./chunk-U56YWPSI.js";import{a as rt}from"./chunk-3TXHFKDN.js";import{Agent as ho}from"agents";import{nanoid as wo}from"nanoid";var k=(o,e,s)=>{o.send(e+"::"+s)};async function ze(o){o.sql`CREATE TABLE IF NOT EXISTS messages (id TEXT PRIMARY KEY, role TEXT NOT NULL, type TEXT NOT NULL, content TEXT NOT NULL, ts INTEGER NOT NULL)`}async function ie(o,e){o.sql`INSERT INTO messages (id, role, type, content, ts) VALUES (${e.id}, ${e.role}, ${e.type}, ${e.content}, ${e.ts})`}async function X(o){return o.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function ut(o){o.sql`DELETE FROM messages`}async function We(o){o.sql`CREATE TABLE IF NOT EXISTS context (
|
|
2
2
|
ref TEXT PRIMARY KEY,
|
|
3
3
|
domain TEXT NOT NULL,
|
|
4
4
|
description TEXT NOT NULL,
|
|
@@ -6,7 +6,7 @@ import{a as dt,b as Zt,c as ee,d as oe}from"./chunk-TK4TFAI5.js";import{a as ne,
|
|
|
6
6
|
cycle INTEGER NOT NULL,
|
|
7
7
|
meta TEXT,
|
|
8
8
|
ts INTEGER NOT NULL
|
|
9
|
-
)`}async function ae(o,e){let s=e.data??null,t=s!=null?
|
|
9
|
+
)`}async function ae(o,e){let s=e.data??null,t=s!=null?zt(s):{data:null,truncated:!1},n=t.truncated?Bt(e.meta,{truncated:!0}):e.meta??null,r=e.ts??Date.now();o.sql`INSERT INTO context (ref, domain, description, data, cycle, meta, ts)
|
|
10
10
|
VALUES (${e.ref}, ${e.domain}, ${e.description}, ${t.data}, ${e.cycle}, ${n}, ${r})
|
|
11
11
|
ON CONFLICT(ref) DO UPDATE SET
|
|
12
12
|
domain = excluded.domain,
|
|
@@ -14,29 +14,29 @@ import{a as dt,b as Zt,c as ee,d as oe}from"./chunk-TK4TFAI5.js";import{a as ne,
|
|
|
14
14
|
data = excluded.data,
|
|
15
15
|
cycle = excluded.cycle,
|
|
16
16
|
meta = excluded.meta,
|
|
17
|
-
ts = excluded.ts`}async function pt(o){return o.sql`SELECT ref, domain, description, cycle, meta, ts FROM context ORDER BY ts ASC`}async function ce(o){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context ORDER BY ts ASC`}async function ft(o,e){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${e} LIMIT 1`[0]??null}async function le(o,e){var t;return((t=o.sql`SELECT data FROM context WHERE ref = ${e} LIMIT 1`[0])==null?void 0:t.data)??null}async function de(o,e){let s=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${e} LIMIT 1`;if(s[0])return s[0];let t=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref LIKE ${e+"%"} LIMIT 2`;return t.length===1?t[0]:null}async function ue(o,e){o.sql`DELETE FROM context WHERE domain = 'tool' AND cycle <= ${e}`}async function pe(o){var s;return((s=o.sql`SELECT COALESCE(MAX(cycle), 0) AS maxCycle FROM context`[0])==null?void 0:s.maxCycle)??0}async function mt(o){o.sql`DELETE FROM context`}async function fe(o){await Ge(o),await ze(o)}function Tt(o){return{"Content-Type":"application/json",Authorization:o.HX_API_KEY}}function gt(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function Nt(o,e){if(!gt(o))return null;let s=await fetch(`${o.HX_ORA_URL}/internal/runs`,{method:"POST",headers:Tt(o),body:JSON.stringify(e)});return s.ok?await s.json():(console.error("[oraTriggers] createRun failed",s.status,await s.text().catch(()=>"")),null)}async function v(o,e){if(!gt(o))return{claimed:!0};let s=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/claim`,{method:"POST",headers:Tt(o)});if(!s.ok){let t=await s.text().catch(()=>"");throw new Error(`claimRun ${e} failed with ${s.status}: ${t}`)}return await s.json()}async function yt(o,e,s,t=3){if(!gt(o))return!0;for(let n=1;n<=t;n++){try{let r=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/complete`,{method:"POST",headers:Tt(o),body:JSON.stringify(s)});if(r.ok||r.status===409)return!0;if(r.status===404)return console.error(`[oraTriggers] completeRun ${e} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${e} attempt ${n} failed with ${r.status}`)}catch(r){console.warn(`[oraTriggers] completeRun ${e} attempt ${n} threw`,r)}n<t&&await new Promise(r=>setTimeout(r,250*n))}return console.error(`[oraTriggers] completeRun ${e} exhausted ${t} attempts; hx-ora will time the run out`),!1}async function me(o,e){if(!gt(o))return Promise.resolve();try{return await Nt(o,e)}catch(s){return console.error("[oraTriggers] recordRun failed",s),null}}var Ct=Object.freeze({}),We="__SYSTEM_";function ge(o){return o.startsWith(We)}function Se(o){let e={};for(let[s,t]of Object.entries(o))ge(s)||(e[s]=t);return Object.freeze(e)}async function ht(o,e){if(!e)return Ct;if(o.HX_ORA_URL&&o.HX_API_KEY)try{let n=await fetch(`${o.HX_ORA_URL}/internal/secrets`,{headers:{Authorization:o.HX_API_KEY}});if(n.ok){let r=await n.json();if(r.secrets)return Se(r.secrets)}else console.warn(`[secrets] API failed with status ${n.status}, falling back to KV`)}catch(n){console.error("[secrets] API request failed, falling back to KV",n)}let s=o.ORA_SECRETS;if(!s)return Ct;let t=`${e}:`;try{let n=await s.list({prefix:t,limit:1e3});n.list_complete===!1&&console.warn(`[secrets] tenant=${e} exceeded list page; truncating to first 1000 keys`);let r=n.keys.filter(u=>!ge(u.name.slice(t.length))),i=await Promise.all(r.map(async u=>{let f=await s.get(u.name);return f!==null?[u.name.slice(t.length),f]:null})),l={};for(let u of i){if(!u)continue;let[f,p]=u;f&&(l[f]=p)}return Object.freeze(l)}catch(n){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,err:n}),Ct}}import{nanoid as ls}from"nanoid";function tt(o){var n,r;let e=(n=o==null?void 0:o.flowData)==null?void 0:n.state,t=((e==null?void 0:e.nodes)??((r=o==null?void 0:o.flowData)==null?void 0:r.nodes)??[]).find(i=>i.type==="startNode");return t==null?void 0:t.data}async function ye(o,e){return typeof e.cycle=="number"&&Number.isFinite(e.cycle)?e.cycle+1:await pe(o)+1}function he(o,e,s,t,n){let r=at(tt(s));return{...e,memoryConfig:r,cycle:t,setContext:async l=>{await ae(o,l),await(n==null?void 0:n(l.ref))},getContextIndex:async()=>pt(o),getContextData:async l=>le(o,l),getContext:async l=>ft(o,l),resolveContext:async l=>de(o,l),pruneContext:async l=>ue(o,l)}}import{nanoid as co}from"nanoid";async function we(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 r=await n.json();return{name:t.name,text:r.text||""}}catch(n){return console.error(`extractDocuments: ${t.name} threw`,n),{name:t.name,text:""}}})):[]}async function At(o,e,s,t,n,r,i){var l,u,f;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});try{let p=await((l=o.getMessages)==null?void 0:l.call(o))??[],{flowId:m,chatId:a,tenant:d}=s.flowData,c=((u=p[p.length-1])==null?void 0:u.type)==="text"?p[p.length-1].content:"NO-TEXT";i==null||i({type:"answer_node",payload:{userMessage:(f=s==null?void 0:s.context)==null?void 0:f.user_input,answer:c}})}catch(p){console.error("answerNodeRunner: failed to emit answer telemetry:",p),t==null||t({type:"debug",content:"Warning: failed to emit answer telemetry"}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(p)}})}n==null||n(e.id,{type:"answerNode",message:"Answer response for: "+e.data.response,saved:!0}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}function G(o,e,s,t,n){var l,u,f;let r=(n==null?void 0:n.callerTag)??"llmNodeRunner",i=(n==null?void 0:n.serializeNonStrings)??!1;try{return Qt(o,e,{context:s.context??{},results:s.results??{},nodes:((u=(l=s.flowData)==null?void 0:l.state)==null?void 0:u.nodes)??[],secrets:(f=n==null?void 0:n.sessionEnv)==null?void 0:f.secrets},{callerTag:r,serializeNonStrings:i,onError:p=>{t==null||t({type:`error:${r}`,content:p})}})}catch(p){return console.error(p),"error"}}var Re="[redacted]",_t=(o,e,s,t,n)=>G(o,e,s,n,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function Ot(o,e,s,t,n,r,i){var f,p,m,a,d,c;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let l=null,u=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(s.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(s.results||{}));let g=((f=e.data)==null?void 0:f.url)||"",y=_t(g,e,s,o,t);if(console.log("[apiNodeRunner] resolved url:",dt(g)?Zt(y):y),!y){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,l);return}let w=(((p=e.data)==null?void 0:p.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",w);let h=((m=e.data)==null?void 0:m.headers)||{},x={},R={};for(let U in h)if(Object.prototype.hasOwnProperty.call(h,U)){let q=String(h[U]??"");R[U]=dt(q),x[U]=_t(q,e,s,o,t)}let I,P=!1;if(w!=="GET"&&w!=="HEAD"&&((a=e.data)==null?void 0:a.body)!==void 0){let U=typeof e.data.body=="string"?e.data.body:JSON.stringify(e.data.body);P=dt(U),I=_t(U,e,s,o,t),!x["Content-Type"]&&!x["content-type"]&&(x["Content-Type"]="application/json")}let _={};for(let U in x)_[U]=R[U]?Re:x[U];console.log("[apiNodeRunner] headers:",JSON.stringify(_)),console.log("[apiNodeRunner] body:",P?Re:I),t==null||t({type:"info:apiNodeRunner",content:`${w} ${y}`});let M=Number((d=e.data)==null?void 0:d.timeoutMs),L=new AbortController,F=Number.isFinite(M)&&M>0?setTimeout(()=>L.abort(),M):null,$;try{console.log("[apiNodeRunner] fetching..."),$=await fetch(y,{method:w,headers:x,body:I,signal:L.signal}),console.log("[apiNodeRunner] fetch returned status:",$.status)}finally{F&&clearTimeout(F)}let C=$.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",C);let N;C.includes("application/json")?N=await $.json():N=await $.text(),console.log("[apiNodeRunner] payload preview:",typeof N=="string"?N.slice(0,200):JSON.stringify(N).slice(0,200)),l={ok:$.ok,status:$.status,data:N};let k=Date.now()-u;i==null||i({type:"api_call",payload:{nodeId:e.id,url:y,method:w,status:$.status,latencyMs:k}}),t==null||t({type:"info:apiNodeRunner",content:`Response ${$.status} (${k}ms)`}),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:",(c=JSON.stringify(l))==null?void 0:c.slice(0,300)),n==null||n(e.id,l)}}import{generateObject as Ye}from"ai";import{z as xe}from"zod";async function $t(o,e,s,t,n,r,i){var g,y,w;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let l=(s==null?void 0:s.context)??{},u=String(((g=e==null?void 0:e.data)==null?void 0:g.input_variable)||"user_input").trim(),f=(l==null?void 0:l[u])??"",p=Array.isArray((y=e==null?void 0:e.data)==null?void 0:y.items)?e.data.items:[];if(p.length===0){t==null||t({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let m=String((w=p[p.length-1])==null?void 0:w.id);if(!f||String(f).trim().length===0){t==null||t({type:"warning:classifier",content:"No input for classification \u2014 falling back to last item."}),n==null||n(e.id,{classification:m}),s.context=s.context||{},s.context.classified_id=m,r==null||r(s);return}let d=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
|
|
17
|
+
ts = excluded.ts`}async function pt(o){return o.sql`SELECT ref, domain, description, cycle, meta, ts FROM context ORDER BY ts ASC`}async function ce(o){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context ORDER BY ts ASC`}async function ft(o,e){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${e} LIMIT 1`[0]??null}async function le(o,e){var t;return((t=o.sql`SELECT data FROM context WHERE ref = ${e} LIMIT 1`[0])==null?void 0:t.data)??null}async function de(o,e){let s=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${e} LIMIT 1`;if(s[0])return s[0];let t=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref LIKE ${e+"%"} LIMIT 2`;return t.length===1?t[0]:null}async function ue(o,e){o.sql`DELETE FROM context WHERE domain = 'tool' AND cycle <= ${e}`}async function pe(o){var s;return((s=o.sql`SELECT COALESCE(MAX(cycle), 0) AS maxCycle FROM context`[0])==null?void 0:s.maxCycle)??0}async function mt(o){o.sql`DELETE FROM context`}async function fe(o){await ze(o),await We(o)}function Tt(o){return{"Content-Type":"application/json",Authorization:o.HX_API_KEY}}function gt(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function Nt(o,e){if(!gt(o))return null;let s=await fetch(`${o.HX_ORA_URL}/internal/runs`,{method:"POST",headers:Tt(o),body:JSON.stringify(e)});return s.ok?await s.json():(console.error("[oraTriggers] createRun failed",s.status,await s.text().catch(()=>"")),null)}async function et(o,e){if(!gt(o))return{claimed:!0};let s=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/claim`,{method:"POST",headers:Tt(o)});if(!s.ok){let t=await s.text().catch(()=>"");throw new Error(`claimRun ${e} failed with ${s.status}: ${t}`)}return await s.json()}async function yt(o,e,s,t=3){if(!gt(o))return!0;for(let n=1;n<=t;n++){try{let r=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/complete`,{method:"POST",headers:Tt(o),body:JSON.stringify(s)});if(r.ok||r.status===409)return!0;if(r.status===404)return console.error(`[oraTriggers] completeRun ${e} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${e} attempt ${n} failed with ${r.status}`)}catch(r){console.warn(`[oraTriggers] completeRun ${e} attempt ${n} threw`,r)}n<t&&await new Promise(r=>setTimeout(r,250*n))}return console.error(`[oraTriggers] completeRun ${e} exhausted ${t} attempts; hx-ora will time the run out`),!1}async function me(o,e){if(!gt(o))return Promise.resolve();try{return await Nt(o,e)}catch(s){return console.error("[oraTriggers] recordRun failed",s),null}}var Ct=Object.freeze({}),Ye="__SYSTEM_";function ge(o){return o.startsWith(Ye)}function Be(o){let e={};for(let[s,t]of Object.entries(o))ge(s)||(e[s]=t);return Object.freeze(e)}async function ht(o,e){if(!e)return Ct;if(o.HX_ORA_URL&&o.HX_API_KEY)try{let n=await fetch(`${o.HX_ORA_URL}/internal/secrets`,{headers:{Authorization:o.HX_API_KEY}});if(n.ok){let r=await n.json();if(r.secrets)return Be(r.secrets)}else console.warn(`[secrets] API failed with status ${n.status}, falling back to KV`)}catch(n){console.error("[secrets] API request failed, falling back to KV",n)}let s=o.ORA_SECRETS;if(!s)return Ct;let t=`${e}:`;try{let n=await s.list({prefix:t,limit:1e3});n.list_complete===!1&&console.warn(`[secrets] tenant=${e} exceeded list page; truncating to first 1000 keys`);let r=n.keys.filter(d=>!ge(d.name.slice(t.length))),i=await Promise.all(r.map(async d=>{let f=await s.get(d.name);return f!==null?[d.name.slice(t.length),f]:null})),l={};for(let d of i){if(!d)continue;let[f,u]=d;f&&(l[f]=u)}return Object.freeze(l)}catch(n){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,err:n}),Ct}}import{nanoid as ms}from"nanoid";function ot(o){var n,r;let e=(n=o==null?void 0:o.flowData)==null?void 0:n.state,t=((e==null?void 0:e.nodes)??((r=o==null?void 0:o.flowData)==null?void 0:r.nodes)??[]).find(i=>i.type==="startNode");return t==null?void 0:t.data}async function ye(o,e){return typeof e.cycle=="number"&&Number.isFinite(e.cycle)?e.cycle+1:await pe(o)+1}function he(o,e,s,t,n){let r=lt(ot(s));return{...e,memoryConfig:r,cycle:t,setContext:async l=>{await ae(o,l),await(n==null?void 0:n(l.ref))},getContextIndex:async()=>pt(o),getContextData:async l=>le(o,l),getContext:async l=>ft(o,l),resolveContext:async l=>de(o,l),pruneContext:async l=>ue(o,l)}}import{nanoid as mo}from"nanoid";async function we(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 r=await n.json();return{name:t.name,text:r.text||""}}catch(n){return console.error(`extractDocuments: ${t.name} threw`,n),{name:t.name,text:""}}})):[]}function Qe(o,e){if(o==="images"||o==="files"||o==="file_content")return!0;let s=o.indexOf(".");if(s===-1)return!1;let t=e.find(i=>i.id===o.slice(0,s));if(!t)return!1;let n=o.slice(s+1).split(".")[0],r=B(t).find(i=>i.name===n);return(r==null?void 0:r.type)==="image"||(r==null?void 0:r.type)==="file"}function Ze(o,e){var i,l,d,f,u;let s=Array.isArray((i=o.data)==null?void 0:i.varMapping)?o.data.varMapping:[];if(s.length===0)return null;let t=((d=(l=e.flowData)==null?void 0:l.state)==null?void 0:d.nodes)||[],n={},r=new Set;for(let p of s){let c=(f=p.var)==null?void 0:f.trim(),m=(u=p.from)==null?void 0:u.trim();if(!c||!m)throw new Error(`Answer node ${o.id} has an incomplete variable mapping`);if(r.has(c))throw new Error(`Answer node ${o.id} has duplicate output key "${c}"`);if(Qe(m,t))throw new Error(`Answer node ${o.id} cannot persist binary source "${m}"`);let a=Q(m,{context:e.context||{},results:e.results||{},nodes:t});(a==null||a==="")&&(a=p.default??""),n[c]=a,r.add(c)}try{JSON.stringify(n)}catch{throw new Error(`Answer node ${o.id} produced a value that is not JSON serializable`)}return n}async function At(o,e,s,t,n,r,i){var d,f,u;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let l;try{l=Ze(e,s)}catch(p){throw t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(p)}}),p}l&&o.outputCollector&&o.outputCollector.add(e.id,l);try{let p=await((d=o.getMessages)==null?void 0:d.call(o))??[],c=((f=p[p.length-1])==null?void 0:f.type)==="text"?p[p.length-1].content:"NO-TEXT";i==null||i({type:"answer_node",payload:{userMessage:(u=s==null?void 0:s.context)==null?void 0:u.user_input,answer:c}})}catch(p){console.error("answerNodeRunner: failed to emit answer telemetry:",p),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:!!l&&!!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 S(o,e,s,t,n){var l,d,f;let r=(n==null?void 0:n.callerTag)??"llmNodeRunner",i=(n==null?void 0:n.serializeNonStrings)??!1;try{return Qt(o,e,{context:s.context??{},results:s.results??{},nodes:((d=(l=s.flowData)==null?void 0:l.state)==null?void 0:d.nodes)??[],secrets:(f=n==null?void 0:n.sessionEnv)==null?void 0:f.secrets},{callerTag:r,serializeNonStrings:i,onError:u=>{t==null||t({type:`error:${r}`,content:u})}})}catch(u){return console.error(u),"error"}}var Re="[redacted]",Ot=(o,e,s,t,n)=>S(o,e,s,n,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function _t(o,e,s,t,n,r,i){var f,u,p,c,m,a;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let l=null,d=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(s.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(s.results||{}));let g=((f=e.data)==null?void 0:f.url)||"",y=Ot(g,e,s,o,t);if(console.log("[apiNodeRunner] resolved url:",dt(g)?Zt(y):y),!y){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,l);return}let w=(((u=e.data)==null?void 0:u.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",w);let h=((p=e.data)==null?void 0:p.headers)||{},x={},R={};for(let $ in h)if(Object.prototype.hasOwnProperty.call(h,$)){let L=String(h[$]??"");R[$]=dt(L),x[$]=Ot(L,e,s,o,t)}let T,M=!1;if(w!=="GET"&&w!=="HEAD"&&((c=e.data)==null?void 0:c.body)!==void 0){let $=typeof e.data.body=="string"?e.data.body:JSON.stringify(e.data.body);M=dt($),T=Ot($,e,s,o,t),!x["Content-Type"]&&!x["content-type"]&&(x["Content-Type"]="application/json")}let A={};for(let $ in x)A[$]=R[$]?Re:x[$];console.log("[apiNodeRunner] headers:",JSON.stringify(A)),console.log("[apiNodeRunner] body:",M?Re:T),t==null||t({type:"info:apiNodeRunner",content:`${w} ${y}`});let D=Number((m=e.data)==null?void 0:m.timeoutMs),b=new AbortController,F=Number.isFinite(D)&&D>0?setTimeout(()=>b.abort(),D):null,P;try{console.log("[apiNodeRunner] fetching..."),P=await fetch(y,{method:w,headers:x,body:T,signal:b.signal}),console.log("[apiNodeRunner] fetch returned status:",P.status)}finally{F&&clearTimeout(F)}let E=P.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",E);let I;E.includes("application/json")?I=await P.json():I=await P.text(),console.log("[apiNodeRunner] payload preview:",typeof I=="string"?I.slice(0,200):JSON.stringify(I).slice(0,200)),l={ok:P.ok,status:P.status,data:I};let _=Date.now()-d;i==null||i({type:"api_call",payload:{nodeId:e.id,url:y,method:w,status:P.status,latencyMs:_}}),t==null||t({type:"info:apiNodeRunner",content:`Response ${P.status} (${_}ms)`}),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:",(a=JSON.stringify(l))==null?void 0:a.slice(0,300)),n==null||n(e.id,l)}}import{generateObject as ve}from"ai";import{z as xe}from"zod";async function $t(o,e,s,t,n,r,i){var g,y,w;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let l=(s==null?void 0:s.context)??{},d=String(((g=e==null?void 0:e.data)==null?void 0:g.input_variable)||"user_input").trim(),f=(l==null?void 0:l[d])??"",u=Array.isArray((y=e==null?void 0:e.data)==null?void 0:y.items)?e.data.items:[];if(u.length===0){t==null||t({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let p=String((w=u[u.length-1])==null?void 0:w.id);if(!f||String(f).trim().length===0){t==null||t({type:"warning:classifier",content:"No input for classification \u2014 falling back to last item."}),n==null||n(e.id,{classification:p}),s.context=s.context||{},s.context.classified_id=p,r==null||r(s);return}let m=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
|
|
18
18
|
If the message is ambiguous or none clearly matches, choose the LAST category in the list.
|
|
19
19
|
|
|
20
20
|
Categories:
|
|
21
|
-
${
|
|
21
|
+
${u.map(h=>{let x=h.keywords??h["keywords/topics"]??"",R=Array.isArray(x)?x.join(", "):String(x||"");return`- id: ${h.id}
|
|
22
22
|
label: ${h.label}
|
|
23
23
|
keywords/topics: ${R}`}).join(`
|
|
24
24
|
`)}
|
|
25
|
-
`,
|
|
25
|
+
`,a=`User message:
|
|
26
26
|
"""${String(f).trim()}"""
|
|
27
27
|
|
|
28
|
-
Select the best matching category id.`;try{let h=Date.now(),x=
|
|
28
|
+
Select the best matching category id.`;try{let h=Date.now(),x=u.map(P=>String(P.id)),R="gpt_4_1_mini",T=await ct(R,o);if(!T)throw new Error(`Model '${R}' not found in registry`);let{modelHandle:M,effectiveParams:A}=T,D=await ve({model:M,messages:[{role:"system",content:m},{role:"user",content:a}],schema:xe.object({classification:xe.enum(x).describe("The id of the best matching category")}),temperature:A.temperature??0}),b=Date.now()-h,F=D.object.classification;i==null||i({type:"class_telemetry",payload:{nodeId:e.id,totalLatency:b,model:D.response.modelId,usage:D.usage,options:x}}),i==null||i({type:"class_result",payload:{result:D}}),n==null||n(e.id,{classification:F}),s.context=s.context||{},s.context.classified_id=F,r==null||r(s),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}catch(h){t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(h)}})}}import{stepCountIs as oo,streamText as so}from"ai";import{nanoid as no}from"nanoid";import"zod";function Ie(o,e){var t,n,r,i,l,d;let s="";if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let f of o.data.varMapping){let u=f.from;if(!u)continue;let p=!1;if(u==="files"||u==="file_content")p=!0;else{let c=u.indexOf(".");if(c!==-1){let m=u.substring(0,c),a=u.substring(c+1).split(".")[0],g=(i=(r=(n=e.flowData)==null?void 0:n.state)==null?void 0:r.nodes)==null?void 0:i.find(y=>y.id===m);if(g){let w=B(g).find(h=>h.name===a);(w==null?void 0:w.type)==="file"&&(p=!0)}}}if(p){let c=Q(u,{context:e.context||{},results:e.results||{},nodes:((d=(l=e.flowData)==null?void 0:l.state)==null?void 0:d.nodes)||[]});typeof c=="string"&&c.trim()&&(s+=(s?`
|
|
29
29
|
|
|
30
|
-
`:"")+a)}}return s}function Te(o,e){var t,n,r,i,l,u;let s=[];if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let f of o.data.varMapping){let p=f.from;if(!p)continue;let m=!1;if(p==="images")m=!0;else{let a=p.indexOf(".");if(a!==-1){let d=p.substring(0,a),c=p.substring(a+1).split(".")[0],g=(i=(r=(n=e.flowData)==null?void 0:n.state)==null?void 0:r.nodes)==null?void 0:i.find(y=>y.id===d);if(g){let w=ct(g).find(h=>h.name===c);(w==null?void 0:w.type)==="image"&&(m=!0)}}}if(m){let a=lt(p,{context:e.context||{},results:e.results||{},nodes:((u=(l=e.flowData)==null?void 0:l.state)==null?void 0:u.nodes)||[]});Array.isArray(a)&&s.push(...a)}}return s}var Be=st({"../tools/composioTool.ts":()=>import("./composioTool-44B637WM.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-SFK4FG4Q.js"),"../tools/recall.ts":()=>import("./recall-IABRCSHY.js"),"../tools/skillTool.ts":()=>import("./skillTool-BSQFKZGK.js"),"../tools/tempTool.ts":()=>import("./tempTool-2RXAF56M.js"),"../tools/twitter.ts":()=>import("./twitter-OMDEG7T2.js"),"../tools/vectorize.ts":()=>import("./vectorize-UJXIDL2E.js")});var Qe=st({});function Pt(o,e,s,t,n){var i;if(!((i=t.memoryConfig)!=null&&i.enabled)||!t.memoryConfig.toolCache||!s.cacheable||!e||typeof e.execute!="function")return e;let r=e.execute.bind(e);return e.execute=async(l,...u)=>{var a;if(!t.getContextIndex)return r(l,...u);let f=await xt(l),m=(await t.getContextIndex()).find(d=>{if(d.domain!=="tool")return!1;let c=It(d.meta);return c.toolName===o&&c.paramsHash===f});if(m){let d=await((a=t.getContext)==null?void 0:a.call(t,m.ref));if((d==null?void 0:d.data)!=null&&It(d.meta).truncated!==!0){n==null||n({type:"info:memory:cacheHit",content:{ref:d.ref,toolName:o}});try{return JSON.parse(d.data)}catch{return d.data}}}return r(l,...u)},e}async function eo(o,e,s,t){var p,m;if(!((p=s.memoryConfig)!=null&&p.enabled)||!s.setContext||s.cycle==null)return;let n=o.toolCalls??[],r=o.toolResults??[];if(!n.length||!r.length)return;let i=new Map;for(let a of r)a!=null&&a.toolCallId&&i.set(a.toolCallId,a);let l=Array.isArray((m=e==null?void 0:e.data)==null?void 0:m.tools)?e.data.tools:[],u=new Map;for(let a of l)a&&typeof a.id=="string"&&u.set(a.id,a);let f=new Map;for(let a of Object.values(s.toolDefs??{}))a&&a.name&&f.set(a.name,a);for(let a of n){let d=a.toolCallId,c=a.toolName,g=i.get(d);if(!c||!g||c==="readSkillRef")continue;let y=a.args??a.input,w=g.result??g.output,h=!1,x="",R="tool",I="",P=f.get(c);P&&P.kind==="skill"&&(h=!0,x=`skill:${c}`,R="skill",I=`Skill instructions for ${c}`),x||(x=await zt(c,y),I=Gt(y,w));let _=u.get(c)??l.find(F=>F.id===c),M=await xt(y),L=typeof w=="string"?w:JSON.stringify(w??null);await s.setContext({ref:x,domain:R,description:I,data:L,cycle:s.cycle,meta:JSON.stringify({toolName:c,paramsHash:M,cacheable:(_==null?void 0:_.cacheable)===!0})}),t==null||t({type:"info:memory:updated",content:{ref:x}})}}async function oo(o,e,s,t){var m;let n=Array.isArray((m=s==null?void 0:s.data)==null?void 0:m.tools)?s.data.tools:[];if(n.length===0)return{};let r={},i=a=>{var x,R;let d=typeof(a==null?void 0:a.description)=="string"?a.description:"",c=a==null?void 0:a.inputSchema,g;try{let I=(c==null?void 0:c.shape)??(typeof((x=c==null?void 0:c._def)==null?void 0:x.shape)=="function"?c._def.shape():(R=c==null?void 0:c._def)==null?void 0:R.shape);I&&typeof I=="object"&&(g=I)}catch{}let y=g?Object.keys(g):[],w=d?`description="${d.length>120?d.slice(0,120)+"\u2026":d}"`:"description=(none)",h=y.length?`inputSchema={${y.join(", ")}}`:"inputSchema=(none)";return`${w} ${h}`},l=(()=>{let a=[],d=[],c=[],g=[];for(let w=0;w<n.length;w++){let h=n[w];!h||typeof h!="object"||typeof h.id!="string"?g.push(w):h.kind==="builtin"?a.push(h.id):h.kind==="skill"?c.push(h.id):h.kind==="http"||h.kind==="mcp"||h.kind==="composio"?d.push(h.id):g.push(w)}let y=[];return a.length&&y.push(`builtin[${a.join(", ")}]`),d.length&&y.push(`custom[${d.join(", ")}]`),c.length&&y.push(`skill[${c.join(", ")}]`),g.length&&y.push(`invalid@[${g.join(", ")}]`),y.join(" ")||"(none)"})();console.log(`[tools] node ${s.id} requested (${n.length}): ${l}`);let u=!1,f=async()=>{if(u&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},u=!0,o.toolDefs;try{let a=await se(o.env),d={};for(let c of a)c&&c.id&&(d[c.id]=c);o.toolDefs=d}catch(a){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(a)}`}),o.toolDefs=o.toolDefs||{}}return u=!0,o.toolDefs},p=[];for(let a=0;a<n.length;a++){let d=n[a];if(!d||typeof d!="object"||typeof d.id!="string"||d.kind!=="builtin"&&d.kind!=="http"&&d.kind!=="mcp"&&d.kind!=="composio"&&d.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${a}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let c=d;if(c.kind!=="builtin"){let y=(await f())[c.id];if(!y){console.error(`[tools] \u2717 custom '${c.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${c.id}' not found for this tenant`});continue}if(c.kind==="composio"){try{let h=await te(y,o,e,t),x=Object.keys(h);for(let[R,I]of Object.entries(h))r[R]=Pt(R,I,c,o,t);console.log(`[tools] \u2713 composio '${c.id}' \u2192 ${x.length} tool(s)`)}catch(h){console.error(`[tools] \u2717 composio '${c.id}': ${String(h)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${c.id}': ${String(h)}`})}continue}if(c.kind==="skill"){if(y.kind!=="skill"){console.error(`[tools] \u2717 skill '${c.id}': row is of kind '${y.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${c.id}' is not a skill`});continue}let h=y.name;if(r[h]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${h}' \u2014 builtin/other already registered, skipping skill '${c.id}'`});continue}try{r[h]=ne(y,o,e,t),p.push(y);let x=typeof y.execution=="string"?JSON.parse(y.execution):y.execution||{},R=Array.isArray(x.references)?x.references.map(I=>I==null?void 0:I.name):[];console.log(`[tools] \u2713 skill '${c.id}' \u2192 '${h}' (refs: ${R.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:h,refCount:R.length,refs:R}})}catch(x){console.error(`[tools] \u2717 skill '${c.id}': ${String(x)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${c.id}': ${String(x)}`})}continue}let w=y.name;if(r[w]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin already registered, skipping custom tool '${c.id}'`});continue}try{let h=oe(y,o,e,t);r[w]=Pt(w,h,c,o,t),console.log(`[tools] \u2713 custom '${c.id}' \u2192 '${w}'`),console.log(`[tools] ${i(r[w])}`)}catch(h){console.error(`[tools] \u2717 custom '${c.id}': ${String(h)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${c.id}': ${String(h)}`})}continue}if(!vt[c.id]){console.error(`[tools] \u2717 builtin '${c.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${c.id}' not found in registry`});continue}try{let g;try{g=await Be(`../tools/${c.id}.ts`)}catch{g=await Qe(`../tools/${c.id}.js`)}let y;if(g[c.id])y=g[c.id];else if(g.default)y=g.default;else if(g.create)y=g.create;else{let _=Object.values(g);_.length>0&&(y=_[0])}if(!y){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${c.id}'`});continue}let w,h,x={};if(c.params&&typeof c.params=="object"){if(typeof c.params.description=="string"?w=c.params.description:c.params.description!==void 0&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${c.id}' \u2014 must be a string`})),c.params.inputSchema!==void 0){let _=c.params.inputSchema;typeof _=="object"&&(typeof _.safeParse=="function"||_._def)?h=_:typeof _=="object"&&_!==null&&_.type==="object"&&_.properties?(h=ee(_),h||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${c.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${c.id}' \u2014 must be a Zod schema or JSON Schema object`})}c.params.defaults!==void 0?typeof c.params.defaults=="object"&&c.params.defaults!==null&&!Array.isArray(c.params.defaults)?x=c.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${c.id}' \u2014 must be an object`}),x={}):c.params.source!==void 0||c.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${c.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),x={}):x={}}let R=y(o,e,x,t);w&&R&&typeof R=="object"&&(R.description=w),h&&R&&typeof R=="object"&&(R.inputSchema=h),r[c.id]=Pt(c.id,R,c,o,t);let I=[];w&&I.push("description"),h&&I.push("inputSchema"),Object.keys(x).length&&I.push(`defaults(${Object.keys(x).join(",")})`);let P=I.length?` [overrides: ${I.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${c.id}'${P}`),console.log(`[tools] ${i(R)}`)}catch(g){console.error(`[tools] \u2717 builtin '${c.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${c.id}': ${String(g)}`});continue}}if(p.length>0)if(r.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{r.readSkillRef=re(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(a=>a.name)}})}catch(a){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(a)}`)}return r}async function Ft(o,e,s,t,n,r,i){var M,L,F,$,C;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let l=!1;try{let N=(M=s.flowData)==null?void 0:M.state;if(N&&N.edges&&N.nodes){let k=N.edges.filter(U=>U.source===e.id);if(k.length>0){let U=N.nodes.find(q=>q.id===k[0].target);U&&U.type==="answerNode"&&(l=!0)}}}catch(N){console.error("Error determining next node for streaming:",N)}let u=G(e.data.template,e,s,t,{sessionEnv:o});(!u||!u.trim())&&(u="Answer straight forward to the user, dont offer any other option to continue");let f=u,p="";if((L=o.memoryConfig)!=null&&L.enabled){let N=await((F=o.getContextIndex)==null?void 0:F.call(o))??[];p=St(N),u+=p}let m=G(e.data.user_template||"",e,s,t,{sessionEnv:o}),a=N=>N&&Object.fromEntries(Object.keys(N).map(k=>[k,"[redacted]"])),d=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:a(o.secrets),userAuth:a(o.userAuth)}:o,c=G(e.data.template,e,s,void 0,{sessionEnv:d})||f;c+=p;let g=G(e.data.user_template||"",e,s,void 0,{sessionEnv:d});t==null||t({type:`info:llmNodeRunner:${e.id}`,content:c}),t==null||t({type:`info:llmNodeRunner:${e.id}`,content:g});let y=($=e==null?void 0:e.data)==null?void 0:$.window_size,w=Number(y);(!Number.isInteger(w)||w<=0)&&(w=5);let h=Te(e,s),x=Ie(e,s),I=(await((C=o.getMessages)==null?void 0:C.call(o))??[]).slice(-w),P=I.filter(N=>N&&typeof N.role=="string"&&typeof N.content=="string");P.length!==I.length&&console.warn(`Filtered ${I.length-P.length} invalid messages from history`);let _=no(P,m,h,x);await so(u,_,o.conn,t,e,l,n,s,r,o,i)}async function so(o,e,s,t,n,r,i,l,u,f,p){var a;let m=Date.now();if(!((a=f.env)!=null&&a.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(d,c)=>{var C,N,k,U,q,B,Q;let g,y={},w,h="none",x=!1,R,I=!1,P=!1,_=0,M=0,L=(C=n==null?void 0:n.data)==null?void 0:C.sendReasoning,F=L!==!1;try{let j=(N=n==null?void 0:n.data)==null?void 0:N.model,z=Array.isArray(j)?j[0]:j||"gpt_5_nano",T=qt(n==null?void 0:n.data),O=await it(z,f,T);if(!O)throw new Error(`Model '${z}' not found in registry`);g=O.modelHandle,y=O.effectiveParams||{},h=O.reasoning.kind;let A=Xt(O.reasoning,(k=n==null?void 0:n.data)==null?void 0:k.reasoningEffort);x=F&&Vt(O.reasoning);let H=typeof((U=n==null?void 0:n.data)==null?void 0:U.reasoningMaxTokens)=="number"?n.data.reasoningMaxTokens:void 0;w=Jt(O.provider,{effort:A,exposeReasoning:x,maxTokens:H}),A&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:A})),console.log(`[reasoning] ${JSON.stringify({model:z,provider:O.provider,capability:O.reasoning,requestedEffort:((q=n==null?void 0:n.data)==null?void 0:q.reasoningEffort)??null,resolvedEffort:A??null,sendReasoning:F,exposeReasoning:x,providerOptions:w??null},null,2)}`);for(let E of O.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:E});t==null||t({type:"info:llmNodeRunner:model",content:z}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(B=n==null?void 0:n.data)!=null&&B.generationPreset?{preset:n.data.generationPreset}:{},...y,...h!=="none"?{reasoning:h,configuredSendReasoning:L,sendReasoning:F,exposeReasoning:x,...A?{effort:A}:{}}:{}}})}catch(j){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(j)}`}),j}let $=await oo(f,l,n,t);if((Q=f.memoryConfig)!=null&&Q.enabled){let{recall:j}=await import("./recall-IABRCSHY.js");$.recall=j(f,l,void 0,t)}console.log(`[tools] node ${n.id} loaded ${Object.keys($).length}: ${Object.keys($).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:n.id,tools:Object.keys($)}});try{let j=ve({model:g,system:o,messages:e,stopWhen:(()=>{var E;let O=!!$.readSkillRef?10:5,A=Number(((E=n.data)==null?void 0:E.max_steps)??O),H=Number.isFinite(A)?Math.max(1,Math.min(30,A)):O;return Ze(H)})(),...Kt(y),...w?{providerOptions:w}:{},tools:$,onFinish:async T=>{var kt,bt;let O=T.text||"",A=T.reasoningText??((kt=T.reasoning)==null?void 0:kt.text)??"";if(console.log(`[reasoning] done: deltas=${_} chars=${M} result.reasoningText=${A.length} finishReason=${T.finishReason??"n/a"} reasoningTokens=${((bt=T.usage)==null?void 0:bt.reasoningTokens)??"n/a"}`),F&&x&&!I&&A&&s){I=!0;try{b(s,D.SERVER_REASONING_STREAM,A)}catch(Je){console.warn("Failed to send finished reasoning over connection",Je)}}let H={id:to(),role:"assistant",type:"text",content:O,ts:Date.now()};r&&(f.setMessages?await f.setMessages(H):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),s&&F&&I&&!P&&(P=!0,b(s,D.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),r&&s&&b(s,D.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),i==null||i((n==null?void 0:n.id)||"llm_result",O),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(T)});let E=Date.now()-m,Xe=R?R-m:void 0;p==null||p({type:"llm_telemetry",payload:{nodeId:n.id,totalLatency:E,timeToFirstToken:Xe,model:T.response.modelId,usage:T.usage}}),p==null||p({type:"llm_result",payload:{result:T}})},onStepFinish:async T=>{let O=(A,H=200)=>{let E=typeof A=="string"?A:JSON.stringify(A);return E?E.length>H?`${E.slice(0,H)}\u2026(+${E.length-H})`:E:""};if(T.toolCalls&&T.toolCalls.length>0){for(let A of T.toolCalls)console.log(`[tools] \u2192 ${A.toolName}(${O(A.args??A.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${n.id}`,content:JSON.stringify(T.toolCalls)})}if(T.toolResults&&T.toolResults.length>0){for(let A of T.toolResults)console.log(`[tools] \u2190 ${A.toolName} \u2192 ${O(A.result??A.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${n.id}`,content:JSON.stringify(T.toolResults)})}await eo(T,n,f,t)},experimental_onToolCallStart:T=>{var O;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(O=T==null?void 0:T.toolCall)==null?void 0:O.toolName,status:"start"}})},experimental_onToolCallFinish:T=>{var O,A;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(O=T==null?void 0:T.toolCall)==null?void 0:O.toolName,status:((A=T==null?void 0:T.toolOutput)==null?void 0:A.type)==="tool-error"?"error":"success"}})},onError:T=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),c(T)},onChunk:T=>{if(T.chunk.type==="reasoning-delta"){let A=T.chunk.text??T.chunk.delta??"";if(A&&(I=!0,_+=1,M+=A.length,_===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),F&&s&&A)try{b(s,D.SERVER_REASONING_STREAM,A)}catch(H){console.warn("Failed to send reasoning chunk over connection",H)}return}if(T.chunk.type==="text-delta"){if(R||(R=Date.now()),s&&F&&I&&!P){P=!0;try{b(s,D.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(A){console.warn("Failed to send reasoning complete over connection",A)}}return}p==null||p({type:T.chunk.type,payload:{nodeId:n.id,chunk:T.chunk}});let O=`llm_chunk:${T.chunk.type}`;t==null||t({type:O,content:{...T}})}}),z=async()=>{let T="";for await(let O of j.fullStream)if(O.type==="text-delta"){if(T+=O.text,r&&s)try{b(s,D.SERVER_TEXT_STREAM,O.text)}catch(A){console.warn("Failed to send chunk over connection",A)}}else if(O.type==="finish-step"&&O.finishReason==="tool-calls"){if(r&&s&&T.trim())try{b(s,D.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(A){console.warn("Failed to flush text segment over connection",A)}T=""}};await Promise.all([j,z()]),d(),t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"success"}})}catch(j){t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"error",error:String(j)}}),c(j)}})}function no(o,e,s,t){let n=!!(s&&s.length>0),r=!!t,i=n||r,u=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,f=p=>{let m=[],a="";if(r&&(a+=`[Attached files]
|
|
30
|
+
`:"")+c)}}return s}function Te(o,e){var t,n,r,i,l,d;let s=[];if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let f of o.data.varMapping){let u=f.from;if(!u)continue;let p=!1;if(u==="images")p=!0;else{let c=u.indexOf(".");if(c!==-1){let m=u.substring(0,c),a=u.substring(c+1).split(".")[0],g=(i=(r=(n=e.flowData)==null?void 0:n.state)==null?void 0:r.nodes)==null?void 0:i.find(y=>y.id===m);if(g){let w=B(g).find(h=>h.name===a);(w==null?void 0:w.type)==="image"&&(p=!0)}}}if(p){let c=Q(u,{context:e.context||{},results:e.results||{},nodes:((d=(l=e.flowData)==null?void 0:l.state)==null?void 0:d.nodes)||[]});Array.isArray(c)&&s.push(...c)}}return s}var to=rt({"../tools/composioTool.ts":()=>import("./composioTool-44B637WM.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-SFK4FG4Q.js"),"../tools/recall.ts":()=>import("./recall-IABRCSHY.js"),"../tools/skillTool.ts":()=>import("./skillTool-BSQFKZGK.js"),"../tools/tempTool.ts":()=>import("./tempTool-2RXAF56M.js"),"../tools/twitter.ts":()=>import("./twitter-OMDEG7T2.js"),"../tools/vectorize.ts":()=>import("./vectorize-UJXIDL2E.js")});var eo=rt({});function Pt(o,e,s,t,n){var i;if(!((i=t.memoryConfig)!=null&&i.enabled)||!t.memoryConfig.toolCache||!s.cacheable||!e||typeof e.execute!="function")return e;let r=e.execute.bind(e);return e.execute=async(l,...d)=>{var c;if(!t.getContextIndex)return r(l,...d);let f=await xt(l),p=(await t.getContextIndex()).find(m=>{if(m.domain!=="tool")return!1;let a=It(m.meta);return a.toolName===o&&a.paramsHash===f});if(p){let m=await((c=t.getContext)==null?void 0:c.call(t,p.ref));if((m==null?void 0:m.data)!=null&&It(m.meta).truncated!==!0){n==null||n({type:"info:memory:cacheHit",content:{ref:m.ref,toolName:o}});try{return JSON.parse(m.data)}catch{return m.data}}}return r(l,...d)},e}async function ro(o,e,s,t){var u,p;if(!((u=s.memoryConfig)!=null&&u.enabled)||!s.setContext||s.cycle==null)return;let n=o.toolCalls??[],r=o.toolResults??[];if(!n.length||!r.length)return;let i=new Map;for(let c of r)c!=null&&c.toolCallId&&i.set(c.toolCallId,c);let l=Array.isArray((p=e==null?void 0:e.data)==null?void 0:p.tools)?e.data.tools:[],d=new Map;for(let c of l)c&&typeof c.id=="string"&&d.set(c.id,c);let f=new Map;for(let c of Object.values(s.toolDefs??{}))c&&c.name&&f.set(c.name,c);for(let c of n){let m=c.toolCallId,a=c.toolName,g=i.get(m);if(!a||!g||a==="readSkillRef")continue;let y=c.args??c.input,w=g.result??g.output,h=!1,x="",R="tool",T="",M=f.get(a);M&&M.kind==="skill"&&(h=!0,x=`skill:${a}`,R="skill",T=`Skill instructions for ${a}`),x||(x=await Gt(a,y),T=St(y,w));let A=d.get(a)??l.find(F=>F.id===a),D=await xt(y),b=typeof w=="string"?w:JSON.stringify(w??null);await s.setContext({ref:x,domain:R,description:T,data:b,cycle:s.cycle,meta:JSON.stringify({toolName:a,paramsHash:D,cacheable:(A==null?void 0:A.cacheable)===!0})}),t==null||t({type:"info:memory:updated",content:{ref:x}})}}async function io(o,e,s,t){var p;let n=Array.isArray((p=s==null?void 0:s.data)==null?void 0:p.tools)?s.data.tools:[];if(n.length===0)return{};let r={},i=c=>{var x,R;let m=typeof(c==null?void 0:c.description)=="string"?c.description:"",a=c==null?void 0:c.inputSchema,g;try{let T=(a==null?void 0:a.shape)??(typeof((x=a==null?void 0:a._def)==null?void 0:x.shape)=="function"?a._def.shape():(R=a==null?void 0:a._def)==null?void 0:R.shape);T&&typeof T=="object"&&(g=T)}catch{}let y=g?Object.keys(g):[],w=m?`description="${m.length>120?m.slice(0,120)+"\u2026":m}"`:"description=(none)",h=y.length?`inputSchema={${y.join(", ")}}`:"inputSchema=(none)";return`${w} ${h}`},l=(()=>{let c=[],m=[],a=[],g=[];for(let w=0;w<n.length;w++){let h=n[w];!h||typeof h!="object"||typeof h.id!="string"?g.push(w):h.kind==="builtin"?c.push(h.id):h.kind==="skill"?a.push(h.id):h.kind==="http"||h.kind==="mcp"||h.kind==="composio"?m.push(h.id):g.push(w)}let y=[];return c.length&&y.push(`builtin[${c.join(", ")}]`),m.length&&y.push(`custom[${m.join(", ")}]`),a.length&&y.push(`skill[${a.join(", ")}]`),g.length&&y.push(`invalid@[${g.join(", ")}]`),y.join(" ")||"(none)"})();console.log(`[tools] node ${s.id} requested (${n.length}): ${l}`);let d=!1,f=async()=>{if(d&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},d=!0,o.toolDefs;try{let c=await se(o.env),m={};for(let a of c)a&&a.id&&(m[a.id]=a);o.toolDefs=m}catch(c){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(c)}`}),o.toolDefs=o.toolDefs||{}}return d=!0,o.toolDefs},u=[];for(let c=0;c<n.length;c++){let m=n[c];if(!m||typeof m!="object"||typeof m.id!="string"||m.kind!=="builtin"&&m.kind!=="http"&&m.kind!=="mcp"&&m.kind!=="composio"&&m.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${c}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let a=m;if(a.kind!=="builtin"){let y=(await f())[a.id];if(!y){console.error(`[tools] \u2717 custom '${a.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${a.id}' not found for this tenant`});continue}if(a.kind==="composio"){try{let h=await te(y,o,e,t),x=Object.keys(h);for(let[R,T]of Object.entries(h))r[R]=Pt(R,T,a,o,t);console.log(`[tools] \u2713 composio '${a.id}' \u2192 ${x.length} tool(s)`)}catch(h){console.error(`[tools] \u2717 composio '${a.id}': ${String(h)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${a.id}': ${String(h)}`})}continue}if(a.kind==="skill"){if(y.kind!=="skill"){console.error(`[tools] \u2717 skill '${a.id}': row is of kind '${y.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${a.id}' is not a skill`});continue}let h=y.name;if(r[h]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${h}' \u2014 builtin/other already registered, skipping skill '${a.id}'`});continue}try{r[h]=ne(y,o,e,t),u.push(y);let x=typeof y.execution=="string"?JSON.parse(y.execution):y.execution||{},R=Array.isArray(x.references)?x.references.map(T=>T==null?void 0:T.name):[];console.log(`[tools] \u2713 skill '${a.id}' \u2192 '${h}' (refs: ${R.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:h,refCount:R.length,refs:R}})}catch(x){console.error(`[tools] \u2717 skill '${a.id}': ${String(x)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${a.id}': ${String(x)}`})}continue}let w=y.name;if(r[w]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin already registered, skipping custom tool '${a.id}'`});continue}try{let h=oe(y,o,e,t);r[w]=Pt(w,h,a,o,t),console.log(`[tools] \u2713 custom '${a.id}' \u2192 '${w}'`),console.log(`[tools] ${i(r[w])}`)}catch(h){console.error(`[tools] \u2717 custom '${a.id}': ${String(h)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${a.id}': ${String(h)}`})}continue}if(!vt[a.id]){console.error(`[tools] \u2717 builtin '${a.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${a.id}' not found in registry`});continue}try{let g;try{g=await to(`../tools/${a.id}.ts`)}catch{g=await eo(`../tools/${a.id}.js`)}let y;if(g[a.id])y=g[a.id];else if(g.default)y=g.default;else if(g.create)y=g.create;else{let A=Object.values(g);A.length>0&&(y=A[0])}if(!y){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${a.id}'`});continue}let w,h,x={};if(a.params&&typeof a.params=="object"){if(typeof a.params.description=="string"?w=a.params.description:a.params.description!==void 0&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${a.id}' \u2014 must be a string`})),a.params.inputSchema!==void 0){let A=a.params.inputSchema;typeof A=="object"&&(typeof A.safeParse=="function"||A._def)?h=A:typeof A=="object"&&A!==null&&A.type==="object"&&A.properties?(h=ee(A),h||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${a.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${a.id}' \u2014 must be a Zod schema or JSON Schema object`})}a.params.defaults!==void 0?typeof a.params.defaults=="object"&&a.params.defaults!==null&&!Array.isArray(a.params.defaults)?x=a.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${a.id}' \u2014 must be an object`}),x={}):a.params.source!==void 0||a.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${a.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),x={}):x={}}let R=y(o,e,x,t);w&&R&&typeof R=="object"&&(R.description=w),h&&R&&typeof R=="object"&&(R.inputSchema=h),r[a.id]=Pt(a.id,R,a,o,t);let T=[];w&&T.push("description"),h&&T.push("inputSchema"),Object.keys(x).length&&T.push(`defaults(${Object.keys(x).join(",")})`);let M=T.length?` [overrides: ${T.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${a.id}'${M}`),console.log(`[tools] ${i(R)}`)}catch(g){console.error(`[tools] \u2717 builtin '${a.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${a.id}': ${String(g)}`});continue}}if(u.length>0)if(r.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{r.readSkillRef=re(o,u,e,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${u.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:u.map(c=>c.name)}})}catch(c){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(c)}`)}return r}async function Mt(o,e,s,t,n,r,i){var D,b,F,P,E;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let l=!1;try{let I=(D=s.flowData)==null?void 0:D.state;if(I&&I.edges&&I.nodes){let _=I.edges.filter($=>$.source===e.id);if(_.length>0){let $=I.nodes.find(L=>L.id===_[0].target);$&&$.type==="answerNode"&&(l=!0)}}}catch(I){console.error("Error determining next node for streaming:",I)}let d=S(e.data.template,e,s,t,{sessionEnv:o});(!d||!d.trim())&&(d="Answer straight forward to the user, dont offer any other option to continue");let f=d,u="";if((b=o.memoryConfig)!=null&&b.enabled){let I=await((F=o.getContextIndex)==null?void 0:F.call(o))??[];u=Wt(I),d+=u}let p=S(e.data.user_template||"",e,s,t,{sessionEnv:o}),c=I=>I&&Object.fromEntries(Object.keys(I).map(_=>[_,"[redacted]"])),m=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:c(o.secrets),userAuth:c(o.userAuth)}:o,a=S(e.data.template,e,s,void 0,{sessionEnv:m})||f;a+=u;let g=S(e.data.user_template||"",e,s,void 0,{sessionEnv:m});t==null||t({type:`info:llmNodeRunner:${e.id}`,content:a}),t==null||t({type:`info:llmNodeRunner:${e.id}`,content:g});let y=(P=e==null?void 0:e.data)==null?void 0:P.window_size,w=Number(y);(!Number.isInteger(w)||w<=0)&&(w=5);let h=Te(e,s),x=Ie(e,s),T=(await((E=o.getMessages)==null?void 0:E.call(o))??[]).slice(-w),M=T.filter(I=>I&&typeof I.role=="string"&&typeof I.content=="string");M.length!==T.length&&console.warn(`Filtered ${T.length-M.length} invalid messages from history`);let A=co(M,p,h,x);await ao(d,A,o.conn,t,e,l,n,s,r,o,i)}async function ao(o,e,s,t,n,r,i,l,d,f,u){var c;let p=Date.now();if(!((c=f.env)!=null&&c.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(m,a)=>{var E,I,_,$,L,Z,v;let g,y={},w,h="none",x=!1,R,T=!1,M=!1,A=0,D=0,b=(E=n==null?void 0:n.data)==null?void 0:E.sendReasoning,F=b!==!1;try{let j=(I=n==null?void 0:n.data)==null?void 0:I.model,G=Array.isArray(j)?j[0]:j||"gpt_5_nano",N=qt(n==null?void 0:n.data),O=await ct(G,f,N);if(!O)throw new Error(`Model '${G}' not found in registry`);g=O.modelHandle,y=O.effectiveParams||{},h=O.reasoning.kind;let C=Vt(O.reasoning,(_=n==null?void 0:n.data)==null?void 0:_.reasoningEffort);x=F&&Xt(O.reasoning);let q=typeof(($=n==null?void 0:n.data)==null?void 0:$.reasoningMaxTokens)=="number"?n.data.reasoningMaxTokens:void 0;w=Jt(O.provider,{effort:C,exposeReasoning:x,maxTokens:q}),C&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:C})),console.log(`[reasoning] ${JSON.stringify({model:G,provider:O.provider,capability:O.reasoning,requestedEffort:((L=n==null?void 0:n.data)==null?void 0:L.reasoningEffort)??null,resolvedEffort:C??null,sendReasoning:F,exposeReasoning:x,providerOptions:w??null},null,2)}`);for(let H of O.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:H});t==null||t({type:"info:llmNodeRunner:model",content:G}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(Z=n==null?void 0:n.data)!=null&&Z.generationPreset?{preset:n.data.generationPreset}:{},...y,...h!=="none"?{reasoning:h,configuredSendReasoning:b,sendReasoning:F,exposeReasoning:x,...C?{effort:C}:{}}:{}}})}catch(j){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(j)}`}),j}let P=await io(f,l,n,t);if((v=f.memoryConfig)!=null&&v.enabled){let{recall:j}=await import("./recall-IABRCSHY.js");P.recall=j(f,l,void 0,t)}console.log(`[tools] node ${n.id} loaded ${Object.keys(P).length}: ${Object.keys(P).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:n.id,tools:Object.keys(P)}});try{let j=so({model:g,system:o,messages:e,stopWhen:(()=>{var H;let O=!!P.readSkillRef?10:5,C=Number(((H=n.data)==null?void 0:H.max_steps)??O),q=Number.isFinite(C)?Math.max(1,Math.min(30,C)):O;return oo(q)})(),...Kt(y),...w?{providerOptions:w}:{},tools:P,onFinish:async N=>{var kt,bt;let O=N.text||"",C=N.reasoningText??((kt=N.reasoning)==null?void 0:kt.text)??"";if(console.log(`[reasoning] done: deltas=${A} chars=${D} result.reasoningText=${C.length} finishReason=${N.finishReason??"n/a"} reasoningTokens=${((bt=N.usage)==null?void 0:bt.reasoningTokens)??"n/a"}`),F&&x&&!T&&C&&s){T=!0;try{k(s,U.SERVER_REASONING_STREAM,C)}catch(Ge){console.warn("Failed to send finished reasoning over connection",Ge)}}let q={id:no(),role:"assistant",type:"text",content:O,ts:Date.now()};r&&(f.setMessages?await f.setMessages(q):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),s&&F&&T&&!M&&(M=!0,k(s,U.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),r&&s&&k(s,U.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),i==null||i((n==null?void 0:n.id)||"llm_result",O),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(N)});let H=Date.now()-p,Se=R?R-p:void 0;u==null||u({type:"llm_telemetry",payload:{nodeId:n.id,totalLatency:H,timeToFirstToken:Se,model:N.response.modelId,usage:N.usage}}),u==null||u({type:"llm_result",payload:{result:N}})},onStepFinish:async N=>{let O=(C,q=200)=>{let H=typeof C=="string"?C:JSON.stringify(C);return H?H.length>q?`${H.slice(0,q)}\u2026(+${H.length-q})`:H:""};if(N.toolCalls&&N.toolCalls.length>0){for(let C of N.toolCalls)console.log(`[tools] \u2192 ${C.toolName}(${O(C.args??C.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${n.id}`,content:JSON.stringify(N.toolCalls)})}if(N.toolResults&&N.toolResults.length>0){for(let C of N.toolResults)console.log(`[tools] \u2190 ${C.toolName} \u2192 ${O(C.result??C.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${n.id}`,content:JSON.stringify(N.toolResults)})}await ro(N,n,f,t)},experimental_onToolCallStart:N=>{var O;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(O=N==null?void 0:N.toolCall)==null?void 0:O.toolName,status:"start"}})},experimental_onToolCallFinish:N=>{var O,C;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(O=N==null?void 0:N.toolCall)==null?void 0:O.toolName,status:((C=N==null?void 0:N.toolOutput)==null?void 0:C.type)==="tool-error"?"error":"success"}})},onError:N=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),a(N)},onChunk:N=>{if(N.chunk.type==="reasoning-delta"){let C=N.chunk.text??N.chunk.delta??"";if(C&&(T=!0,A+=1,D+=C.length,A===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),F&&s&&C)try{k(s,U.SERVER_REASONING_STREAM,C)}catch(q){console.warn("Failed to send reasoning chunk over connection",q)}return}if(N.chunk.type==="text-delta"){if(R||(R=Date.now()),s&&F&&T&&!M){M=!0;try{k(s,U.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(C){console.warn("Failed to send reasoning complete over connection",C)}}return}u==null||u({type:N.chunk.type,payload:{nodeId:n.id,chunk:N.chunk}});let O=`llm_chunk:${N.chunk.type}`;t==null||t({type:O,content:{...N}})}}),G=async()=>{let N="";for await(let O of j.fullStream)if(O.type==="text-delta"){if(N+=O.text,r&&s)try{k(s,U.SERVER_TEXT_STREAM,O.text)}catch(C){console.warn("Failed to send chunk over connection",C)}}else if(O.type==="finish-step"&&O.finishReason==="tool-calls"){if(r&&s&&N.trim())try{k(s,U.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(C){console.warn("Failed to flush text segment over connection",C)}N=""}};await Promise.all([j,G()]),m(),t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"success"}})}catch(j){t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"error",error:String(j)}}),a(j)}})}function co(o,e,s,t){let n=!!(s&&s.length>0),r=!!t,i=n||r,d=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,f=u=>{let p=[],c="";if(r&&(c+=`[Attached files]
|
|
31
31
|
${t}
|
|
32
32
|
[End of attached files]
|
|
33
33
|
|
|
34
|
-
`),
|
|
34
|
+
`),u&&(c+=u),c&&p.push({type:"text",text:c}),n)for(let m of s)p.push({type:"image",image:m.data,mimeType:m.mimeType});return p};return e&&d&&d.content===e?[...o.slice(0,-1).map(p=>({role:p.role,content:p.content})),{role:"user",content:f(e)}]:e?[...o.map(u=>({role:u.role,content:u.content})),{role:"user",content:f(e)}]:i&&d?[...o.slice(0,-1).map(p=>({role:p.role,content:p.content})),{role:"user",content:f(d.content)}]:o.map(u=>({role:u.role,content:u.content}))}async function Ft(o,e,s,t,n,r,i){var f,u,p,c;console.log(`**** MEMO Node id: ${e.id} ****`),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let l="",d=Date.now();try{if(t==null||t({type:"info:memoNodeRunner",content:"Starting memo node execution"}),((f=s==null?void 0:s.context)==null?void 0:f[e.data.query_key])===void 0){t==null||t({type:"error:memoNodeRunner",content:`Query key ${e.data.query_key} not found in context`}),n==null||n(e.id,l);return}if(!o.env||!o.ctx){t==null||t({type:"error:memoNodeRunner",content:"Missing env or ctx"}),n==null||n(e.id,l);return}if(!e.data.rag_id){t==null||t({type:"error:memoNodeRunner",content:"Missing rag_id"}),n==null||n(e.id,l);return}let m=((u=s==null?void 0:s.context)==null?void 0:u[e.data.query_key])||"";t==null||t({type:"info:memoNodeRunner",content:`Query text: ${m}`}),t==null||t({type:"info:memoNodeRunner",content:"Generating embedding for query"});let a=await Lt(o,m,!0);t==null||t({type:"info:memoNodeRunner",content:`Embedding generated successfully, length: ${a.data[0].length}`});let g=Array.isArray(e.data.rag_id)?e.data.rag_id:[e.data.rag_id],y=[];for(let R of g){t==null||t({type:"info:memoNodeRunner",content:`Executing RAG query with namespace: ${R}`});let T=await o.env[`VDB_${(p=s.flowData)==null?void 0:p.tenant}_1024`].query(a.data[0],{namespace:R,topK:e.data.topk,returnMetadata:"all"});t==null||t({type:"info:memoNodeRunner",content:`RAG query completed for namespace ${R}, matches: ${((c=T.matches)==null?void 0:c.length)||0}`}),Array.isArray(T.matches)&&y.push(...T.matches)}let w=Date.now()-d;l=y.map(R=>{var T;return(T=R.metadata)==null?void 0:T.value}).filter(R=>typeof R=="string").join(`
|
|
35
35
|
|
|
36
|
-
`),i==null||i({type:"memo_search",payload:{nodeId:e.id,searchLatencyMs:w,retrievedContext:l}}),t==null||t({type:"info:memoNodeRunner",content:`Context retrieval complete, length: ${l.length}, preview: ${l.substring(0,200)}...`}),t==null||t({type:"info:memoNodeRunner",content:"Memo node execution completed successfully"})}catch(
|
|
37
|
-
${
|
|
36
|
+
`),i==null||i({type:"memo_search",payload:{nodeId:e.id,searchLatencyMs:w,retrievedContext:l}}),t==null||t({type:"info:memoNodeRunner",content:`Context retrieval complete, length: ${l.length}, preview: ${l.substring(0,200)}...`}),t==null||t({type:"info:memoNodeRunner",content:"Memo node execution completed successfully"})}catch(m){console.error("Error processing MemoNode:",m),t==null||t({type:"error:memoNodeRunner",content:`Memo node execution failed: ${m}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(m)}})}finally{n==null||n(e.id,l),t==null||t({type:"info:memoNodeRunner",content:`onResult called with context length: ${l.length}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}}async function Dt(o,e,s,t,n,r,i){var u,p,c,m,a,g,y;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:s}),i==null||i({type:"start_node",payload:{userMessage:(u=s==null?void 0:s.context)==null?void 0:u.user_input}});let l=((p=e.data)==null?void 0:p.allow_images)!==!1,d=((c=e.data)==null?void 0:c.allow_documents)!==!1;!l&&(s!=null&&s.context)&&(s.context.user_images=[],r==null||r({...s})),!d&&(s!=null&&s.context)&&(s.context.files="",r==null||r({...s}));let f={};for(let w of Y(e.data))f[w.name]=(m=s==null?void 0:s.context)==null?void 0:m[w.name];n==null||n(e.id,{...f,user_input:(a=s==null?void 0:s.context)==null?void 0:a.user_input,images:l?(g=s==null?void 0:s.context)==null?void 0:g.user_images:[],files:d?(y=s==null?void 0:s.context)==null?void 0:y.files:""}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}function Ce(o,e,s){let t=e;async function n(){var f;if(await((f=s==null?void 0:s.shouldStop)==null?void 0:f.call(s)))throw new wt}async function r(f){let u=f;for(t.executedNodes=t.executedNodes||[],t.context=t.context||{},t.results=t.results||{};u&&u.id;)await n(),await i(u),await n(),u=po(u,t.flowData,t)}async function i(f){var a;let u=d[f.type];if(!u){(a=s==null?void 0:s.onError)==null||a.call(s,`Unknown node type: ${f.type}`);return}let p=g=>{var y;return(y=s==null?void 0:s.onServerEvent)==null?void 0:y.call(s,{...g,ts:Date.now()})},c=g=>{var y,w;if((y=s==null?void 0:s.onTelemetry)==null||y.call(s,g),g.type==="llm_telemetry"||g.type==="class_telemetry"){let h=(w=g.payload)==null?void 0:w.usage;h&&(t.tokenUsage=t.tokenUsage||{promptTokens:0,completionTokens:0,totalTokens:0},t.tokenUsage.promptTokens+=h.promptTokens||0,t.tokenUsage.completionTokens+=h.completionTokens||0,t.tokenUsage.totalTokens+=h.totalTokens||0)}};return await u(o,f,t,p,(g,y)=>{t.results[g]=y},s==null?void 0:s.onChangeState,c)}let l=async f=>{var m,a,g,y,w,h,x;let u=Date.now(),p="completed",c;try{await n();let R=typeof f=="string"?at(f):f,T=(R==null?void 0:R.text)||"",M=(R==null?void 0:R.images)||[],A=(R==null?void 0:R.documents)||[],D=await we(A,o.env),b=D.length>0?D.map(E=>`--- file: ${E.name} ---
|
|
37
|
+
${E.text}`).join(`
|
|
38
38
|
|
|
39
|
-
`):"";t.context={user_input:I,user_images:P,files:L},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},(d=s==null?void 0:s.onServerEvent)==null||d.call(s,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:F,error:$}=ro(t.flowData);if(!F)m="failed",a=$||"Flow Format Error",(c=s==null?void 0:s.onError)==null||c.call(s,a);else{let C=Y(F.data),{values:N,errors:k}=jt(C,R==null?void 0:R.inputs);if(k.length>0)return m="failed",a=`Invalid flow inputs: ${k.join("; ")}`,(g=s==null?void 0:s.onError)==null||g.call(s,a),{status:m,error:a};t.context={...t.context,inputs:N,...N},t.context.user_input||(t.context.user_input=I),await r(F),(y=s==null?void 0:s.onServerEvent)==null||y.call(s,{type:"agent:telemetry",content:{durationMs:Date.now()-p,tokenUsage:t.tokenUsage},timestamp:Date.now()})}}catch(R){R instanceof wt?(m="stopped",a=R.message,(w=s==null?void 0:s.onServerEvent)==null||w.call(s,{type:"agent:stopped",content:a,timestamp:Date.now()})):(m="failed",a=R instanceof Error?R.message:"Agent execution failed",(h=s==null?void 0:s.onError)==null||h.call(s,a))}finally{(x=s==null?void 0:s.onServerEvent)==null||x.call(s,{type:"agent:complete",content:{status:m,durationMs:Date.now()-p},timestamp:Date.now()})}return{status:m,error:a}},u={startNode:Dt,classifierNode:$t,llmNode:Ft,memoNode:Mt,answerNode:At,apiNode:Ot};return l}var wt=class extends Error{constructor(){super("Stopped by user"),this.name="FlowExecutionStoppedError"}};function ro(o){var p;let e=(o==null?void 0:o.state)??o;if(!e||!e.nodes||!e.edges||e.edges.length===0)return{error:"Flow is missing state, nodes, or edges."};let s=e.nodes.filter(m=>m.type==="startNode");if(s.length!==1)return{error:`Flow must include exactly one START node, found ${s.length}.`};let t=s[0],n=e.nodes.filter(m=>m.type==="answerNode");if(n.length===0)return{error:"Flow must include at least one ANSWER node."};let r=new Map;for(let m of e.edges)r.has(m.source)||r.set(m.source,[]),r.get(m.source).push(m.target);let i=new Map;for(let m of e.edges)i.has(m.target)||i.set(m.target,[]),i.get(m.target).push(m.source);let l=Ne(t.id,r),u=new Set;for(let m of n){let a=Ne(m.id,i);for(let d of a)u.add(d)}let f=[];for(let m of l)if(!u.has(m)){let a=e.nodes.find(d=>d.id===m);if(a){let d=((p=a.data)==null?void 0:p.label)||"";f.push(`${m}(${d},${a.type})`)}}return f.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${f.join(", ")}`}:{startNode:t}}function Ne(o,e){let s=new Set,t=[o];for(s.add(o);t.length>0;){let n=t.shift(),r=e.get(n)||[];for(let i of r)s.has(i)||(s.add(i),t.push(i))}return s}function io(o,e){var s;return((s=o.state)==null?void 0:s.nodes.find(t=>t.id===e))||null}function ao(o,e,s){var l;let t=e==null?void 0:e.state;if(!t)return null;let n=t.edges.filter(u=>u.source===o.id);if(n.length===0)return null;let r=n[0].target;if(o.type==="classifierNode"&&((l=s==null?void 0:s.context)!=null&&l.classified_id)){let u=s.context.classified_id,f=n.find(p=>p.sourceHandle===`source-${u}`);f?r=f.target:console.log(`No matching edge, falling back to first: ${r}`)}return io(e,r)}async function Ae(o,e){var t,n;let s=(t=e==null?void 0:e.flowData)==null?void 0:t.flowId;if(!(o!=null&&o.HX_CORE_URL)||!s)return{engineState:e,refreshed:!1};try{let r=await W(s,o),i={...e,flowData:{...r,tenant:e.flowData.tenant,flowId:s,chatId:e.flowData.chatId}},l=r==null?void 0:r.stateVersion,u=typeof l=="number"&&l!==((n=e.flowData)==null?void 0:n.stateVersion);return{engineState:i,refreshed:u}}catch(r){return console.error(`[flowRefresh] fetch failed for flow ${s}:`,r),{engineState:e,refreshed:!1}}}function _e(o,e){return!o||!o.HX_ORA_URL||!o.HX_API_KEY?Promise.resolve():fetch(`${o.HX_ORA_URL}/internal/sessions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:o.HX_API_KEY},body:JSON.stringify(e)}).catch(s=>{console.error("[sessionIndex] failed to index session",s)})}var Oe=async(o,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),`${JSON.stringify(o)}`};async function et(o,e){var r,i;let s=o.id||o.name||"",[t,n]=String(s).split("::");if(!t||!n)return null;try{let u=(r=(await X(t,e)).metadata)==null?void 0:r.tenant,f=await W(t,e),p=(i=o.state)==null?void 0:i.user,m={flowData:{...f,tenant:u,flowId:t,chatId:n},executedNodes:[],context:p?{user:p}:{}};return o.setState({...o.state,engineState:m}),m}catch(l){return console.error("Failed to initialize engine state:",l),null}}async function ot(o){var _,M,L,F,$;let{agent:e,env:s,ctx:t,payload:n,connection:r}=o,i=Date.now(),l=[],u=async()=>await V(e),f=async C=>{await ie(e,C)},p=async C=>{if(e.state.modelsCache&&e.state.modelsCache[C])return e.state.modelsCache[C];try{let{fetchOraModel:N}=await import("./oraApi-YIJGMXX7.js"),k=await N(C,s);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[C]:k}}),k}catch(N){throw console.error(`Error fetching model ${C}:`,N),N}},m={id:co(),role:"user",type:"text",content:n.text,images:n.images,ts:Date.now()};await f(m);let a={onChangeState:C=>{e.setState({...e.state,engineState:C})},onServerEvent:async C=>{var N;await((N=o.onServerEvent)==null?void 0:N.call(o,C)),l.push(C)},onTelemetry:async C=>{var N,k,U,q,B,Q;await Oe({...C,userId:o.resolveUserId(),tenant:((k=(N=e.state.engineState)==null?void 0:N.flowData)==null?void 0:k.tenant)||"",flowId:((q=(U=e.state.engineState)==null?void 0:U.flowData)==null?void 0:q.flowId)||"",sessionId:((Q=(B=e.state.engineState)==null?void 0:B.flowData)==null?void 0:Q.chatId)||""},s)},onError:C=>{var N;(N=o.onError)==null||N.call(o,C),e.setState({...e.state,error:C})},shouldStop:o.shouldStop},d=e.state.engineState?{...e.state.engineState}:null;if(d){let{engineState:C,refreshed:N}=await Ae(s,d);d=C,N&&e.setState({...e.state,engineState:d,modelsCache:{}})}else if(d=await et(e,s),!d){let C="Failed to initialize agent";return a.onError(C),{status:"failed",error:C}}let c=o.secrets;if(!c||Object.keys(c).length===0){let C=(_=d.flowData)==null?void 0:_.tenant;c=C?await ht(s,C):{},(M=o.onSecretsLoaded)==null||M.call(o,c)}let g=o.user??e.state.user??void 0;g&&!((L=d.context)!=null&&L.user)&&(d.context={...d.context||{},user:g});let y=at(tt(d)),w=typeof d.cycle=="number"?d.cycle:0;y.enabled&&(w=await ye(e,d),d.cycle=w,e.setState({...e.state,engineState:d}));let h=he(e,{env:s,ctx:t,conn:r,getMessages:u,setMessages:f,getOraModel:p,secrets:c,userAuth:o.userAuth,user:g,composioSessions:o.composioSessions,publicOrigin:o.publicOrigin,skillRefCache:o.skillRefCache},d,w,o.onMemoryRef),x=await Ce(h,d,a)(n),{tenant:R,flowId:I,chatId:P}=d.flowData??{};return R&&I&&P&&t.waitUntil(_e(s,{id:`${I}::${P}`,tenant:R,flowId:I,sessionId:P,userId:o.resolveUserId(),title:(F=n.text)==null?void 0:F.slice(0,120),turnTs:i,events:l})),x.status==="completed"&&(($=h.memoryConfig)!=null&&$.enabled)&&h.memoryConfig.mode==="summarize"&&t&&t.waitUntil(Yt(e,h,w)),e.setState({...e.state,lastUpdated:new Date}),{status:x.status,error:x.error,engineState:d}}import{nanoid as lo}from"nanoid";function uo(o){let e=o.headers.get("X-User-Payload");if(!e)return null;try{let s=JSON.parse(e),t=typeof(s==null?void 0:s.email)=="string"?Z(s.email):null;return t?{...s,email:t}:null}catch{return null}}async function $e(o,e,s,t){var n;try{let r=await e.json(),i=r.message;if(!i||typeof i!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let l=typeof r.userId=="string"?Z(r.userId):null,u=uo(e),f=u==null?void 0:u.email;u?o.setState({...o.state,user:u,injectedUserId:f}):l&&!((n=o.state.user)!=null&&n.email)&&o.setState({...o.state,injectedUserId:l});let p=()=>f??l??o.state.injectedUserId??void 0;o.skillRefCache||(o.skillRefCache=new Map);let m=r.inputs&&typeof r.inputs=="object"?r.inputs:void 0;if(!o.state.engineState&&!await et(o,s))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let a=f?`run-${lo(12)}`:null;a&&(await o.registerManualRun(a,i,f),await v(s,a).catch(y=>{console.warn(`[AgentHTTP] could not mark manual run ${a} as running`,y)}));let d;try{d=await ot({agent:o,env:s,ctx:t,payload:{text:i,inputs:m},skillRefCache:o.skillRefCache,user:u??void 0,resolveUserId:p,shouldStop:a?()=>o.isRunStopRequested(a):void 0}),a&&t.waitUntil(o.completeManualRun(a,d.status==="completed"?"succeeded":d.status==="stopped"?"skipped":"failed",d.error))}finally{a&&await o.clearRunStopRequest(a)}if(d.status==="failed")return new Response(JSON.stringify({error:d.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});if(d.status==="stopped")return new Response(JSON.stringify({error:d.error||"Stopped by user"}),{status:409,headers:{"content-type":"application/json"}});let g=(await V(o)).reverse().find(y=>y.role==="assistant");return new Response(JSON.stringify({answer:(g==null?void 0:g.content)||""}),{headers:{"content-type":"application/json"}})}catch(r){return new Response(JSON.stringify({error:r.message}),{status:500,headers:{"content-type":"application/json"}})}}async function Pe(o){try{return await ut(o),await mt(o),o.skillRefCache&&o.skillRefCache.clear(),o.setState({...o.state,error:"",engineState:void 0,modelsCache:{},lastUpdated:new Date}),new Response(JSON.stringify({success:!0,messages:[]}),{headers:{"content-type":"application/json"}})}catch(e){return new Response(JSON.stringify({error:e.message}),{status:500,headers:{"content-type":"application/json"}})}}var Fe="trigger:nonce:",mo=900*1e3,Ut="run:stop:",Me=class extends po{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{}};resolveSessionUserId(){var e;return((e=this.state.user)==null?void 0:e.email)??this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async inspectPersistedSession(e){return e==="state"?{state:this.state}:e==="messages"?{messages:await V(this)}:{context:await ce(this)}}async requestRunStop(e){return e!=null&&e.trim()?(await this.ctx.storage.put(`${Ut}${e}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(e){return!!await this.ctx.storage.get(`${Ut}${e}`)}async clearRunStopRequest(e){await this.ctx.storage.delete(`${Ut}${e}`)}async onRequest(e){let s=new URL(e.url);if(s.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(s.pathname.endsWith("/history")){let t=await V(this);return new Response(JSON.stringify(t),{headers:{"content-type":"application/json"}})}if(s.pathname.endsWith("/context")){let t={"content-type":"application/json","access-control-allow-origin":"*"};if(!e.headers.get("X-User-Payload"))return new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:t});let n=s.searchParams.get("ref");if(n){let i=await ft(this,n);return i?new Response(JSON.stringify({entry:i}),{headers:t}):new Response(JSON.stringify({error:"Not found"}),{status:404,headers:t})}let r=await pt(this);return new Response(JSON.stringify({entries:r}),{headers:t})}return e.method==="POST"&&s.pathname.endsWith("/message")?$e(this,e,this.env,this.ctx):e.method==="DELETE"&&s.pathname.endsWith("/clear")?Pe(this):new Response("Ready to assist.")}async onConnect(e,s){var a,d,c,g,y;let[t,n]=e.server.split("::"),i=(a=(await X(t,this.env)).metadata)==null?void 0:a.tenant;this.secrets=await ht(this.env,i),this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let l=null;if(s.request){try{this.publicOrigin=new URL(s.request.url).origin}catch{}let w=s.request.headers.get("X-User-Payload");if(w)try{l=JSON.parse(w)}catch(h){console.warn("Failed to parse X-User-Payload",h)}}let u=await W(t,this.env);this.setState({...this.state,user:l||null,sessionId:n,engineState:{flowData:{...u,tenant:i,flowId:t,chatId:n},executedNodes:[],context:l?{user:l}:{}}}),l||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let f=await V(this);b(e,D.SERVER_HISTORY,JSON.stringify({messages:f}));let m=(((d=u==null?void 0:u.state)==null?void 0:d.nodes)??(u==null?void 0:u.nodes)??[]).find(w=>w.type==="startNode");if(m){let w={allow_images:((c=m.data)==null?void 0:c.allow_images)??!1,allow_documents:((g=m.data)==null?void 0:g.allow_documents)??!1,greeting:(y=m.data)==null?void 0:y.greeting};b(e,D.SERVER_CONFIG,JSON.stringify(w))}}async onMessage(e,s){if(typeof s!="string")return;let t=s.indexOf(":");if(t===-1)return;let n=s.substring(0,t),r=s.substring(t+1);if(!n||!r)return;let l={[D.USER_MESSAGE]:u=>this.onUserMessage(e,u),[D.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[D.USER_AUTH]:u=>this.onUserAuth(e,u),[D.USER_IDENTITY]:u=>this.onUserIdentity(e,u)}[n];l&&await l(r)}async onUserMessage(e,s){let t=rt(s),n=this.hasAuditableUser()?`run-${fo(12)}`:null;n&&(await this.registerManualRun(n,t.text),await v(this.env,n).catch(r=>{console.warn(`[AgentDO] could not mark manual run ${n} as running`,r)}));try{let r=await ot({agent:this,env:this.env,ctx:this.ctx,payload:t,connection:e,secrets:this.secrets,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:this.state.user,resolveUserId:()=>this.resolveSessionUserId(),shouldStop:n?()=>this.isRunStopRequested(n):void 0,onServerEvent:i=>{b(e,D.SERVER_EVENT,JSON.stringify(i))},onError:i=>{b(e,D.SERVER_ERROR,i)},onMemoryRef:i=>{b(e,D.SERVER_EVENT,JSON.stringify({type:"info:memory:updated",content:{ref:i}}))},onSecretsLoaded:i=>{this.secrets=i}});n&&this.ctx.waitUntil(this.completeManualRun(n,r.status==="completed"?"succeeded":r.status==="stopped"?"skipped":"failed",r.error))}finally{n&&await this.clearRunStopRequest(n)}}hasAuditableUser(e){var s;return!!(e||(s=this.state.user)!=null&&s.email)}registerManualRun(e,s,t){var u,f;let{tenant:n,flowId:r,chatId:i}=((u=this.state.engineState)==null?void 0:u.flowData)??{},l=t||((f=this.state.user)==null?void 0:f.email);return!n||!r||!i||!l?Promise.resolve():me(this.env,{id:e,tenant:n,flowId:r,userId:l,sessionId:i,label:s==null?void 0:s.slice(0,120)})}completeManualRun(e,s,t){return yt(this.env,e,{status:s,error:t})}async enqueueTrigger(e){var n;if(!(e!=null&&e.runId)||!(e!=null&&e.flowId))return{queued:!1};if(e.nonce&&!await this.claimTriggerNonce(e.nonce))return console.warn(`[AgentDO] rejected replayed trigger nonce ${e.nonce}`),{queued:!1,duplicate:!0};let s=e.runAsUserId;return s&&!((n=this.state.user)!=null&&n.email)&&this.state.injectedUserId!==s&&this.setState({...this.state,injectedUserId:s}),{queued:!0,taskId:await this.queue("processTrigger",e)}}async claimTriggerNonce(e){let s=`${Fe}${e}`;if(await this.ctx.storage.get(s))return!1;let t=Date.now();await this.ctx.storage.put(s,t);let r=[...(await this.ctx.storage.list({prefix:Fe})).entries()].filter(([,i])=>t-i>mo).map(([i])=>i);return r.length>0&&await this.ctx.storage.delete(r),!0}async processTrigger(e){if(!(await v(this.env,e.runId)).claimed){console.warn(`[AgentDO] activation ${e.activationId} skipped \u2014 run ${e.runId} already claimed`);return}try{this.state.engineState||await et(this,this.env);let t=Y(tt(this.state.engineState)),n=Et(t,e.inputs||{},e.label),r=await ot({agent:this,env:this.env,ctx:this.ctx,payload:{text:n,inputs:e.inputs||{}},secrets:this.secrets,composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>e.runAsUserId||this.resolveSessionUserId(),shouldStop:()=>this.isRunStopRequested(e.runId),onSecretsLoaded:i=>{this.secrets=i}});await yt(this.env,e.runId,{status:r.status==="completed"?"succeeded":r.status==="stopped"?"skipped":"failed",error:r.error})}catch(t){let n=t instanceof Error?t.message:"Trigger execution failed";throw await yt(this.env,e.runId,{status:"failed",error:n}),t}finally{await this.clearRunStopRequest(e.runId)}}async onUserIdentity(e,s){let t=Z(s);if(!t){b(e,D.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:t}),b(e,D.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,s){let t=Ht(s);if(!t){b(e,D.SERVER_ERROR,"Invalid auth payload");return}let n=t.value.trim();n===""?delete this.userAuth[t.name]:this.userAuth[t.name]=t.value,b(e,D.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:t.name,set:n!==""}}))}async onClearHistory(e){await ut(this),await mt(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear();let s=this.state.engineState?{...this.state.engineState,cycle:void 0}:void 0;this.setState({...this.state,error:"",engineState:s,modelsCache:{},lastUpdated:new Date}),e&&b(e,D.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await fe(this);let e=await V(this);`${JSON.stringify(e)}`}async onClose(e,s,t,n){console.log(`Session closed: ${this.state.sessionId} ${s} - ${t}`)}async onError(e){console.error("AgentDO encountered an error:",e)}};function ir(o){let e=o.state;if(!e)return null;let s=["startNode","answerNode"];for(let t of s)if(!e.nodes.some(r=>r.type===t))return!1;return e.nodes.find(t=>t.type==="startNode")}import{importSPKI as go,jwtVerify as yo}from"jose";function De(o){let e={};if(!o)return e;let s=o.split(";");for(let t of s){let n=t.indexOf("=");if(n>-1){let r=t.slice(0,n).trim(),i=t.slice(n+1).trim();r&&(e[r]=decodeURIComponent(i))}}return e}function ho(o){return(typeof o.email=="string"?o.email.trim():"")||null}async function J(o,e,s){let t=De(o.headers.get("cookie")),n=new URL(o.url),r=t.access_token||n.searchParams.get("access_token"),i=await wo(e,r);if(i.ok){let l=i.payload,u=ho(l);return u?{id:l.sub,email:u,name:l.name,first_name:l.given_name,last_name:l.family_name,tenant:l.tenant,roles:l["ora-roles"],db_name:l.db_name||null,user_id:l.user_id||null}:null}return null}async function wo(o,e){if(!e||typeof e!="string")return{ok:!1,payload:null,protectedHeader:null};if(!o.KC_RS256_PK)throw new Error("PK is not defined");let s=`-----BEGIN PUBLIC KEY-----
|
|
39
|
+
`):"";t.context={user_input:T,user_images:M,files:b},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},(m=s==null?void 0:s.onServerEvent)==null||m.call(s,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:F,error:P}=lo(t.flowData);if(!F)p="failed",c=P||"Flow Format Error",(a=s==null?void 0:s.onError)==null||a.call(s,c);else{let E=Y(F.data),{values:I,errors:_}=jt(E,R==null?void 0:R.inputs);if(_.length>0)return p="failed",c=`Invalid flow inputs: ${_.join("; ")}`,(g=s==null?void 0:s.onError)==null||g.call(s,c),{status:p,error:c};t.context={...t.context,inputs:I,...I},t.context.user_input||(t.context.user_input=T),await r(F),(y=s==null?void 0:s.onServerEvent)==null||y.call(s,{type:"agent:telemetry",content:{durationMs:Date.now()-u,tokenUsage:t.tokenUsage},timestamp:Date.now()})}}catch(R){R instanceof wt?(p="stopped",c=R.message,(w=s==null?void 0:s.onServerEvent)==null||w.call(s,{type:"agent:stopped",content:c,timestamp:Date.now()})):(p="failed",c=R instanceof Error?R.message:"Agent execution failed",(h=s==null?void 0:s.onError)==null||h.call(s,c))}finally{(x=s==null?void 0:s.onServerEvent)==null||x.call(s,{type:"agent:complete",content:{status:p,durationMs:Date.now()-u},timestamp:Date.now()})}return{status:p,error:c}},d={startNode:Dt,classifierNode:$t,llmNode:Mt,memoNode:Ft,answerNode:At,apiNode:_t};return l}var wt=class extends Error{constructor(){super("Stopped by user"),this.name="FlowExecutionStoppedError"}};function lo(o){var u;let e=(o==null?void 0:o.state)??o;if(!e||!e.nodes||!e.edges||e.edges.length===0)return{error:"Flow is missing state, nodes, or edges."};let s=e.nodes.filter(p=>p.type==="startNode");if(s.length!==1)return{error:`Flow must include exactly one START node, found ${s.length}.`};let t=s[0],n=e.nodes.filter(p=>p.type==="answerNode");if(n.length===0)return{error:"Flow must include at least one ANSWER node."};let r=new Map;for(let p of e.edges)r.has(p.source)||r.set(p.source,[]),r.get(p.source).push(p.target);let i=new Map;for(let p of e.edges)i.has(p.target)||i.set(p.target,[]),i.get(p.target).push(p.source);let l=Ne(t.id,r),d=new Set;for(let p of n){let c=Ne(p.id,i);for(let m of c)d.add(m)}let f=[];for(let p of l)if(!d.has(p)){let c=e.nodes.find(m=>m.id===p);if(c){let m=((u=c.data)==null?void 0:u.label)||"";f.push(`${p}(${m},${c.type})`)}}return f.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${f.join(", ")}`}:{startNode:t}}function Ne(o,e){let s=new Set,t=[o];for(s.add(o);t.length>0;){let n=t.shift(),r=e.get(n)||[];for(let i of r)s.has(i)||(s.add(i),t.push(i))}return s}function uo(o,e){var s;return((s=o.state)==null?void 0:s.nodes.find(t=>t.id===e))||null}function po(o,e,s){var l;let t=e==null?void 0:e.state;if(!t)return null;let n=t.edges.filter(d=>d.source===o.id);if(n.length===0)return null;let r=n[0].target;if(o.type==="classifierNode"&&((l=s==null?void 0:s.context)!=null&&l.classified_id)){let d=s.context.classified_id,f=n.find(u=>u.sourceHandle===`source-${d}`);f?r=f.target:console.log(`No matching edge, falling back to first: ${r}`)}return uo(e,r)}async function Ae(o,e){var t,n;let s=(t=e==null?void 0:e.flowData)==null?void 0:t.flowId;if(!(o!=null&&o.HX_CORE_URL)||!s)return{engineState:e,refreshed:!1};try{let r=await z(s,o),i={...e,flowData:{...r,tenant:e.flowData.tenant,flowId:s,chatId:e.flowData.chatId}},l=r==null?void 0:r.stateVersion,d=typeof l=="number"&&l!==((n=e.flowData)==null?void 0:n.stateVersion);return{engineState:i,refreshed:d}}catch(r){return console.error(`[flowRefresh] fetch failed for flow ${s}:`,r),{engineState:e,refreshed:!1}}}function Oe(o,e){return!o||!o.HX_ORA_URL||!o.HX_API_KEY?Promise.resolve():fetch(`${o.HX_ORA_URL}/internal/sessions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:o.HX_API_KEY},body:JSON.stringify(e)}).catch(s=>{console.error("[sessionIndex] failed to index session",s)})}function _e(){let o={};return{add(e,s){o[e]=s},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 fo(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function $e(o,e){if(!fo(o))throw new Error("Structured outputs require HX_ORA_URL and HX_API_KEY");let s=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(!s.ok){let t=await s.text().catch(()=>"");throw new Error(`Structured output persistence failed with ${s.status}${t?`: ${t}`:""}`)}}var Pe=async(o,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),`${JSON.stringify(o)}`};async function st(o,e){var r,i;let s=o.id||o.name||"",[t,n]=String(s).split("::");if(!t||!n)return null;try{let d=(r=(await V(t,e)).metadata)==null?void 0:r.tenant,f=await z(t,e),u=(i=o.state)==null?void 0:i.user,p={flowData:{...f,tenant:d,flowId:t,chatId:n},executedNodes:[],context:u?{user:u}:{}};return o.setState({...o.state,engineState:p}),p}catch(l){return console.error("Failed to initialize engine state:",l),null}}async function nt(o){var D,b,F,P,E;let{agent:e,env:s,ctx:t,payload:n,connection:r}=o,i=Date.now(),l=[],d=o.runId?_e():void 0,f=async()=>await X(e),u=async I=>{await ie(e,I)},p=async I=>{if(e.state.modelsCache&&e.state.modelsCache[I])return e.state.modelsCache[I];try{let{fetchOraModel:_}=await import("./oraApi-YIJGMXX7.js"),$=await _(I,s);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[I]:$}}),$}catch(_){throw console.error(`Error fetching model ${I}:`,_),_}},c={id:mo(),role:"user",type:"text",content:n.text,images:n.images,ts:Date.now()};await u(c);let m={onChangeState:I=>{e.setState({...e.state,engineState:I})},onServerEvent:async I=>{var _;await((_=o.onServerEvent)==null?void 0:_.call(o,I)),l.push(I)},onTelemetry:async I=>{var _,$,L,Z,v,j;await Pe({...I,userId:o.resolveUserId(),tenant:(($=(_=e.state.engineState)==null?void 0:_.flowData)==null?void 0:$.tenant)||"",flowId:((Z=(L=e.state.engineState)==null?void 0:L.flowData)==null?void 0:Z.flowId)||"",sessionId:((j=(v=e.state.engineState)==null?void 0:v.flowData)==null?void 0:j.chatId)||""},s)},onError:I=>{var _;(_=o.onError)==null||_.call(o,I),e.setState({...e.state,error:I})},shouldStop:o.shouldStop},a=e.state.engineState?{...e.state.engineState}:null;if(a){let{engineState:I,refreshed:_}=await Ae(s,a);a=I,_&&e.setState({...e.state,engineState:a,modelsCache:{}})}else if(a=await st(e,s),!a){let I="Failed to initialize agent";return m.onError(I),{status:"failed",error:I}}let g=o.secrets;if(!g||Object.keys(g).length===0){let I=(D=a.flowData)==null?void 0:D.tenant;g=I?await ht(s,I):{},(b=o.onSecretsLoaded)==null||b.call(o,g)}let y=o.user??e.state.user??void 0;y&&!((F=a.context)!=null&&F.user)&&(a.context={...a.context||{},user:y});let w=lt(ot(a)),h=typeof a.cycle=="number"?a.cycle:0;w.enabled&&(h=await ye(e,a),a.cycle=h,e.setState({...e.state,engineState:a}));let x=he(e,{env:s,ctx:t,conn:r,getMessages:f,setMessages:u,getOraModel:p,secrets:g,userAuth:o.userAuth,user:y,composioSessions:o.composioSessions,publicOrigin:o.publicOrigin,skillRefCache:o.skillRefCache,runId:o.runId,outputCollector:d},a,h,o.onMemoryRef),R=await Ce(x,a,m)(n);if(R.status==="completed"&&o.runId&&(d!=null&&d.hasOutputs())){let{flowId:I,chatId:_}=a.flowData??{};if(!I||!_)R={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await $e(s,{flowId:I,sessionId:_,runId:o.runId,createdAt:new Date(i).toISOString(),data:d.snapshotData(),answerNodeIds:d.answerNodeIds()});let $={...a.results||{}};for(let L of d.answerNodeIds())$[L]={...$[L]||{},persisted:!0,runId:o.runId};a={...a,results:$},e.setState({...e.state,engineState:a})}catch($){let L=$ instanceof Error?$.message:"Structured output persistence failed";m.onError(L),await m.onServerEvent({type:"error:answer-output",content:{runId:o.runId,error:L},timestamp:Date.now()}),R={status:"failed",error:L}}}let{tenant:T,flowId:M,chatId:A}=a.flowData??{};return T&&M&&A&&t.waitUntil(Oe(s,{id:`${M}::${A}`,tenant:T,flowId:M,sessionId:A,userId:o.resolveUserId(),title:(P=n.text)==null?void 0:P.slice(0,120),turnTs:i,events:l})),R.status==="completed"&&((E=x.memoryConfig)!=null&&E.enabled)&&x.memoryConfig.mode==="summarize"&&t&&t.waitUntil(Yt(e,x,h)),e.setState({...e.state,lastUpdated:new Date}),{status:R.status,error:R.error,engineState:a}}import{nanoid as go}from"nanoid";function yo(o){let e=o.headers.get("X-User-Payload");if(!e)return null;try{let s=JSON.parse(e),t=typeof(s==null?void 0:s.email)=="string"?tt(s.email):null;return t?{...s,email:t}:null}catch{return null}}async function Me(o,e,s,t){var n;try{let r=await e.json(),i=r.message;if(!i||typeof i!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let l=typeof r.userId=="string"?tt(r.userId):null,d=yo(e),f=d==null?void 0:d.email;d?o.setState({...o.state,user:d,injectedUserId:f}):l&&!((n=o.state.user)!=null&&n.email)&&o.setState({...o.state,injectedUserId:l});let u=()=>f??l??o.state.injectedUserId??void 0;o.skillRefCache||(o.skillRefCache=new Map);let p=r.inputs&&typeof r.inputs=="object"?r.inputs:void 0;if(!o.state.engineState&&!await st(o,s))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let c=f?`run-${go(12)}`:null;c&&(await o.registerManualRun(c,i,f),await et(s,c).catch(y=>{console.warn(`[AgentHTTP] could not mark manual run ${c} as running`,y)}));let m;try{m=await nt({agent:o,env:s,ctx:t,payload:{text:i,inputs:p},skillRefCache:o.skillRefCache,user:d??void 0,resolveUserId:u,runId:c??void 0,shouldStop:c?()=>o.isRunStopRequested(c):void 0}),c&&t.waitUntil(o.completeManualRun(c,m.status==="completed"?"succeeded":m.status==="stopped"?"skipped":"failed",m.error))}finally{c&&await o.clearRunStopRequest(c)}if(m.status==="failed")return new Response(JSON.stringify({error:m.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});if(m.status==="stopped")return new Response(JSON.stringify({error:m.error||"Stopped by user"}),{status:409,headers:{"content-type":"application/json"}});let g=(await X(o)).reverse().find(y=>y.role==="assistant");return new Response(JSON.stringify({answer:(g==null?void 0:g.content)||""}),{headers:{"content-type":"application/json"}})}catch(r){return new Response(JSON.stringify({error:r.message}),{status:500,headers:{"content-type":"application/json"}})}}async function Fe(o){try{return await ut(o),await mt(o),o.skillRefCache&&o.skillRefCache.clear(),o.setState({...o.state,error:"",engineState:void 0,modelsCache:{},lastUpdated:new Date}),new Response(JSON.stringify({success:!0,messages:[]}),{headers:{"content-type":"application/json"}})}catch(e){return new Response(JSON.stringify({error:e.message}),{status:500,headers:{"content-type":"application/json"}})}}var De="trigger:nonce:",Ro=900*1e3,Ut="run:stop:",Ue=class extends ho{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{}};resolveSessionUserId(){var e;return((e=this.state.user)==null?void 0:e.email)??this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async inspectPersistedSession(e){return e==="state"?{state:this.state}:e==="messages"?{messages:await X(this)}:{context:await ce(this)}}async requestRunStop(e){return e!=null&&e.trim()?(await this.ctx.storage.put(`${Ut}${e}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(e){return!!await this.ctx.storage.get(`${Ut}${e}`)}async clearRunStopRequest(e){await this.ctx.storage.delete(`${Ut}${e}`)}async onRequest(e){let s=new URL(e.url);if(s.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(s.pathname.endsWith("/history")){let t=await X(this);return new Response(JSON.stringify(t),{headers:{"content-type":"application/json"}})}if(s.pathname.endsWith("/context")){let t={"content-type":"application/json","access-control-allow-origin":"*"};if(!e.headers.get("X-User-Payload"))return new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:t});let n=s.searchParams.get("ref");if(n){let i=await ft(this,n);return i?new Response(JSON.stringify({entry:i}),{headers:t}):new Response(JSON.stringify({error:"Not found"}),{status:404,headers:t})}let r=await pt(this);return new Response(JSON.stringify({entries:r}),{headers:t})}return e.method==="POST"&&s.pathname.endsWith("/message")?Me(this,e,this.env,this.ctx):e.method==="DELETE"&&s.pathname.endsWith("/clear")?Fe(this):new Response("Ready to assist.")}async onConnect(e,s){var c,m,a,g,y;let[t,n]=e.server.split("::"),i=(c=(await V(t,this.env)).metadata)==null?void 0:c.tenant;this.secrets=await ht(this.env,i),this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let l=null;if(s.request){try{this.publicOrigin=new URL(s.request.url).origin}catch{}let w=s.request.headers.get("X-User-Payload");if(w)try{l=JSON.parse(w)}catch(h){console.warn("Failed to parse X-User-Payload",h)}}let d=await z(t,this.env);this.setState({...this.state,user:l||null,sessionId:n,engineState:{flowData:{...d,tenant:i,flowId:t,chatId:n},executedNodes:[],context:l?{user:l}:{}}}),l||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let f=await X(this);k(e,U.SERVER_HISTORY,JSON.stringify({messages:f}));let p=(((m=d==null?void 0:d.state)==null?void 0:m.nodes)??(d==null?void 0:d.nodes)??[]).find(w=>w.type==="startNode");if(p){let w={allow_images:((a=p.data)==null?void 0:a.allow_images)??!1,allow_documents:((g=p.data)==null?void 0:g.allow_documents)??!1,greeting:(y=p.data)==null?void 0:y.greeting};k(e,U.SERVER_CONFIG,JSON.stringify(w))}}async onMessage(e,s){if(typeof s!="string")return;let t=s.indexOf(":");if(t===-1)return;let n=s.substring(0,t),r=s.substring(t+1);if(!n||!r)return;let l={[U.USER_MESSAGE]:d=>this.onUserMessage(e,d),[U.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[U.USER_AUTH]:d=>this.onUserAuth(e,d),[U.USER_IDENTITY]:d=>this.onUserIdentity(e,d)}[n];l&&await l(r)}async onUserMessage(e,s){let t=at(s),n=this.hasAuditableUser()?`run-${wo(12)}`:null;n&&(await this.registerManualRun(n,t.text),await et(this.env,n).catch(r=>{console.warn(`[AgentDO] could not mark manual run ${n} as running`,r)}));try{let r=await nt({agent:this,env:this.env,ctx:this.ctx,payload:t,connection:e,secrets:this.secrets,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:this.state.user,resolveUserId:()=>this.resolveSessionUserId(),runId:n??void 0,shouldStop:n?()=>this.isRunStopRequested(n):void 0,onServerEvent:i=>{k(e,U.SERVER_EVENT,JSON.stringify(i))},onError:i=>{k(e,U.SERVER_ERROR,i)},onMemoryRef:i=>{k(e,U.SERVER_EVENT,JSON.stringify({type:"info:memory:updated",content:{ref:i}}))},onSecretsLoaded:i=>{this.secrets=i}});n&&this.ctx.waitUntil(this.completeManualRun(n,r.status==="completed"?"succeeded":r.status==="stopped"?"skipped":"failed",r.error))}finally{n&&await this.clearRunStopRequest(n)}}hasAuditableUser(e){var s;return!!(e||(s=this.state.user)!=null&&s.email)}registerManualRun(e,s,t){var d,f;let{tenant:n,flowId:r,chatId:i}=((d=this.state.engineState)==null?void 0:d.flowData)??{},l=t||((f=this.state.user)==null?void 0:f.email);return!n||!r||!i||!l?Promise.resolve():me(this.env,{id:e,tenant:n,flowId:r,userId:l,sessionId:i,label:s==null?void 0:s.slice(0,120)})}completeManualRun(e,s,t){return yt(this.env,e,{status:s,error:t})}async enqueueTrigger(e){var n;if(!(e!=null&&e.runId)||!(e!=null&&e.flowId))return{queued:!1};if(e.nonce&&!await this.claimTriggerNonce(e.nonce))return console.warn(`[AgentDO] rejected replayed trigger nonce ${e.nonce}`),{queued:!1,duplicate:!0};let s=e.runAsUserId;return s&&!((n=this.state.user)!=null&&n.email)&&this.state.injectedUserId!==s&&this.setState({...this.state,injectedUserId:s}),{queued:!0,taskId:await this.queue("processTrigger",e)}}async claimTriggerNonce(e){let s=`${De}${e}`;if(await this.ctx.storage.get(s))return!1;let t=Date.now();await this.ctx.storage.put(s,t);let r=[...(await this.ctx.storage.list({prefix:De})).entries()].filter(([,i])=>t-i>Ro).map(([i])=>i);return r.length>0&&await this.ctx.storage.delete(r),!0}async processTrigger(e){if(!(await et(this.env,e.runId)).claimed){console.warn(`[AgentDO] activation ${e.activationId} skipped \u2014 run ${e.runId} already claimed`);return}try{this.state.engineState||await st(this,this.env);let t=Y(ot(this.state.engineState)),n=Et(t,e.inputs||{},e.label),r=await nt({agent:this,env:this.env,ctx:this.ctx,payload:{text:n,inputs:e.inputs||{}},secrets:this.secrets,composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>e.runAsUserId||this.resolveSessionUserId(),runId:e.runId,shouldStop:()=>this.isRunStopRequested(e.runId),onSecretsLoaded:i=>{this.secrets=i}});await yt(this.env,e.runId,{status:r.status==="completed"?"succeeded":r.status==="stopped"?"skipped":"failed",error:r.error})}catch(t){let n=t instanceof Error?t.message:"Trigger execution failed";throw await yt(this.env,e.runId,{status:"failed",error:n}),t}finally{await this.clearRunStopRequest(e.runId)}}async onUserIdentity(e,s){let t=tt(s);if(!t){k(e,U.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:t}),k(e,U.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,s){let t=Ht(s);if(!t){k(e,U.SERVER_ERROR,"Invalid auth payload");return}let n=t.value.trim();n===""?delete this.userAuth[t.name]:this.userAuth[t.name]=t.value,k(e,U.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:t.name,set:n!==""}}))}async onClearHistory(e){await ut(this),await mt(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear();let s=this.state.engineState?{...this.state.engineState,cycle:void 0}:void 0;this.setState({...this.state,error:"",engineState:s,modelsCache:{},lastUpdated:new Date}),e&&k(e,U.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await fe(this);let e=await X(this);`${JSON.stringify(e)}`}async onClose(e,s,t,n){console.log(`Session closed: ${this.state.sessionId} ${s} - ${t}`)}async onError(e){console.error("AgentDO encountered an error:",e)}};function mr(o){let e=o.state;if(!e)return null;let s=["startNode","answerNode"];for(let t of s)if(!e.nodes.some(r=>r.type===t))return!1;return e.nodes.find(t=>t.type==="startNode")}import{importSPKI as xo,jwtVerify as Io}from"jose";function ke(o){let e={};if(!o)return e;let s=o.split(";");for(let t of s){let n=t.indexOf("=");if(n>-1){let r=t.slice(0,n).trim(),i=t.slice(n+1).trim();r&&(e[r]=decodeURIComponent(i))}}return e}function To(o){return(typeof o.email=="string"?o.email.trim():"")||null}async function J(o,e,s){let t=ke(o.headers.get("cookie")),n=new URL(o.url),r=t.access_token||n.searchParams.get("access_token"),i=await No(e,r);if(i.ok){let l=i.payload,d=To(l);return d?{id:l.sub,email:d,name:l.name,first_name:l.given_name,last_name:l.family_name,tenant:l.tenant,roles:l["ora-roles"],db_name:l.db_name||null,user_id:l.user_id||null}:null}return null}async function No(o,e){if(!e||typeof e!="string")return{ok:!1,payload:null,protectedHeader:null};if(!o.KC_RS256_PK)throw new Error("PK is not defined");let s=`-----BEGIN PUBLIC KEY-----
|
|
40
40
|
${o.KC_RS256_PK}
|
|
41
|
-
-----END PUBLIC KEY-----`,t=await
|
|
42
|
-
`)}async function qe(o,e){let s=await crypto.subtle.importKey("raw",ke.encode(o),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return xo(await crypto.subtle.sign("HMAC",s,ke.encode(e)))}function To(o,e){if(o.length!==e.length)return!1;let s=0;for(let t=0;t<o.length;t++)s|=o.charCodeAt(t)^e.charCodeAt(t);return s===0}async function wr(o){let e=String(o.timestamp??Math.floor(Date.now()/1e3)),s=await qe(o.secret,He({timestamp:e,nonce:o.nonce,tenant:o.tenant,destination:o.destination,body:o.body}));return{"content-type":"application/json",[Ee]:o.tenant,[Le]:e,[je]:o.nonce,[be]:`v1=${s}`}}async function Ke(o){var f,p,m,a,d;if(!((f=o.secret)!=null&&f.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(p=o.headers.get(Ee))==null?void 0:p.trim(),s=(m=o.headers.get(Le))==null?void 0:m.trim(),t=(a=o.headers.get(je))==null?void 0:a.trim(),n=(d=o.headers.get(be))==null?void 0:d.trim();if(!e||!s||!t||!n)return{ok:!1,error:"missing signature headers"};if(!n.startsWith("v1="))return{ok:!1,error:"unsupported signature version"};let r=Number(s);if(!Number.isFinite(r))return{ok:!1,error:"invalid timestamp"};let i=Math.floor((o.now??Date.now())/1e3),l=o.toleranceSeconds??300;if(Math.abs(i-r)>l)return{ok:!1,error:"stale timestamp"};let u=await qe(o.secret.trim(),He({timestamp:s,nonce:t,tenant:e,destination:o.url,body:o.body}));return To(n.slice(3),u)?{ok:!0,tenant:e,nonce:t,timestamp:r}:{ok:!1,error:"signature mismatch"}}var K=(o,e=200)=>new Response(JSON.stringify(o),{status:e,headers:{"content-type":"application/json"}});async function Ve(o,e,s){var f;if(new URL(o.url).pathname!=="/api/triggers/dispatch")return;if(o.method!=="POST")return K({error:"Method not allowed"},405);let n=await o.text(),r=await Ke({secret:e.HX_API_KEY,body:n,url:o.url,headers:o.headers});if(!r.ok)return console.warn(`[triggers] rejected dispatch: ${r.error}`),K({error:"Invalid signature"},401);let i;try{i=JSON.parse(n)}catch{return K({error:"Invalid payload"},400)}if(!(i!=null&&i.runId)||!(i!=null&&i.flowId)||!(i!=null&&i.runAsUserId)||!(i!=null&&i.tenant)||!(i!=null&&i.activationId)||!(i!=null&&i.triggerId)||!(i!=null&&i.triggerKind)||!(i!=null&&i.invocationMode))return K({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(i.tenant!==r.tenant)return K({error:"Tenant mismatch"},403);let l;try{l=await X(i.flowId,e)}catch{return K({error:"Flow not found"},404)}if(!((f=l==null?void 0:l.metadata)!=null&&f.tenant)||l.metadata.tenant!==i.tenant)return console.warn(`[triggers] flow ${i.flowId} does not belong to tenant ${i.tenant}`),K({error:"Tenant mismatch"},403);let u=await Ue(e,{...i,sessionId:i.sessionId||i.runAsUserId,nonce:r.nonce});return u.status==="error"?K({error:u.error},502):u.status==="deduped"?K({deduped:!0,runId:u.runId},200):K({accepted:!0,runId:u.runId,taskId:u.taskId},202)}var No=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,Co=new Set(["state","messages","context"]);async function Ao(o,e){let s=new URL(o.url);if(!s.pathname.startsWith("/api/internal/sessions/"))return;let t=s.pathname.split("/");if(t[6]!=="runs"||t[8]!=="stop"||t.length!==9)return;if(o.method!=="POST")return new Response("Method not allowed",{status:405});if(!e.HX_API_KEY||o.headers.get("Authorization")!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let n=decodeURIComponent(t[4]||""),r=decodeURIComponent(t[5]||""),i=decodeURIComponent(t[7]||"");if(!n||!r||!i)return new Response("Not found",{status:404});try{let l=await Rt(e.AGENT,`${n}::${r}`);return Response.json(await l.requestRunStop(i))}catch(l){return console.error("[agents] failed to request run stop",l),Response.json({error:"Failed to stop run"},{status:502})}}async function _o(o,e){let s=new URL(o.url);if(!s.pathname.startsWith("/api/internal/sessions/"))return;if(o.method!=="GET")return new Response("Method not allowed",{status:405});let t=o.headers.get("Authorization")||"";if(!e.HX_API_KEY||t!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let n=s.pathname.split("/"),r=decodeURIComponent(n[4]||""),i=decodeURIComponent(n[5]||""),l=n[6];if(!r||!i||!l||!Co.has(l))return new Response("Not found",{status:404});try{let f=await(await Rt(e.AGENT,`${r}::${i}`)).inspectPersistedSession(l);return Response.json(f)}catch(u){return console.error("[agents] failed to inspect persisted session",u),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function $r(o,e,s){var l,u,f,p;let t=new URL(o.url),n=await Ve(o,e,s);if(n instanceof Response)return n;let r=await Ao(o,e);if(r instanceof Response)return r;let i=await _o(o,e);if(i instanceof Response)return i;if(t.pathname.startsWith("/a/")){let m=t.pathname.split("/"),a=m[2],d=m[3];try{if(!a)return Response.redirect(new URL("/",t.origin).toString(),302);let c;try{c=await X(a,e)}catch{return new Response("Flow not found",{status:404})}if(!c.metadata||((l=c.metadata)==null?void 0:l.status)!=="active")return new Response("NO chat",{status:404});if(((u=c.metadata)==null?void 0:u.visibility)==="private"&&!await J(o,e,s)){let y=new URL("/login",t.origin);return y.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(y.toString(),302)}if(!d){let g=crypto.randomUUID(),y=new URL(`/a/${a}/${g}`,t.origin);return Response.redirect(y.toString(),302)}if(!No.test(d))return new Response("Id del chat no v\xE1lido",{status:400})}catch(c){return console.error("Error accessing flow KV:",c),new Response("Flow error",{status:500})}}if(t.pathname.startsWith("/api/agent/flow")){let m=t.pathname.split("/"),a=m[4],d=m[5],c=`${a}::${d}`;try{let g=await J(o,e,s);if(!g){let R=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${R}) \u2014 Composio connections from tool editor will not apply`)}let y=new Headers(o.headers);y.delete("X-User-Payload"),g&&y.set("X-User-Payload",JSON.stringify(g));let w=new Request(o,{headers:y});return(await Rt(e.AGENT,c)).fetch(w)}catch(g){return console.error("Error accessing agent:",g),new Response("Agent error",{status:500})}}if(t.pathname.startsWith("/api/ora/connect")){let m=t.pathname.split("/"),a=m[4],d=m[5];if(!a||!d)return new Response("Missing flowId or sessionId",{status:400});let c=o.headers.get("Authorization")||t.searchParams.get("authorization");if(!c)return new Response("Missing Authorization header",{status:401});try{let g=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${a}`,w=await(await fetch(g,{method:"GET",headers:{Authorization:c}})).json();if(((f=w.payload)==null?void 0:f.flowId)!==a)return console.error("FlowId mismatch:",(p=w.payload)==null?void 0:p.flowId,"!==",a),new Response("Validation error",{status:403});let h=`${a}::${d}`,x=await J(o,e,s);if(!x){let M=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${M}) \u2014 Composio connections from tool editor will not apply`)}let R=new Headers(o.headers);R.delete("X-User-Payload"),x&&R.set("X-User-Payload",JSON.stringify(x));let I=new Request(o,{headers:R});return(await Rt(e.AGENT,h)).fetch(I)}catch(g){return console.error("Error in /api/ora/connect:",g),new Response("Internal error",{status:500})}}}async function Mr(o,e,s){let t=new URL(o.url),n=o.method;if(!t.pathname.startsWith("/api/instances"))return;let r=await J(o,e,s);if(!r)return new Response("Unauthorized",{status:401});let i=e.HX_CORE_URL,l=e.HX_API_KEY;if(!i||!l)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let f=t.pathname.slice("/api/instances".length);f.startsWith("/")&&(f=f.slice(1)),f.endsWith("/")&&(f=f.slice(0,-1));let p="/ora/instances";f&&(p+=`/${f}`);let m=i.endsWith("/")?i.slice(0,-1):i,a=new URL(`${m}${p}`);t.searchParams.forEach((g,y)=>{a.searchParams.set(y,g)}),n==="GET"&&!f&&a.searchParams.set("filter_user_id",r.email);let d=new Headers;d.set("Authorization",l),d.set("Content-Type","application/json"),d.set("X-User-Payload",JSON.stringify(r));let c={method:n,headers:d};if(["POST","PATCH","PUT"].includes(n))try{c.body=await o.text()}catch(g){console.error("Error reading request body:",g)}try{let g=await fetch(a.toString(),c),y=await g.text();return new Response(y,{status:g.status,headers:{"Content-Type":"application/json"}})}catch(g){return console.error("Error proxying to flow instance backend:",g),new Response("Internal Server Error",{status:500})}}async function kr(o,e,s){let t=new URL(o.url);if(o.method==="POST"&&t.pathname==="/auth/login")try{let n=await o.formData(),r=n.get("username"),i=n.get("password"),l=n.get("nextURL")||"/";if(!r||!i)return new Response("Missing username or password",{status:400});let u=new URLSearchParams;u.append("username",r),u.append("password",i),u.append("grant_type","password"),u.append("client_id",e.KC_CLIENT_ID),u.append("client_secret",e.KC_CLIENT_SECRET);let f=await fetch(`${e.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:u});if(!f.ok)return new Response("Unauthorized",{status:401});let p=await f.json(),m=new Response(null,{status:302,headers:{Location:l}}),a=(d,c,g)=>{m.headers.append("Set-Cookie",`${d}=${c}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${g}`)};return p.access_token&&a("access_token",p.access_token,p.expires_in),p.refresh_token&&a("refresh_token",p.refresh_token,p.refresh_expires_in||3600*24*30),p.id_token&&a("id_token",p.id_token,p.expires_in),m}catch(n){return console.error("Auth error:",n),new Response("Internal Server Error",{status:500})}if(t.pathname==="/auth/logout"){let n=new Response(null,{status:302,headers:{Location:"/login"}}),r=i=>{n.headers.append("Set-Cookie",`${i}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return r("access_token"),r("refresh_token"),r("id_token"),n}if(t.pathname.startsWith("/s/")){let n=await J(o,e,s);if(!n){let r=new URL("/login",t.origin);return r.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(r.toString(),302)}return{user:n}}}export{Me as AgentDO,ko as FLOW_INPUT_NAME_RE,wt as FlowExecutionStoppedError,Lo as GENERATION_PARAM_KEYS,Eo as GENERATION_PRESETS,bo as MAX_USER_IDENTITY_LENGTH,es as MODEL_REGISTRY_SNAPSHOT,S as NodeType,jo as PRESET_PARAM_KEYS,So as REASONING_EFFORT_LEVELS,vt as TOOL_REGISTRY_SNAPSHOT,je as TRIGGER_NONCE_HEADER,be as TRIGGER_SIGNATURE_HEADER,hr as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,Ee as TRIGGER_TENANT_HEADER,Le as TRIGGER_TIMESTAMP_HEADER,Ko as applyPresetToOverrides,Jt as buildReasoningProviderOptions,wr as buildSignedTriggerHeaders,Et as buildTriggerMessageText,Fo as buildUrl,ho as canonicalUserEmail,v as claimRun,mt as clearAllContext,ut as clearAllMessages,yt as completeRun,Oo as convertTempMessure,Nt as createRun,ue as deleteContextToolsUpToCycle,Ho as deriveParamSupport,Ue as dispatchTrigger,Lt as embedText,fe as ensureAgentTables,ze as ensureContextTable,Ge as ensureMessagesTable,ce as getAllContext,V as getAllMessages,ft as getContext,le as getContextData,pt as getContextIndex,ts as getDefaultOutVars,ct as getEffectiveOutVars,Y as getFlowInputDefs,pe as getMaxContextCycle,os as getModelEntry,$r as handleAgentsRoutes,kr as handleAuthRoutes,pr as handleCommonRoutes,Mr as handleIntancesRoutes,_o as handlePersistedSessionInspection,Ao as handleSessionRunControl,Ve as handleTriggerRoutes,Do as hashText,et as initializeEngineState,ee as jsonSchemaToZod,nt as logc,D as messageTypes,Io as normalizeDestination,Vo as normalizeEffectiveParams,jt as normalizeFlowInputs,Qo as normalizeModelEntry,Yo as normalizeReasoning,Jo as openAiReasoningParamSupport,Xo as openAiStandardParamSupport,De as parseCookies,Ht as parseUserAuth,rt as parseUserMessage,qt as pickNodeOverrides,Bo as reasoningEffortLevels,Vt as reasoningExposable,me as recordRun,Zo as registerProvider,de as resolveContextRef,it as resolveModelById,lt as resolveOutVarRef,qo as resolvePreset,Xt as resolveReasoningEffort,Qt as resolveTemplate,ot as runAgentTurn,Po as safeParseJSON,Z as sanitizeUserIdentity,Oe as sendEvent,b as serverSend,ae as setContext,ie as setMessage,qe as signTriggerMaterial,Ce as startEngine,Wo as stripUnsupportedFromNodeData,$o as tempTool,To as timingSafeEqualHex,Kt as toStreamTextSettings,He as triggerSignatureMaterial,Mo as twitter,ir as validateFlowStart,Uo as vectorize,wo as verifyToken,Ke as verifyTriggerRequest,J as verifyUser,vo as walkPath,zo as workersAiParamSupport,Go as xaiParamSupport};
|
|
41
|
+
-----END PUBLIC KEY-----`,t=await xo(s,"RS256");try{let{payload:n,protectedHeader:r}=await Io(e,t);return{ok:!0,payload:n,protectedHeader:r}}catch(n){return console.error("JWT verification failed:",n),{ok:!1,payload:null,protectedHeader:null}}}async function xr(o,e,s){let t=new URL(o.url);if(t.pathname==="/favicon.ico")return new Response(null,{status:204});if(t.pathname.startsWith("/.well-known/appspecific"))return new Response(null,{status:204})}import{getAgentByName as Rt}from"agents";import{getAgentByName as Co}from"agents";async function be(o,e){let s=e.sessionId||e.runAsUserId,t=e.inputs||{},n=e.runId;if(!n){let d=await Nt(o,{tenant:e.tenant,flowId:e.flowId,userId:e.runAsUserId,sessionId:s,triggerId:e.triggerId,triggerKind:e.triggerKind,invocationMode:e.invocationMode,activationId:e.activationId,deliveryId:void 0,externalDeliveryId:e.externalDeliveryId,correlationKey:e.correlationKey,inputs:t,label:e.label});if(!d)return{status:"error",error:"Failed to register run"};if(!d.created&&d.run.status!=="queued")return{status:"deduped",runId:d.run.id};n=d.run.id}let r={...e,sessionId:s,runId:n,inputs:t},l=await(await Co(o.AGENT,`${e.flowId}::${s}`)).enqueueTrigger(r);return l.duplicate?{status:"deduped",runId:n}:l.queued?{status:"queued",runId:n,activation:r,taskId:l.taskId}:{status:"error",error:"Failed to queue trigger"}}var je="x-ora-signature",Ee="x-ora-timestamp",He="x-ora-nonce",qe="x-ora-tenant",Ar=300,Le=new TextEncoder;function Ao(o){return[...new Uint8Array(o)].map(e=>e.toString(16).padStart(2,"0")).join("")}function Oo(o){try{let e=new URL(o);return`${e.origin}${e.pathname.replace(/\/$/,"")}`}catch{return o.replace(/\/$/,"")}}function Ke(o){return["v1",o.timestamp,o.nonce,o.tenant,Oo(o.destination),o.body].join(`
|
|
42
|
+
`)}async function Xe(o,e){let s=await crypto.subtle.importKey("raw",Le.encode(o),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return Ao(await crypto.subtle.sign("HMAC",s,Le.encode(e)))}function _o(o,e){if(o.length!==e.length)return!1;let s=0;for(let t=0;t<o.length;t++)s|=o.charCodeAt(t)^e.charCodeAt(t);return s===0}async function Or(o){let e=String(o.timestamp??Math.floor(Date.now()/1e3)),s=await Xe(o.secret,Ke({timestamp:e,nonce:o.nonce,tenant:o.tenant,destination:o.destination,body:o.body}));return{"content-type":"application/json",[qe]:o.tenant,[Ee]:e,[He]:o.nonce,[je]:`v1=${s}`}}async function Ve(o){var f,u,p,c,m;if(!((f=o.secret)!=null&&f.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(u=o.headers.get(qe))==null?void 0:u.trim(),s=(p=o.headers.get(Ee))==null?void 0:p.trim(),t=(c=o.headers.get(He))==null?void 0:c.trim(),n=(m=o.headers.get(je))==null?void 0:m.trim();if(!e||!s||!t||!n)return{ok:!1,error:"missing signature headers"};if(!n.startsWith("v1="))return{ok:!1,error:"unsupported signature version"};let r=Number(s);if(!Number.isFinite(r))return{ok:!1,error:"invalid timestamp"};let i=Math.floor((o.now??Date.now())/1e3),l=o.toleranceSeconds??300;if(Math.abs(i-r)>l)return{ok:!1,error:"stale timestamp"};let d=await Xe(o.secret.trim(),Ke({timestamp:s,nonce:t,tenant:e,destination:o.url,body:o.body}));return _o(n.slice(3),d)?{ok:!0,tenant:e,nonce:t,timestamp:r}:{ok:!1,error:"signature mismatch"}}var K=(o,e=200)=>new Response(JSON.stringify(o),{status:e,headers:{"content-type":"application/json"}});async function Je(o,e,s){var f;if(new URL(o.url).pathname!=="/api/triggers/dispatch")return;if(o.method!=="POST")return K({error:"Method not allowed"},405);let n=await o.text(),r=await Ve({secret:e.HX_API_KEY,body:n,url:o.url,headers:o.headers});if(!r.ok)return console.warn(`[triggers] rejected dispatch: ${r.error}`),K({error:"Invalid signature"},401);let i;try{i=JSON.parse(n)}catch{return K({error:"Invalid payload"},400)}if(!(i!=null&&i.runId)||!(i!=null&&i.flowId)||!(i!=null&&i.runAsUserId)||!(i!=null&&i.tenant)||!(i!=null&&i.activationId)||!(i!=null&&i.triggerId)||!(i!=null&&i.triggerKind)||!(i!=null&&i.invocationMode))return K({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(i.tenant!==r.tenant)return K({error:"Tenant mismatch"},403);let l;try{l=await V(i.flowId,e)}catch{return K({error:"Flow not found"},404)}if(!((f=l==null?void 0:l.metadata)!=null&&f.tenant)||l.metadata.tenant!==i.tenant)return console.warn(`[triggers] flow ${i.flowId} does not belong to tenant ${i.tenant}`),K({error:"Tenant mismatch"},403);let d=await be(e,{...i,sessionId:i.sessionId||i.runAsUserId,nonce:r.nonce});return d.status==="error"?K({error:d.error},502):d.status==="deduped"?K({deduped:!0,runId:d.runId},200):K({accepted:!0,runId:d.runId,taskId:d.taskId},202)}var $o=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,Po=new Set(["state","messages","context"]);async function Mo(o,e){let s=new URL(o.url);if(!s.pathname.startsWith("/api/internal/sessions/"))return;let t=s.pathname.split("/");if(t[6]!=="runs"||t[8]!=="stop"||t.length!==9)return;if(o.method!=="POST")return new Response("Method not allowed",{status:405});if(!e.HX_API_KEY||o.headers.get("Authorization")!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let n=decodeURIComponent(t[4]||""),r=decodeURIComponent(t[5]||""),i=decodeURIComponent(t[7]||"");if(!n||!r||!i)return new Response("Not found",{status:404});try{let l=await Rt(e.AGENT,`${n}::${r}`);return Response.json(await l.requestRunStop(i))}catch(l){return console.error("[agents] failed to request run stop",l),Response.json({error:"Failed to stop run"},{status:502})}}async function Fo(o,e){let s=new URL(o.url);if(!s.pathname.startsWith("/api/internal/sessions/"))return;if(o.method!=="GET")return new Response("Method not allowed",{status:405});let t=o.headers.get("Authorization")||"";if(!e.HX_API_KEY||t!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let n=s.pathname.split("/"),r=decodeURIComponent(n[4]||""),i=decodeURIComponent(n[5]||""),l=n[6];if(!r||!i||!l||!Po.has(l))return new Response("Not found",{status:404});try{let f=await(await Rt(e.AGENT,`${r}::${i}`)).inspectPersistedSession(l);return Response.json(f)}catch(d){return console.error("[agents] failed to inspect persisted session",d),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function Lr(o,e,s){var l,d,f,u;let t=new URL(o.url),n=await Je(o,e,s);if(n instanceof Response)return n;let r=await Mo(o,e);if(r instanceof Response)return r;let i=await Fo(o,e);if(i instanceof Response)return i;if(t.pathname.startsWith("/a/")){let p=t.pathname.split("/"),c=p[2],m=p[3];try{if(!c)return Response.redirect(new URL("/",t.origin).toString(),302);let a;try{a=await V(c,e)}catch{return new Response("Flow not found",{status:404})}if(!a.metadata||((l=a.metadata)==null?void 0:l.status)!=="active")return new Response("NO chat",{status:404});if(((d=a.metadata)==null?void 0:d.visibility)==="private"&&!await J(o,e,s)){let y=new URL("/login",t.origin);return y.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(y.toString(),302)}if(!m){let g=crypto.randomUUID(),y=new URL(`/a/${c}/${g}`,t.origin);return Response.redirect(y.toString(),302)}if(!$o.test(m))return new Response("Id del chat no v\xE1lido",{status:400})}catch(a){return console.error("Error accessing flow KV:",a),new Response("Flow error",{status:500})}}if(t.pathname.startsWith("/api/agent/flow")){let p=t.pathname.split("/"),c=p[4],m=p[5],a=`${c}::${m}`;try{let g=await J(o,e,s);if(!g){let R=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${R}) \u2014 Composio connections from tool editor will not apply`)}let y=new Headers(o.headers);y.delete("X-User-Payload"),g&&y.set("X-User-Payload",JSON.stringify(g));let w=new Request(o,{headers:y});return(await Rt(e.AGENT,a)).fetch(w)}catch(g){return console.error("Error accessing agent:",g),new Response("Agent error",{status:500})}}if(t.pathname.startsWith("/api/ora/connect")){let p=t.pathname.split("/"),c=p[4],m=p[5];if(!c||!m)return new Response("Missing flowId or sessionId",{status:400});let a=o.headers.get("Authorization")||t.searchParams.get("authorization");if(!a)return new Response("Missing Authorization header",{status:401});try{let g=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${c}`,w=await(await fetch(g,{method:"GET",headers:{Authorization:a}})).json();if(((f=w.payload)==null?void 0:f.flowId)!==c)return console.error("FlowId mismatch:",(u=w.payload)==null?void 0:u.flowId,"!==",c),new Response("Validation error",{status:403});let h=`${c}::${m}`,x=await J(o,e,s);if(!x){let D=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${D}) \u2014 Composio connections from tool editor will not apply`)}let R=new Headers(o.headers);R.delete("X-User-Payload"),x&&R.set("X-User-Payload",JSON.stringify(x));let T=new Request(o,{headers:R});return(await Rt(e.AGENT,h)).fetch(T)}catch(g){return console.error("Error in /api/ora/connect:",g),new Response("Internal error",{status:500})}}}async function Hr(o,e,s){let t=new URL(o.url),n=o.method;if(!t.pathname.startsWith("/api/instances"))return;let r=await J(o,e,s);if(!r)return new Response("Unauthorized",{status:401});let i=e.HX_CORE_URL,l=e.HX_API_KEY;if(!i||!l)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let f=t.pathname.slice("/api/instances".length);f.startsWith("/")&&(f=f.slice(1)),f.endsWith("/")&&(f=f.slice(0,-1));let u="/ora/instances";f&&(u+=`/${f}`);let p=i.endsWith("/")?i.slice(0,-1):i,c=new URL(`${p}${u}`);t.searchParams.forEach((g,y)=>{c.searchParams.set(y,g)}),n==="GET"&&!f&&c.searchParams.set("filter_user_id",r.email);let m=new Headers;m.set("Authorization",l),m.set("Content-Type","application/json"),m.set("X-User-Payload",JSON.stringify(r));let a={method:n,headers:m};if(["POST","PATCH","PUT"].includes(n))try{a.body=await o.text()}catch(g){console.error("Error reading request body:",g)}try{let g=await fetch(c.toString(),a),y=await g.text();return new Response(y,{status:g.status,headers:{"Content-Type":"application/json"}})}catch(g){return console.error("Error proxying to flow instance backend:",g),new Response("Internal Server Error",{status:500})}}async function Xr(o,e,s){let t=new URL(o.url);if(o.method==="POST"&&t.pathname==="/auth/login")try{let n=await o.formData(),r=n.get("username"),i=n.get("password"),l=n.get("nextURL")||"/";if(!r||!i)return new Response("Missing username or password",{status:400});let d=new URLSearchParams;d.append("username",r),d.append("password",i),d.append("grant_type","password"),d.append("client_id",e.KC_CLIENT_ID),d.append("client_secret",e.KC_CLIENT_SECRET);let f=await fetch(`${e.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:d});if(!f.ok)return new Response("Unauthorized",{status:401});let u=await f.json(),p=new Response(null,{status:302,headers:{Location:l}}),c=(m,a,g)=>{p.headers.append("Set-Cookie",`${m}=${a}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${g}`)};return u.access_token&&c("access_token",u.access_token,u.expires_in),u.refresh_token&&c("refresh_token",u.refresh_token,u.refresh_expires_in||3600*24*30),u.id_token&&c("id_token",u.id_token,u.expires_in),p}catch(n){return console.error("Auth error:",n),new Response("Internal Server Error",{status:500})}if(t.pathname==="/auth/logout"){let n=new Response(null,{status:302,headers:{Location:"/login"}}),r=i=>{n.headers.append("Set-Cookie",`${i}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return r("access_token"),r("refresh_token"),r("id_token"),n}if(t.pathname.startsWith("/s/")){let n=await J(o,e,s);if(!n){let r=new URL("/login",t.origin);return r.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(r.toString(),302)}return{user:n}}}export{Ue as AgentDO,Ho as FLOW_INPUT_NAME_RE,wt as FlowExecutionStoppedError,Ko as GENERATION_PARAM_KEYS,Vo as GENERATION_PRESETS,qo as MAX_USER_IDENTITY_LENGTH,is as MODEL_REGISTRY_SNAPSHOT,W as NodeType,Xo as PRESET_PARAM_KEYS,vo as REASONING_EFFORT_LEVELS,vt as TOOL_REGISTRY_SNAPSHOT,He as TRIGGER_NONCE_HEADER,je as TRIGGER_SIGNATURE_HEADER,Ar as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,qe as TRIGGER_TENANT_HEADER,Ee as TRIGGER_TIMESTAMP_HEADER,Go as applyPresetToOverrides,Jt as buildReasoningProviderOptions,Or as buildSignedTriggerHeaders,Et as buildTriggerMessageText,bo as buildUrl,To as canonicalUserEmail,et as claimRun,mt as clearAllContext,ut as clearAllMessages,yt as completeRun,Do as convertTempMessure,Nt as createRun,ue as deleteContextToolsUpToCycle,Jo as deriveParamSupport,be as dispatchTrigger,Lt as embedText,fe as ensureAgentTables,We as ensureContextTable,ze as ensureMessagesTable,ce as getAllContext,X as getAllMessages,ft as getContext,le as getContextData,pt as getContextIndex,rs as getDefaultOutVars,B as getEffectiveOutVars,Y as getFlowInputDefs,pe as getMaxContextCycle,as as getModelEntry,Lr as handleAgentsRoutes,Xr as handleAuthRoutes,xr as handleCommonRoutes,Hr as handleIntancesRoutes,Fo as handlePersistedSessionInspection,Mo as handleSessionRunControl,Je as handleTriggerRoutes,jo as hashText,st as initializeEngineState,ee as jsonSchemaToZod,it as logc,U as messageTypes,Oo as normalizeDestination,zo as normalizeEffectiveParams,jt as normalizeFlowInputs,os as normalizeModelEntry,ts as normalizeReasoning,Yo as openAiReasoningParamSupport,Wo as openAiStandardParamSupport,ke as parseCookies,Ht as parseUserAuth,at as parseUserMessage,qt as pickNodeOverrides,es as reasoningEffortLevels,Xt as reasoningExposable,me as recordRun,ss as registerProvider,Ze as resolveAnswerMappings,de as resolveContextRef,ct as resolveModelById,Q as resolveOutVarRef,So as resolvePreset,Vt as resolveReasoningEffort,Qt as resolveTemplate,nt as runAgentTurn,ko as safeParseJSON,tt as sanitizeUserIdentity,Pe as sendEvent,k as serverSend,ae as setContext,ie as setMessage,Xe as signTriggerMaterial,Ce as startEngine,Zo as stripUnsupportedFromNodeData,Uo as tempTool,_o as timingSafeEqualHex,Kt as toStreamTextSettings,Ke as triggerSignatureMaterial,Lo as twitter,mr as validateFlowStart,Eo as vectorize,No as verifyToken,Ve as verifyTriggerRequest,J as verifyUser,ns as walkPath,Qo as workersAiParamSupport,Bo as xaiParamSupport};
|
|
@@ -5,6 +5,7 @@ import type { ContextIndexEntry, ContextRow, ContextUpsertInput, MemoryConfig }
|
|
|
5
5
|
import type { TriggerActivation } from '../../common/types/trigger-types';
|
|
6
6
|
import type { FlowEngineState } from '../logic/FlowEngine';
|
|
7
7
|
import type { ComposioSessionMeta } from '../utils/composio';
|
|
8
|
+
import type { RunOutputCollector } from '../utils/oraOutputs';
|
|
8
9
|
import { type SecretsMap } from '../utils/secrets';
|
|
9
10
|
export interface SessionEnv {
|
|
10
11
|
env?: Env;
|
|
@@ -35,6 +36,10 @@ export interface SessionEnv {
|
|
|
35
36
|
user?: UserInterface;
|
|
36
37
|
/** Origin derived from the WebSocket upgrade request (preferred over ORA_PUBLIC_URL for callbacks). */
|
|
37
38
|
publicOrigin?: string;
|
|
39
|
+
/** Auditable run currently executing. Anonymous turns omit it. */
|
|
40
|
+
runId?: string;
|
|
41
|
+
/** Turn-local structured output collector. Never persisted in Agent state. */
|
|
42
|
+
outputCollector?: RunOutputCollector;
|
|
38
43
|
}
|
|
39
44
|
export type { ComposioSessionMeta };
|
|
40
45
|
export interface State {
|
|
@@ -24,6 +24,8 @@ export interface AgentTurnOptions {
|
|
|
24
24
|
skillRefCache?: Map<string, string>;
|
|
25
25
|
user?: UserInterface;
|
|
26
26
|
resolveUserId: () => string | undefined;
|
|
27
|
+
/** Existing auditable run id. Anonymous turns intentionally omit it. */
|
|
28
|
+
runId?: string;
|
|
27
29
|
onServerEvent?: (event: FlowEngineEvent) => void | Promise<void>;
|
|
28
30
|
onError?: (error: string) => void;
|
|
29
31
|
onMemoryRef?: (ref: string) => void | Promise<void>;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { SessionEnv } from '../core/AgentDO';
|
|
2
2
|
import type { FlowEngineEvent, FlowEngineState } from '../logic/FlowEngine';
|
|
3
3
|
import type { TelemetryEvent } from '../utils/telemetry';
|
|
4
|
+
export declare function resolveAnswerMappings(node: any, engineState: FlowEngineState): Record<string, unknown> | null;
|
|
4
5
|
export default function answerNodeRunner(sessionEnv: SessionEnv, node: any, engineState: FlowEngineState, onServerEvent?: (event: FlowEngineEvent) => void, onResult?: (key: string, result: any) => void, onChangeState?: (state: FlowEngineState) => void, onTelemetry?: (event: TelemetryEvent) => void): Promise<void>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export type StructuredAnswerValues = Record<string, unknown>;
|
|
2
|
+
export type StructuredRunData = Record<string, unknown>;
|
|
3
|
+
export interface RunOutputCollector {
|
|
4
|
+
add(answerNodeId: string, values: StructuredAnswerValues): void;
|
|
5
|
+
hasOutputs(): boolean;
|
|
6
|
+
answerNodeIds(): string[];
|
|
7
|
+
snapshotData(): StructuredRunData;
|
|
8
|
+
}
|
|
9
|
+
export declare function createRunOutputCollector(): RunOutputCollector;
|
|
10
|
+
export declare function persistRunOutputs(env: Env | undefined, input: {
|
|
11
|
+
flowId: string;
|
|
12
|
+
sessionId: string;
|
|
13
|
+
runId: string;
|
|
14
|
+
createdAt: string;
|
|
15
|
+
data: StructuredRunData;
|
|
16
|
+
answerNodeIds: string[];
|
|
17
|
+
}): Promise<void>;
|