@hugex/ai 2.9.11 → 2.9.12
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 lt,b as
|
|
1
|
+
import{a as lt,b as Bt,c as Zt,d as vt}from"./chunk-TK4TFAI5.js";import{a as ee,b as oe}from"./chunk-4FUIFBZO.js";import{a as te}from"./chunk-YHXUBVN2.js";import{a as Yo,b as rt,c as Bo,d as it,e as ht,f as Vt,g as Xt,h as Jt,i as Gt,j as zt,k as wt,l as Wt}from"./chunk-57TCP6J4.js";import{a as k,b as nt,c as ko,d as Z,e as Lt,f as St,g as Zo,h as vo}from"./chunk-76OHKISD.js";import{a as Y,b as Po,c as B,d as Ut,e as bt,f as So,g as Qo,h as at,i as ct,j as Yt}from"./chunk-C2HAGFXJ.js";import{a as Do,b as Uo,c as bo,d as Lo,e as jo,f as Eo,g as jt,h as Ho,i as Et,j as Ko,k as qo,l as Vo,m as Xo,n as Jo,o as Go,p as zo,q as Wo,r as Ht,s as Kt,t as qt}from"./chunk-GRZ6ZRHM.js";import{a as Co}from"./chunk-RYHQGPX5.js";import{a as Ao}from"./chunk-R6EKV3WR.js";import{a as $o}from"./chunk-6HY7QUMP.js";import{a as _o,b as Oo}from"./chunk-V6JSMX5A.js";import{a as X,b as W,c as Mo,d as Dt,e as Fo}from"./chunk-G3SGJ7XJ.js";import{a as Qt}from"./chunk-4WAWR4LB.js";import{a as st}from"./chunk-U56YWPSI.js";import{a as ot}from"./chunk-3TXHFKDN.js";import{Agent as lo}from"agents";import{nanoid as uo}from"nanoid";var U=(o,e,s)=>{o.send(e+"::"+s)};async function Xe(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 se(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 V(o){return o.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function dt(o){o.sql`DELETE FROM messages`}async function Je(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 lt,b as Yt,c as Zt,d as St}from"./chunk-TK4TFAI5.js";import{a as te,
|
|
|
6
6
|
cycle INTEGER NOT NULL,
|
|
7
7
|
meta TEXT,
|
|
8
8
|
ts INTEGER NOT NULL
|
|
9
|
-
)`}async function
|
|
9
|
+
)`}async function ne(o,e){let s=e.data??null,t=s!=null?Jt(s):{data:null,truncated:!1},n=t.truncated?Wt(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 lt,b as Yt,c as Zt,d as St}from"./chunk-TK4TFAI5.js";import{a as te,
|
|
|
14
14
|
data = excluded.data,
|
|
15
15
|
cycle = excluded.cycle,
|
|
16
16
|
meta = excluded.meta,
|
|
17
|
-
ts = excluded.ts`}async function ut(o){return o.sql`SELECT ref, domain, description, 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 ne(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 re(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 ie(o,e){o.sql`DELETE FROM context WHERE domain = 'tool' AND cycle <= ${e}`}async function ae(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 pt(o){o.sql`DELETE FROM context`}async function ce(o){await Ve(o),await Je(o)}function xt(o){return{"Content-Type":"application/json",Authorization:o.HX_API_KEY}}function mt(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function Rt(o,e){if(!mt(o))return null;let s=await fetch(`${o.HX_ORA_URL}/internal/runs`,{method:"POST",headers:xt(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 le(o,e){if(!mt(o))return{claimed:!0};let s=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/claim`,{method:"POST",headers:xt(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 gt(o,e,s,t=3){if(!mt(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:xt(o),body:JSON.stringify(s)});if(r.ok)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 de(o,e){if(!mt(o))return Promise.resolve();try{return await Rt(o,e)}catch(s){return console.error("[oraTriggers] recordRun failed",s),null}}var It=Object.freeze({}),Xe="__SYSTEM_";function ue(o){return o.startsWith(Xe)}function Ge(o){let e={};for(let[s,t]of Object.entries(o))ue(s)||(e[s]=t);return Object.freeze(e)}async function yt(o,e){if(!e)return It;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 Ge(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 It;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=>!ue(d.name.slice(t.length))),i=await Promise.all(r.map(async d=>{let p=await s.get(d.name);return p!==null?[d.name.slice(t.length),p]:null})),f={};for(let d of i){if(!d)continue;let[p,l]=d;p&&(f[p]=l)}return Object.freeze(f)}catch(n){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,err:n}),It}}import{nanoid as ss}from"nanoid";function v(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 fe(o,e){return typeof e.cycle=="number"&&Number.isFinite(e.cycle)?e.cycle+1:await ae(o)+1}function pe(o,e,s,t,n){let r=it(v(s));return{...e,memoryConfig:r,cycle:t,setContext:async f=>{await se(o,f),await(n==null?void 0:n(f.ref))},getContextIndex:async()=>ut(o),getContextData:async f=>ne(o,f),getContext:async f=>ft(o,f),resolveContext:async f=>re(o,f),pruneContext:async f=>ie(o,f)}}import{nanoid as ro}from"nanoid";async function me(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 Tt(o,e,s,t,n,r,i){var f,d,p;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});try{let l=await((f=o.getMessages)==null?void 0:f.call(o))??[],{flowId:m,chatId:c,tenant:u}=s.flowData,a=((d=l[l.length-1])==null?void 0:d.type)==="text"?l[l.length-1].content:"NO-TEXT";i==null||i({type:"answer_node",payload:{userMessage:(p=s==null?void 0:s.context)==null?void 0:p.user_input,answer:a}})}catch(l){console.error("answerNodeRunner: failed to emit answer telemetry:",l),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(l)}})}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 f,d,p;let r=(n==null?void 0:n.callerTag)??"llmNodeRunner",i=(n==null?void 0:n.serializeNonStrings)??!1;try{return zt(o,e,{context:s.context??{},results:s.results??{},nodes:((d=(f=s.flowData)==null?void 0:f.state)==null?void 0:d.nodes)??[],secrets:(p=n==null?void 0:n.sessionEnv)==null?void 0:p.secrets},{callerTag:r,serializeNonStrings:i,onError:l=>{t==null||t({type:`error:${r}`,content:l})}})}catch(l){return console.error(l),"error"}}var ge="[redacted]",Nt=(o,e,s,t,n)=>G(o,e,s,n,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function Ct(o,e,s,t,n,r,i){var p,l,m,c,u,a;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let f=null,d=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(s.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(s.results||{}));let y=((p=e.data)==null?void 0:p.url)||"",w=Nt(y,e,s,o,t);if(console.log("[apiNodeRunner] resolved url:",lt(y)?Yt(w):w),!w){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,f);return}let h=(((l=e.data)==null?void 0:l.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",h);let g=((m=e.data)==null?void 0:m.headers)||{},x={},I={};for(let U in g)if(Object.prototype.hasOwnProperty.call(g,U)){let q=String(g[U]??"");I[U]=lt(q),x[U]=Nt(q,e,s,o,t)}let R,$=!1;if(h!=="GET"&&h!=="HEAD"&&((c=e.data)==null?void 0:c.body)!==void 0){let U=typeof e.data.body=="string"?e.data.body:JSON.stringify(e.data.body);$=lt(U),R=Nt(U,e,s,o,t),!x["Content-Type"]&&!x["content-type"]&&(x["Content-Type"]="application/json")}let O={};for(let U in x)O[U]=I[U]?ge:x[U];console.log("[apiNodeRunner] headers:",JSON.stringify(O)),console.log("[apiNodeRunner] body:",$?ge:R),t==null||t({type:"info:apiNodeRunner",content:`${h} ${w}`});let k=Number((u=e.data)==null?void 0:u.timeoutMs),b=new AbortController,M=Number.isFinite(k)&&k>0?setTimeout(()=>b.abort(),k):null,F;try{console.log("[apiNodeRunner] fetching..."),F=await fetch(w,{method:h,headers:x,body:R,signal:b.signal}),console.log("[apiNodeRunner] fetch returned status:",F.status)}finally{M&&clearTimeout(M)}let A=F.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",A);let N;A.includes("application/json")?N=await F.json():N=await F.text(),console.log("[apiNodeRunner] payload preview:",typeof N=="string"?N.slice(0,200):JSON.stringify(N).slice(0,200)),f={ok:F.ok,status:F.status,data:N};let L=Date.now()-d;i==null||i({type:"api_call",payload:{nodeId:e.id,url:w,method:h,status:F.status,latencyMs:L}}),t==null||t({type:"info:apiNodeRunner",content:`Response ${F.status} (${L}ms)`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}catch(y){console.error("Error processing ApiNode:",y),t==null||t({type:"error:apiNodeRunner",content:`API node execution failed: ${y}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(y)}})}finally{console.log("[apiNodeRunner] final result:",(a=JSON.stringify(f))==null?void 0:a.slice(0,300)),n==null||n(e.id,f)}}import{generateObject as We}from"ai";import{z as ye}from"zod";async function At(o,e,s,t,n,r,i){var y,w,h;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let f=(s==null?void 0:s.context)??{},d=String(((y=e==null?void 0:e.data)==null?void 0:y.input_variable)||"user_input").trim(),p=(f==null?void 0:f[d])??"",l=Array.isArray((w=e==null?void 0:e.data)==null?void 0:w.items)?e.data.items:[];if(l.length===0){t==null||t({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let m=String((h=l[l.length-1])==null?void 0:h.id);if(!p||String(p).trim().length===0){t==null||t({type:"warning:classifier",content:"No input for classification \u2014 falling back to last item."}),n==null||n(e.id,{classification:m}),s.context=s.context||{},s.context.classified_id=m,r==null||r(s);return}let u=`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 ut(o){return o.sql`SELECT ref, domain, description, cycle, meta, ts FROM context ORDER BY ts ASC`}async function re(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 ie(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 ae(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 ce(o,e){o.sql`DELETE FROM context WHERE domain = 'tool' AND cycle <= ${e}`}async function le(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 pt(o){o.sql`DELETE FROM context`}async function de(o){await Xe(o),await Je(o)}function Rt(o){return{"Content-Type":"application/json",Authorization:o.HX_API_KEY}}function mt(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function xt(o,e){if(!mt(o))return null;let s=await fetch(`${o.HX_ORA_URL}/internal/runs`,{method:"POST",headers:Rt(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 ue(o,e){if(!mt(o))return{claimed:!0};let s=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/claim`,{method:"POST",headers:Rt(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 gt(o,e,s,t=3){if(!mt(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:Rt(o),body:JSON.stringify(s)});if(r.ok)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 fe(o,e){if(!mt(o))return Promise.resolve();try{return await xt(o,e)}catch(s){return console.error("[oraTriggers] recordRun failed",s),null}}var It=Object.freeze({}),Ge="__SYSTEM_";function pe(o){return o.startsWith(Ge)}function ze(o){let e={};for(let[s,t]of Object.entries(o))pe(s)||(e[s]=t);return Object.freeze(e)}async function yt(o,e){if(!e)return It;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 ze(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 It;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(l=>!pe(l.name.slice(t.length))),i=await Promise.all(r.map(async l=>{let p=await s.get(l.name);return p!==null?[l.name.slice(t.length),p]:null})),c={};for(let l of i){if(!l)continue;let[p,d]=l;p&&(c[p]=d)}return Object.freeze(c)}catch(n){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,err:n}),It}}import{nanoid as is}from"nanoid";function v(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 me(o,e){return typeof e.cycle=="number"&&Number.isFinite(e.cycle)?e.cycle+1:await le(o)+1}function ge(o,e,s,t,n){let r=it(v(s));return{...e,memoryConfig:r,cycle:t,setContext:async c=>{await ne(o,c),await(n==null?void 0:n(c.ref))},getContextIndex:async()=>ut(o),getContextData:async c=>ie(o,c),getContext:async c=>ft(o,c),resolveContext:async c=>ae(o,c),pruneContext:async c=>ce(o,c)}}import{nanoid as io}from"nanoid";async function ye(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 Tt(o,e,s,t,n,r,i){var c,l,p;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});try{let d=await((c=o.getMessages)==null?void 0:c.call(o))??[],{flowId:m,chatId:u,tenant:f}=s.flowData,a=((l=d[d.length-1])==null?void 0:l.type)==="text"?d[d.length-1].content:"NO-TEXT";i==null||i({type:"answer_node",payload:{userMessage:(p=s==null?void 0:s.context)==null?void 0:p.user_input,answer:a}})}catch(d){console.error("answerNodeRunner: failed to emit answer telemetry:",d),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(d)}})}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 c,l,p;let r=(n==null?void 0:n.callerTag)??"llmNodeRunner",i=(n==null?void 0:n.serializeNonStrings)??!1;try{return Yt(o,e,{context:s.context??{},results:s.results??{},nodes:((l=(c=s.flowData)==null?void 0:c.state)==null?void 0:l.nodes)??[],secrets:(p=n==null?void 0:n.sessionEnv)==null?void 0:p.secrets},{callerTag:r,serializeNonStrings:i,onError:d=>{t==null||t({type:`error:${r}`,content:d})}})}catch(d){return console.error(d),"error"}}var he="[redacted]",Nt=(o,e,s,t,n)=>G(o,e,s,n,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function Ct(o,e,s,t,n,r,i){var p,d,m,u,f,a;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=null,l=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(s.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(s.results||{}));let g=((p=e.data)==null?void 0:p.url)||"",h=Nt(g,e,s,o,t);if(console.log("[apiNodeRunner] resolved url:",lt(g)?Bt(h):h),!h){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,c);return}let w=(((d=e.data)==null?void 0:d.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",w);let y=((m=e.data)==null?void 0:m.headers)||{},R={},x={};for(let D in y)if(Object.prototype.hasOwnProperty.call(y,D)){let K=String(y[D]??"");x[D]=lt(K),R[D]=Nt(K,e,s,o,t)}let I,M=!1;if(w!=="GET"&&w!=="HEAD"&&((u=e.data)==null?void 0:u.body)!==void 0){let D=typeof e.data.body=="string"?e.data.body:JSON.stringify(e.data.body);M=lt(D),I=Nt(D,e,s,o,t),!R["Content-Type"]&&!R["content-type"]&&(R["Content-Type"]="application/json")}let _={};for(let D in R)_[D]=x[D]?he:R[D];console.log("[apiNodeRunner] headers:",JSON.stringify(_)),console.log("[apiNodeRunner] body:",M?he:I),t==null||t({type:"info:apiNodeRunner",content:`${w} ${h}`});let P=Number((f=e.data)==null?void 0:f.timeoutMs),b=new AbortController,F=Number.isFinite(P)&&P>0?setTimeout(()=>b.abort(),P):null,$;try{console.log("[apiNodeRunner] fetching..."),$=await fetch(h,{method:w,headers:R,body:I,signal:b.signal}),console.log("[apiNodeRunner] fetch returned status:",$.status)}finally{F&&clearTimeout(F)}let A=$.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",A);let N;A.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)),c={ok:$.ok,status:$.status,data:N};let L=Date.now()-l;i==null||i({type:"api_call",payload:{nodeId:e.id,url:h,method:w,status:$.status,latencyMs:L}}),t==null||t({type:"info:apiNodeRunner",content:`Response ${$.status} (${L}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(c))==null?void 0:a.slice(0,300)),n==null||n(e.id,c)}}import{generateObject as We}from"ai";import{z as we}from"zod";async function At(o,e,s,t,n,r,i){var g,h,w;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=(s==null?void 0:s.context)??{},l=String(((g=e==null?void 0:e.data)==null?void 0:g.input_variable)||"user_input").trim(),p=(c==null?void 0:c[l])??"",d=Array.isArray((h=e==null?void 0:e.data)==null?void 0:h.items)?e.data.items:[];if(d.length===0){t==null||t({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let m=String((w=d[d.length-1])==null?void 0:w.id);if(!p||String(p).trim().length===0){t==null||t({type:"warning:classifier",content:"No input for classification \u2014 falling back to last item."}),n==null||n(e.id,{classification:m}),s.context=s.context||{},s.context.classified_id=m,r==null||r(s);return}let f=`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
|
-
${
|
|
22
|
-
label: ${
|
|
23
|
-
keywords/topics: ${
|
|
21
|
+
${d.map(y=>{let R=y.keywords??y["keywords/topics"]??"",x=Array.isArray(R)?R.join(", "):String(R||"");return`- id: ${y.id}
|
|
22
|
+
label: ${y.label}
|
|
23
|
+
keywords/topics: ${x}`}).join(`
|
|
24
24
|
`)}
|
|
25
25
|
`,a=`User message:
|
|
26
26
|
"""${String(p).trim()}"""
|
|
27
27
|
|
|
28
|
-
Select the best matching category id.`;try{let
|
|
28
|
+
Select the best matching category id.`;try{let y=Date.now(),R=d.map($=>String($.id)),x="gpt_4_1_mini",I=await rt(x,o);if(!I)throw new Error(`Model '${x}' not found in registry`);let{modelHandle:M,effectiveParams:_}=I,P=await We({model:M,messages:[{role:"system",content:f},{role:"user",content:a}],schema:we.object({classification:we.enum(R).describe("The id of the best matching category")}),temperature:_.temperature??0}),b=Date.now()-y,F=P.object.classification;i==null||i({type:"class_telemetry",payload:{nodeId:e.id,totalLatency:b,model:P.response.modelId,usage:P.usage,options:R}}),i==null||i({type:"class_result",payload:{result:P}}),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(y){t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(y)}})}}import{stepCountIs as Se,streamText as Qe}from"ai";import{nanoid as Ze}from"nanoid";import"zod";function Re(o,e){var t,n,r,i,c,l;let s="";if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let p of o.data.varMapping){let d=p.from;if(!d)continue;let m=!1;if(d==="files"||d==="file_content")m=!0;else{let u=d.indexOf(".");if(u!==-1){let f=d.substring(0,u),a=d.substring(u+1).split(".")[0],g=(i=(r=(n=e.flowData)==null?void 0:n.state)==null?void 0:r.nodes)==null?void 0:i.find(h=>h.id===f);if(g){let w=at(g).find(y=>y.name===a);(w==null?void 0:w.type)==="file"&&(m=!0)}}}if(m){let u=ct(d,{context:e.context||{},results:e.results||{},nodes:((l=(c=e.flowData)==null?void 0:c.state)==null?void 0:l.nodes)||[]});typeof u=="string"&&u.trim()&&(s+=(s?`
|
|
29
29
|
|
|
30
|
-
`:"")+c)}}return s}function we(o,e){var t,n,r,i,f,d;let s=[];if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let p of o.data.varMapping){let l=p.from;if(!l)continue;let m=!1;if(l==="images")m=!0;else{let c=l.indexOf(".");if(c!==-1){let u=l.substring(0,c),a=l.substring(c+1).split(".")[0],y=(i=(r=(n=e.flowData)==null?void 0:n.state)==null?void 0:r.nodes)==null?void 0:i.find(w=>w.id===u);if(y){let h=at(y).find(g=>g.name===a);(h==null?void 0:h.type)==="image"&&(m=!0)}}}if(m){let c=ct(l,{context:e.context||{},results:e.results||{},nodes:((d=(f=e.flowData)==null?void 0:f.state)==null?void 0:d.nodes)||[]});Array.isArray(c)&&s.push(...c)}}return s}var ze=ot({"../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 Ye=ot({});function _t(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(f,...d)=>{var c;if(!t.getContextIndex)return r(f,...d);let p=await ht(f),m=(await t.getContextIndex()).find(u=>{if(u.domain!=="tool")return!1;let a=wt(u.meta);return a.toolName===o&&a.paramsHash===p});if(m){let u=await((c=t.getContext)==null?void 0:c.call(t,m.ref));if((u==null?void 0:u.data)!=null&&wt(u.meta).truncated!==!0){n==null||n({type:"info:memory:cacheHit",content:{ref:u.ref,toolName:o}});try{return JSON.parse(u.data)}catch{return u.data}}}return r(f,...d)},e}async function Se(o,e,s,t){var l,m;if(!((l=s.memoryConfig)!=null&&l.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 f=Array.isArray((m=e==null?void 0:e.data)==null?void 0:m.tools)?e.data.tools:[],d=new Map;for(let c of f)c&&typeof c.id=="string"&&d.set(c.id,c);let p=new Map;for(let c of Object.values(s.toolDefs??{}))c&&c.name&&p.set(c.name,c);for(let c of n){let u=c.toolCallId,a=c.toolName,y=i.get(u);if(!a||!y||a==="readSkillRef")continue;let w=c.args??c.input,h=y.result??y.output,g=!1,x="",I="tool",R="",$=p.get(a);$&&$.kind==="skill"&&(g=!0,x=`skill:${a}`,I="skill",R=`Skill instructions for ${a}`),x||(x=await Vt(a,w),R=Kt(w,h));let O=d.get(a)??f.find(M=>M.id===a),k=await ht(w),b=typeof h=="string"?h:JSON.stringify(h??null);await s.setContext({ref:x,domain:I,description:R,data:b,cycle:s.cycle,meta:JSON.stringify({toolName:a,paramsHash:k,cacheable:(O==null?void 0:O.cacheable)===!0})}),t==null||t({type:"info:memory:updated",content:{ref:x}})}}async function ve(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=c=>{var x,I;let u=typeof(c==null?void 0:c.description)=="string"?c.description:"",a=c==null?void 0:c.inputSchema,y;try{let R=(a==null?void 0:a.shape)??(typeof((x=a==null?void 0:a._def)==null?void 0:x.shape)=="function"?a._def.shape():(I=a==null?void 0:a._def)==null?void 0:I.shape);R&&typeof R=="object"&&(y=R)}catch{}let w=y?Object.keys(y):[],h=u?`description="${u.length>120?u.slice(0,120)+"\u2026":u}"`:"description=(none)",g=w.length?`inputSchema={${w.join(", ")}}`:"inputSchema=(none)";return`${h} ${g}`},f=(()=>{let c=[],u=[],a=[],y=[];for(let h=0;h<n.length;h++){let g=n[h];!g||typeof g!="object"||typeof g.id!="string"?y.push(h):g.kind==="builtin"?c.push(g.id):g.kind==="skill"?a.push(g.id):g.kind==="http"||g.kind==="mcp"||g.kind==="composio"?u.push(g.id):y.push(h)}let w=[];return c.length&&w.push(`builtin[${c.join(", ")}]`),u.length&&w.push(`custom[${u.join(", ")}]`),a.length&&w.push(`skill[${a.join(", ")}]`),y.length&&w.push(`invalid@[${y.join(", ")}]`),w.join(" ")||"(none)"})();console.log(`[tools] node ${s.id} requested (${n.length}): ${f}`);let d=!1,p=async()=>{if(d&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},d=!0,o.toolDefs;try{let c=await vt(o.env),u={};for(let a of c)a&&a.id&&(u[a.id]=a);o.toolDefs=u}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},l=[];for(let c=0;c<n.length;c++){let u=n[c];if(!u||typeof u!="object"||typeof u.id!="string"||u.kind!=="builtin"&&u.kind!=="http"&&u.kind!=="mcp"&&u.kind!=="composio"&&u.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${c}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let a=u;if(a.kind!=="builtin"){let w=(await p())[a.id];if(!w){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 g=await Qt(w,o,e,t),x=Object.keys(g);for(let[I,R]of Object.entries(g))r[I]=_t(I,R,a,o,t);console.log(`[tools] \u2713 composio '${a.id}' \u2192 ${x.length} tool(s)`)}catch(g){console.error(`[tools] \u2717 composio '${a.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${a.id}': ${String(g)}`})}continue}if(a.kind==="skill"){if(w.kind!=="skill"){console.error(`[tools] \u2717 skill '${a.id}': row is of kind '${w.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${a.id}' is not a skill`});continue}let g=w.name;if(r[g]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${g}' \u2014 builtin/other already registered, skipping skill '${a.id}'`});continue}try{r[g]=te(w,o,e,t),l.push(w);let x=typeof w.execution=="string"?JSON.parse(w.execution):w.execution||{},I=Array.isArray(x.references)?x.references.map(R=>R==null?void 0:R.name):[];console.log(`[tools] \u2713 skill '${a.id}' \u2192 '${g}' (refs: ${I.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:g,refCount:I.length,refs:I}})}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 h=w.name;if(r[h]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${h}' \u2014 builtin already registered, skipping custom tool '${a.id}'`});continue}try{let g=St(w,o,e,t);r[h]=_t(h,g,a,o,t),console.log(`[tools] \u2713 custom '${a.id}' \u2192 '${h}'`),console.log(`[tools] ${i(r[h])}`)}catch(g){console.error(`[tools] \u2717 custom '${a.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${a.id}': ${String(g)}`})}continue}if(!Bt[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 y;try{y=await ze(`../tools/${a.id}.ts`)}catch{y=await Ye(`../tools/${a.id}.js`)}let w;if(y[a.id])w=y[a.id];else if(y.default)w=y.default;else if(y.create)w=y.create;else{let O=Object.values(y);O.length>0&&(w=O[0])}if(!w){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${a.id}'`});continue}let h,g,x={};if(a.params&&typeof a.params=="object"){if(typeof a.params.description=="string"?h=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 O=a.params.inputSchema;typeof O=="object"&&(typeof O.safeParse=="function"||O._def)?g=O:typeof O=="object"&&O!==null&&O.type==="object"&&O.properties?(g=Zt(O),g||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 I=w(o,e,x,t);h&&I&&typeof I=="object"&&(I.description=h),g&&I&&typeof I=="object"&&(I.inputSchema=g),r[a.id]=_t(a.id,I,a,o,t);let R=[];h&&R.push("description"),g&&R.push("inputSchema"),Object.keys(x).length&&R.push(`defaults(${Object.keys(x).join(",")})`);let $=R.length?` [overrides: ${R.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${a.id}'${$}`),console.log(`[tools] ${i(I)}`)}catch(y){console.error(`[tools] \u2717 builtin '${a.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${a.id}': ${String(y)}`});continue}}if(l.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=ee(o,l,e,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${l.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:l.map(c=>c.name)}})}catch(c){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(c)}`)}return r}async function Ot(o,e,s,t,n,r,i){var k,b,M,F,A;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let f=!1;try{let N=(k=s.flowData)==null?void 0:k.state;if(N&&N.edges&&N.nodes){let L=N.edges.filter(U=>U.source===e.id);if(L.length>0){let U=N.nodes.find(q=>q.id===L[0].target);U&&U.type==="answerNode"&&(f=!0)}}}catch(N){console.error("Error determining next node for streaming:",N)}let d=G(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 p=d,l="";if((b=o.memoryConfig)!=null&&b.enabled){let N=await((M=o.getContextIndex)==null?void 0:M.call(o))??[];l=Xt(N),d+=l}let m=G(e.data.user_template||"",e,s,t,{sessionEnv:o}),c=N=>N&&Object.fromEntries(Object.keys(N).map(L=>[L,"[redacted]"])),u=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:c(o.secrets),userAuth:c(o.userAuth)}:o,a=G(e.data.template,e,s,void 0,{sessionEnv:u})||p;a+=l;let y=G(e.data.user_template||"",e,s,void 0,{sessionEnv:u});t==null||t({type:`info:llmNodeRunner:${e.id}`,content:a}),t==null||t({type:`info:llmNodeRunner:${e.id}`,content:y});let w=(F=e==null?void 0:e.data)==null?void 0:F.window_size,h=Number(w);(!Number.isInteger(h)||h<=0)&&(h=5);let g=we(e,s),x=he(e,s),R=(await((A=o.getMessages)==null?void 0:A.call(o))??[]).slice(-h),$=R.filter(N=>N&&typeof N.role=="string"&&typeof N.content=="string");$.length!==R.length&&console.warn(`Filtered ${R.length-$.length} invalid messages from history`);let O=eo($,m,g,x);await to(d,O,o.conn,t,e,f,n,s,r,o,i)}async function to(o,e,s,t,n,r,i,f,d,p,l){var c;let m=Date.now();if(!((c=p.env)!=null&&c.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(u,a)=>{var A,N,L,U,q,Q,Z;let y,w={},h,g="none",x=!1,I,R=!1,$=!1,O=0,k=0,b=(A=n==null?void 0:n.data)==null?void 0:A.sendReasoning,M=b!==!1;try{let j=(N=n==null?void 0:n.data)==null?void 0:N.model,W=Array.isArray(j)?j[0]:j||"gpt_5_nano",T=Lt(n==null?void 0:n.data),_=await rt(W,p,T);if(!_)throw new Error(`Model '${W}' not found in registry`);y=_.modelHandle,w=_.effectiveParams||{},g=_.reasoning.kind;let C=Ht(_.reasoning,(L=n==null?void 0:n.data)==null?void 0:L.reasoningEffort);x=M&&Et(_.reasoning);let H=typeof((U=n==null?void 0:n.data)==null?void 0:U.reasoningMaxTokens)=="number"?n.data.reasoningMaxTokens:void 0;h=qt(_.provider,{effort:C,exposeReasoning:x,maxTokens:H}),C&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:C})),console.log(`[reasoning] ${JSON.stringify({model:W,provider:_.provider,capability:_.reasoning,requestedEffort:((q=n==null?void 0:n.data)==null?void 0:q.reasoningEffort)??null,resolvedEffort:C??null,sendReasoning:M,exposeReasoning:x,providerOptions:h??null},null,2)}`);for(let E of _.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:E});t==null||t({type:"info:llmNodeRunner:model",content:W}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(Q=n==null?void 0:n.data)!=null&&Q.generationPreset?{preset:n.data.generationPreset}:{},...w,...g!=="none"?{reasoning:g,configuredSendReasoning:b,sendReasoning:M,exposeReasoning:x,...C?{effort:C}:{}}:{}}})}catch(j){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(j)}`}),j}let F=await ve(p,f,n,t);if((Z=p.memoryConfig)!=null&&Z.enabled){let{recall:j}=await import("./recall-IABRCSHY.js");F.recall=j(p,f,void 0,t)}console.log(`[tools] node ${n.id} loaded ${Object.keys(F).length}: ${Object.keys(F).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:n.id,tools:Object.keys(F)}});try{let j=Qe({model:y,system:o,messages:e,stopWhen:(()=>{var E;let _=!!F.readSkillRef?10:5,C=Number(((E=n.data)==null?void 0:E.max_steps)??_),H=Number.isFinite(C)?Math.max(1,Math.min(30,C)):_;return Be(H)})(),...jt(w),...h?{providerOptions:h}:{},tools:F,onFinish:async T=>{var Mt,kt;let _=T.text||"",C=T.reasoningText??((Mt=T.reasoning)==null?void 0:Mt.text)??"";if(console.log(`[reasoning] done: deltas=${O} chars=${k} result.reasoningText=${C.length} finishReason=${T.finishReason??"n/a"} reasoningTokens=${((kt=T.usage)==null?void 0:kt.reasoningTokens)??"n/a"}`),M&&x&&!R&&C&&s){R=!0;try{D(s,P.SERVER_REASONING_STREAM,C)}catch(Ke){console.warn("Failed to send finished reasoning over connection",Ke)}}let H={id:Ze(),role:"assistant",type:"text",content:_,ts:Date.now()};r&&(p.setMessages?await p.setMessages(H):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),s&&M&&R&&!$&&($=!0,D(s,P.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),r&&s&&D(s,P.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),i==null||i((n==null?void 0:n.id)||"llm_result",_),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(T)});let E=Date.now()-m,qe=I?I-m:void 0;l==null||l({type:"llm_telemetry",payload:{nodeId:n.id,totalLatency:E,timeToFirstToken:qe,model:T.response.modelId,usage:T.usage}}),l==null||l({type:"llm_result",payload:{result:T}})},onStepFinish:async T=>{let _=(C,H=200)=>{let E=typeof C=="string"?C:JSON.stringify(C);return E?E.length>H?`${E.slice(0,H)}\u2026(+${E.length-H})`:E:""};if(T.toolCalls&&T.toolCalls.length>0){for(let C of T.toolCalls)console.log(`[tools] \u2192 ${C.toolName}(${_(C.args??C.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${n.id}`,content:JSON.stringify(T.toolCalls)})}if(T.toolResults&&T.toolResults.length>0){for(let C of T.toolResults)console.log(`[tools] \u2190 ${C.toolName} \u2192 ${_(C.result??C.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${n.id}`,content:JSON.stringify(T.toolResults)})}await Se(T,n,p,t)},experimental_onToolCallStart:T=>{var _;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(_=T==null?void 0:T.toolCall)==null?void 0:_.toolName,status:"start"}})},experimental_onToolCallFinish:T=>{var _,C;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(_=T==null?void 0:T.toolCall)==null?void 0:_.toolName,status:((C=T==null?void 0:T.toolOutput)==null?void 0:C.type)==="tool-error"?"error":"success"}})},onError:T=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),a(T)},onChunk:T=>{if(T.chunk.type==="reasoning-delta"){let C=T.chunk.text??T.chunk.delta??"";if(C&&(R=!0,O+=1,k+=C.length,O===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),M&&s&&C)try{D(s,P.SERVER_REASONING_STREAM,C)}catch(H){console.warn("Failed to send reasoning chunk over connection",H)}return}if(T.chunk.type==="text-delta"){if(I||(I=Date.now()),s&&M&&R&&!$){$=!0;try{D(s,P.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(C){console.warn("Failed to send reasoning complete over connection",C)}}return}l==null||l({type:T.chunk.type,payload:{nodeId:n.id,chunk:T.chunk}});let _=`llm_chunk:${T.chunk.type}`;t==null||t({type:_,content:{...T}})}}),W=async()=>{let T="";for await(let _ of j.fullStream)if(_.type==="text-delta"){if(T+=_.text,r&&s)try{D(s,P.SERVER_TEXT_STREAM,_.text)}catch(C){console.warn("Failed to send chunk over connection",C)}}else if(_.type==="finish-step"&&_.finishReason==="tool-calls"){if(r&&s&&T.trim())try{D(s,P.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(C){console.warn("Failed to flush text segment over connection",C)}T=""}};await Promise.all([j,W()]),u(),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 eo(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,p=l=>{let m=[],c="";if(r&&(c+=`[Attached files]
|
|
30
|
+
`:"")+u)}}return s}function xe(o,e){var t,n,r,i,c,l;let s=[];if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let p of o.data.varMapping){let d=p.from;if(!d)continue;let m=!1;if(d==="images")m=!0;else{let u=d.indexOf(".");if(u!==-1){let f=d.substring(0,u),a=d.substring(u+1).split(".")[0],g=(i=(r=(n=e.flowData)==null?void 0:n.state)==null?void 0:r.nodes)==null?void 0:i.find(h=>h.id===f);if(g){let w=at(g).find(y=>y.name===a);(w==null?void 0:w.type)==="image"&&(m=!0)}}}if(m){let u=ct(d,{context:e.context||{},results:e.results||{},nodes:((l=(c=e.flowData)==null?void 0:c.state)==null?void 0:l.nodes)||[]});Array.isArray(u)&&s.push(...u)}}return s}var Ye=ot({"../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 Be=ot({});function _t(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(c,...l)=>{var u;if(!t.getContextIndex)return r(c,...l);let p=await ht(c),m=(await t.getContextIndex()).find(f=>{if(f.domain!=="tool")return!1;let a=wt(f.meta);return a.toolName===o&&a.paramsHash===p});if(m){let f=await((u=t.getContext)==null?void 0:u.call(t,m.ref));if((f==null?void 0:f.data)!=null&&wt(f.meta).truncated!==!0){n==null||n({type:"info:memory:cacheHit",content:{ref:f.ref,toolName:o}});try{return JSON.parse(f.data)}catch{return f.data}}}return r(c,...l)},e}async function ve(o,e,s,t){var d,m;if(!((d=s.memoryConfig)!=null&&d.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 u of r)u!=null&&u.toolCallId&&i.set(u.toolCallId,u);let c=Array.isArray((m=e==null?void 0:e.data)==null?void 0:m.tools)?e.data.tools:[],l=new Map;for(let u of c)u&&typeof u.id=="string"&&l.set(u.id,u);let p=new Map;for(let u of Object.values(s.toolDefs??{}))u&&u.name&&p.set(u.name,u);for(let u of n){let f=u.toolCallId,a=u.toolName,g=i.get(f);if(!a||!g||a==="readSkillRef")continue;let h=u.args??u.input,w=g.result??g.output,y=!1,R="",x="tool",I="",M=p.get(a);M&&M.kind==="skill"&&(y=!0,R=`skill:${a}`,x="skill",I=`Skill instructions for ${a}`),R||(R=await Xt(a,h),I=Vt(h,w));let _=l.get(a)??c.find(F=>F.id===a),P=await ht(h),b=typeof w=="string"?w:JSON.stringify(w??null);await s.setContext({ref:R,domain:x,description:I,data:b,cycle:s.cycle,meta:JSON.stringify({toolName:a,paramsHash:P,cacheable:(_==null?void 0:_.cacheable)===!0})}),t==null||t({type:"info:memory:updated",content:{ref:R}})}}async function to(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=u=>{var R,x;let f=typeof(u==null?void 0:u.description)=="string"?u.description:"",a=u==null?void 0:u.inputSchema,g;try{let I=(a==null?void 0:a.shape)??(typeof((R=a==null?void 0:a._def)==null?void 0:R.shape)=="function"?a._def.shape():(x=a==null?void 0:a._def)==null?void 0:x.shape);I&&typeof I=="object"&&(g=I)}catch{}let h=g?Object.keys(g):[],w=f?`description="${f.length>120?f.slice(0,120)+"\u2026":f}"`:"description=(none)",y=h.length?`inputSchema={${h.join(", ")}}`:"inputSchema=(none)";return`${w} ${y}`},c=(()=>{let u=[],f=[],a=[],g=[];for(let w=0;w<n.length;w++){let y=n[w];!y||typeof y!="object"||typeof y.id!="string"?g.push(w):y.kind==="builtin"?u.push(y.id):y.kind==="skill"?a.push(y.id):y.kind==="http"||y.kind==="mcp"||y.kind==="composio"?f.push(y.id):g.push(w)}let h=[];return u.length&&h.push(`builtin[${u.join(", ")}]`),f.length&&h.push(`custom[${f.join(", ")}]`),a.length&&h.push(`skill[${a.join(", ")}]`),g.length&&h.push(`invalid@[${g.join(", ")}]`),h.join(" ")||"(none)"})();console.log(`[tools] node ${s.id} requested (${n.length}): ${c}`);let l=!1,p=async()=>{if(l&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},l=!0,o.toolDefs;try{let u=await te(o.env),f={};for(let a of u)a&&a.id&&(f[a.id]=a);o.toolDefs=f}catch(u){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(u)}`}),o.toolDefs=o.toolDefs||{}}return l=!0,o.toolDefs},d=[];for(let u=0;u<n.length;u++){let f=n[u];if(!f||typeof f!="object"||typeof f.id!="string"||f.kind!=="builtin"&&f.kind!=="http"&&f.kind!=="mcp"&&f.kind!=="composio"&&f.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${u}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let a=f;if(a.kind!=="builtin"){let h=(await p())[a.id];if(!h){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 y=await Qt(h,o,e,t),R=Object.keys(y);for(let[x,I]of Object.entries(y))r[x]=_t(x,I,a,o,t);console.log(`[tools] \u2713 composio '${a.id}' \u2192 ${R.length} tool(s)`)}catch(y){console.error(`[tools] \u2717 composio '${a.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${a.id}': ${String(y)}`})}continue}if(a.kind==="skill"){if(h.kind!=="skill"){console.error(`[tools] \u2717 skill '${a.id}': row is of kind '${h.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${a.id}' is not a skill`});continue}let y=h.name;if(r[y]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${y}' \u2014 builtin/other already registered, skipping skill '${a.id}'`});continue}try{r[y]=ee(h,o,e,t),d.push(h);let R=typeof h.execution=="string"?JSON.parse(h.execution):h.execution||{},x=Array.isArray(R.references)?R.references.map(I=>I==null?void 0:I.name):[];console.log(`[tools] \u2713 skill '${a.id}' \u2192 '${y}' (refs: ${x.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:y,refCount:x.length,refs:x}})}catch(R){console.error(`[tools] \u2717 skill '${a.id}': ${String(R)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${a.id}': ${String(R)}`})}continue}let w=h.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 y=vt(h,o,e,t);r[w]=_t(w,y,a,o,t),console.log(`[tools] \u2713 custom '${a.id}' \u2192 '${w}'`),console.log(`[tools] ${i(r[w])}`)}catch(y){console.error(`[tools] \u2717 custom '${a.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${a.id}': ${String(y)}`})}continue}if(!St[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 Ye(`../tools/${a.id}.ts`)}catch{g=await Be(`../tools/${a.id}.js`)}let h;if(g[a.id])h=g[a.id];else if(g.default)h=g.default;else if(g.create)h=g.create;else{let _=Object.values(g);_.length>0&&(h=_[0])}if(!h){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${a.id}'`});continue}let w,y,R={};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.params.inputSchema;typeof _=="object"&&(typeof _.safeParse=="function"||_._def)?y=_:typeof _=="object"&&_!==null&&_.type==="object"&&_.properties?(y=Zt(_),y||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)?R=a.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${a.id}' \u2014 must be an object`}),R={}):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`}),R={}):R={}}let x=h(o,e,R,t);w&&x&&typeof x=="object"&&(x.description=w),y&&x&&typeof x=="object"&&(x.inputSchema=y),r[a.id]=_t(a.id,x,a,o,t);let I=[];w&&I.push("description"),y&&I.push("inputSchema"),Object.keys(R).length&&I.push(`defaults(${Object.keys(R).join(",")})`);let M=I.length?` [overrides: ${I.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${a.id}'${M}`),console.log(`[tools] ${i(x)}`)}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(d.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=oe(o,d,e,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${d.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:d.map(u=>u.name)}})}catch(u){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(u)}`)}return r}async function Ot(o,e,s,t,n,r,i){var P,b,F,$,A;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=!1;try{let N=(P=s.flowData)==null?void 0:P.state;if(N&&N.edges&&N.nodes){let L=N.edges.filter(D=>D.source===e.id);if(L.length>0){let D=N.nodes.find(K=>K.id===L[0].target);D&&D.type==="answerNode"&&(c=!0)}}}catch(N){console.error("Error determining next node for streaming:",N)}let l=G(e.data.template,e,s,t,{sessionEnv:o});(!l||!l.trim())&&(l="Answer straight forward to the user, dont offer any other option to continue");let p=l,d="";if((b=o.memoryConfig)!=null&&b.enabled){let N=await((F=o.getContextIndex)==null?void 0:F.call(o))??[];d=Gt(N),l+=d}let m=G(e.data.user_template||"",e,s,t,{sessionEnv:o}),u=N=>N&&Object.fromEntries(Object.keys(N).map(L=>[L,"[redacted]"])),f=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:u(o.secrets),userAuth:u(o.userAuth)}:o,a=G(e.data.template,e,s,void 0,{sessionEnv:f})||p;a+=d;let g=G(e.data.user_template||"",e,s,void 0,{sessionEnv:f});t==null||t({type:`info:llmNodeRunner:${e.id}`,content:a}),t==null||t({type:`info:llmNodeRunner:${e.id}`,content:g});let h=($=e==null?void 0:e.data)==null?void 0:$.window_size,w=Number(h);(!Number.isInteger(w)||w<=0)&&(w=5);let y=xe(e,s),R=Re(e,s),I=(await((A=o.getMessages)==null?void 0:A.call(o))??[]).slice(-w),M=I.filter(N=>N&&typeof N.role=="string"&&typeof N.content=="string");M.length!==I.length&&console.warn(`Filtered ${I.length-M.length} invalid messages from history`);let _=oo(M,m,y,R);await eo(l,_,o.conn,t,e,c,n,s,r,o,i)}async function eo(o,e,s,t,n,r,i,c,l,p,d){var u;let m=Date.now();if(!((u=p.env)!=null&&u.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(f,a)=>{var A,N,L,D,K,S,Q;let g,h={},w,y="none",R=!1,x,I=!1,M=!1,_=0,P=0,b=(A=n==null?void 0:n.data)==null?void 0:A.sendReasoning,F=b!==!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=jt(n==null?void 0:n.data),O=await rt(z,p,T);if(!O)throw new Error(`Model '${z}' not found in registry`);g=O.modelHandle,h=O.effectiveParams||{},y=O.reasoning.kind;let C=Kt(O.reasoning,(L=n==null?void 0:n.data)==null?void 0:L.reasoningEffort);R=F&&Ht(O.reasoning);let H=typeof((D=n==null?void 0:n.data)==null?void 0:D.reasoningMaxTokens)=="number"?n.data.reasoningMaxTokens:void 0;w=qt(O.provider,{effort:C,exposeReasoning:R,maxTokens:H}),C&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:C})),console.log(`[reasoning] ${JSON.stringify({model:z,provider:O.provider,capability:O.reasoning,requestedEffort:((K=n==null?void 0:n.data)==null?void 0:K.reasoningEffort)??null,resolvedEffort:C??null,sendReasoning:F,exposeReasoning:R,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:{...(S=n==null?void 0:n.data)!=null&&S.generationPreset?{preset:n.data.generationPreset}:{},...h,...y!=="none"?{reasoning:y,configuredSendReasoning:b,sendReasoning:F,exposeReasoning:R,...C?{effort:C}:{}}:{}}})}catch(j){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(j)}`}),j}let $=await to(p,c,n,t);if((Q=p.memoryConfig)!=null&&Q.enabled){let{recall:j}=await import("./recall-IABRCSHY.js");$.recall=j(p,c,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=Qe({model:g,system:o,messages:e,stopWhen:(()=>{var E;let O=!!$.readSkillRef?10:5,C=Number(((E=n.data)==null?void 0:E.max_steps)??O),H=Number.isFinite(C)?Math.max(1,Math.min(30,C)):O;return Se(H)})(),...Et(h),...w?{providerOptions:w}:{},tools:$,onFinish:async T=>{var Pt,kt;let O=T.text||"",C=T.reasoningText??((Pt=T.reasoning)==null?void 0:Pt.text)??"";if(console.log(`[reasoning] done: deltas=${_} chars=${P} result.reasoningText=${C.length} finishReason=${T.finishReason??"n/a"} reasoningTokens=${((kt=T.usage)==null?void 0:kt.reasoningTokens)??"n/a"}`),F&&R&&!I&&C&&s){I=!0;try{U(s,k.SERVER_REASONING_STREAM,C)}catch(Ve){console.warn("Failed to send finished reasoning over connection",Ve)}}let H={id:Ze(),role:"assistant",type:"text",content:O,ts:Date.now()};r&&(p.setMessages?await p.setMessages(H):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),s&&F&&I&&!M&&(M=!0,U(s,k.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),r&&s&&U(s,k.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,qe=x?x-m:void 0;d==null||d({type:"llm_telemetry",payload:{nodeId:n.id,totalLatency:E,timeToFirstToken:qe,model:T.response.modelId,usage:T.usage}}),d==null||d({type:"llm_result",payload:{result:T}})},onStepFinish:async T=>{let O=(C,H=200)=>{let E=typeof C=="string"?C:JSON.stringify(C);return E?E.length>H?`${E.slice(0,H)}\u2026(+${E.length-H})`:E:""};if(T.toolCalls&&T.toolCalls.length>0){for(let C of T.toolCalls)console.log(`[tools] \u2192 ${C.toolName}(${O(C.args??C.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${n.id}`,content:JSON.stringify(T.toolCalls)})}if(T.toolResults&&T.toolResults.length>0){for(let C of T.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(T.toolResults)})}await ve(T,n,p,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,C;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(O=T==null?void 0:T.toolCall)==null?void 0:O.toolName,status:((C=T==null?void 0:T.toolOutput)==null?void 0:C.type)==="tool-error"?"error":"success"}})},onError:T=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),a(T)},onChunk:T=>{if(T.chunk.type==="reasoning-delta"){let C=T.chunk.text??T.chunk.delta??"";if(C&&(I=!0,_+=1,P+=C.length,_===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),F&&s&&C)try{U(s,k.SERVER_REASONING_STREAM,C)}catch(H){console.warn("Failed to send reasoning chunk over connection",H)}return}if(T.chunk.type==="text-delta"){if(x||(x=Date.now()),s&&F&&I&&!M){M=!0;try{U(s,k.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(C){console.warn("Failed to send reasoning complete over connection",C)}}return}d==null||d({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{U(s,k.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&&T.trim())try{U(s,k.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(C){console.warn("Failed to flush text segment over connection",C)}T=""}};await Promise.all([j,z()]),f(),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 oo(o,e,s,t){let n=!!(s&&s.length>0),r=!!t,i=n||r,l=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,p=d=>{let m=[],u="";if(r&&(u+=`[Attached files]
|
|
31
31
|
${t}
|
|
32
32
|
[End of attached files]
|
|
33
33
|
|
|
34
|
-
`),
|
|
34
|
+
`),d&&(u+=d),u&&m.push({type:"text",text:u}),n)for(let f of s)m.push({type:"image",image:f.data,mimeType:f.mimeType});return m};return e&&l&&l.content===e?[...o.slice(0,-1).map(m=>({role:m.role,content:m.content})),{role:"user",content:p(e)}]:e?[...o.map(d=>({role:d.role,content:d.content})),{role:"user",content:p(e)}]:i&&l?[...o.slice(0,-1).map(m=>({role:m.role,content:m.content})),{role:"user",content:p(l.content)}]:o.map(d=>({role:d.role,content:d.content}))}async function $t(o,e,s,t,n,r,i){var p,d,m,u;console.log(`**** MEMO Node id: ${e.id} ****`),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c="",l=Date.now();try{if(t==null||t({type:"info:memoNodeRunner",content:"Starting memo node execution"}),((p=s==null?void 0:s.context)==null?void 0:p[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,c);return}if(!o.env||!o.ctx){t==null||t({type:"error:memoNodeRunner",content:"Missing env or ctx"}),n==null||n(e.id,c);return}if(!e.data.rag_id){t==null||t({type:"error:memoNodeRunner",content:"Missing rag_id"}),n==null||n(e.id,c);return}let f=((d=s==null?void 0:s.context)==null?void 0:d[e.data.query_key])||"";t==null||t({type:"info:memoNodeRunner",content:`Query text: ${f}`}),t==null||t({type:"info:memoNodeRunner",content:"Generating embedding for query"});let a=await Dt(o,f,!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],h=[];for(let x of g){t==null||t({type:"info:memoNodeRunner",content:`Executing RAG query with namespace: ${x}`});let I=await o.env[`VDB_${(m=s.flowData)==null?void 0:m.tenant}_1024`].query(a.data[0],{namespace:x,topK:e.data.topk,returnMetadata:"all"});t==null||t({type:"info:memoNodeRunner",content:`RAG query completed for namespace ${x}, matches: ${((u=I.matches)==null?void 0:u.length)||0}`}),Array.isArray(I.matches)&&h.push(...I.matches)}let w=Date.now()-l;c=h.map(x=>{var I;return(I=x.metadata)==null?void 0:I.value}).filter(x=>typeof x=="string").join(`
|
|
35
35
|
|
|
36
|
-
`),i==null||i({type:"memo_search",payload:{nodeId:e.id,searchLatencyMs:
|
|
37
|
-
${
|
|
36
|
+
`),i==null||i({type:"memo_search",payload:{nodeId:e.id,searchLatencyMs:w,retrievedContext:c}}),t==null||t({type:"info:memoNodeRunner",content:`Context retrieval complete, length: ${c.length}, preview: ${c.substring(0,200)}...`}),t==null||t({type:"info:memoNodeRunner",content:"Memo node execution completed successfully"})}catch(f){console.error("Error processing MemoNode:",f),t==null||t({type:"error:memoNodeRunner",content:`Memo node execution failed: ${f}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(f)}})}finally{n==null||n(e.id,c),t==null||t({type:"info:memoNodeRunner",content:`onResult called with context length: ${c.length}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}}async function Mt(o,e,s,t,n,r,i){var d,m,u,f,a,g,h;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:(d=s==null?void 0:s.context)==null?void 0:d.user_input}});let c=((m=e.data)==null?void 0:m.allow_images)!==!1,l=((u=e.data)==null?void 0:u.allow_documents)!==!1;!c&&(s!=null&&s.context)&&(s.context.user_images=[],r==null||r({...s})),!l&&(s!=null&&s.context)&&(s.context.files="",r==null||r({...s}));let p={};for(let w of B(e.data))p[w.name]=(f=s==null?void 0:s.context)==null?void 0:f[w.name];n==null||n(e.id,{...p,user_input:(a=s==null?void 0:s.context)==null?void 0:a.user_input,images:c?(g=s==null?void 0:s.context)==null?void 0:g.user_images:[],files:l?(h=s==null?void 0:s.context)==null?void 0:h.files:""}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}function Te(o,e,s){let t=e;async function n(l){let p=l;for(t.executedNodes=t.executedNodes||[],t.context=t.context||{},t.results=t.results||{};p&&p.id;)await r(p),p=ro(p,t.flowData,t)}async function r(l){var f;let p=c[l.type];if(!p){(f=s==null?void 0:s.onError)==null||f.call(s,`Unknown node type: ${l.type}`);return}let d=a=>{var g;return(g=s==null?void 0:s.onServerEvent)==null?void 0:g.call(s,{...a,ts:Date.now()})},m=a=>{var g,h;if((g=s==null?void 0:s.onTelemetry)==null||g.call(s,a),a.type==="llm_telemetry"||a.type==="class_telemetry"){let w=(h=a.payload)==null?void 0:h.usage;w&&(t.tokenUsage=t.tokenUsage||{promptTokens:0,completionTokens:0,totalTokens:0},t.tokenUsage.promptTokens+=w.promptTokens||0,t.tokenUsage.completionTokens+=w.completionTokens||0,t.tokenUsage.totalTokens+=w.totalTokens||0)}};return await p(o,l,t,d,(a,g)=>{t.results[a]=g},s==null?void 0:s.onChangeState,m)}let i=async l=>{var u,f,a,g,h,w;let p=Date.now(),d="completed",m;try{let y=typeof l=="string"?nt(l):l,R=(y==null?void 0:y.text)||"",x=(y==null?void 0:y.images)||[],I=(y==null?void 0:y.documents)||[],M=await ye(I,o.env),_=M.length>0?M.map(F=>`--- file: ${F.name} ---
|
|
37
|
+
${F.text}`).join(`
|
|
38
38
|
|
|
39
|
-
`):"";t.context={user_input:x,user_images:I,files:O},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},(c=s==null?void 0:s.onServerEvent)==null||c.call(s,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:k,error:b}=oo(t.flowData);if(!k)l="failed",m=b||"Flow Format Error",(u=s==null?void 0:s.onError)==null||u.call(s,m);else{let M=B(k.data),{values:F,errors:A}=Ut(M,g==null?void 0:g.inputs);if(A.length>0)return l="failed",m=`Invalid flow inputs: ${A.join("; ")}`,(a=s==null?void 0:s.onError)==null||a.call(s,m),{status:l,error:m};t.context={...t.context,inputs:F,...F},t.context.user_input||(t.context.user_input=x),await n(k),(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(g){l="failed",m=g instanceof Error?g.message:"Agent execution failed",(w=s==null?void 0:s.onError)==null||w.call(s,m)}finally{(h=s==null?void 0:s.onServerEvent)==null||h.call(s,{type:"agent:complete",content:{status:l,durationMs:Date.now()-p},timestamp:Date.now()})}return{status:l,error:m}},f={startNode:Ft,classifierNode:At,llmNode:Ot,memoNode:$t,answerNode:Tt,apiNode:Ct};return i}function oo(o){var l;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 f=xe(t.id,r),d=new Set;for(let m of n){let c=xe(m.id,i);for(let u of c)d.add(u)}let p=[];for(let m of f)if(!d.has(m)){let c=e.nodes.find(u=>u.id===m);if(c){let u=((l=c.data)==null?void 0:l.label)||"";p.push(`${m}(${u},${c.type})`)}}return p.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${p.join(", ")}`}:{startNode:t}}function xe(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 so(o,e){var s;return((s=o.state)==null?void 0:s.nodes.find(t=>t.id===e))||null}function no(o,e,s){var f;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"&&((f=s==null?void 0:s.context)!=null&&f.classified_id)){let d=s.context.classified_id,p=n.find(l=>l.sourceHandle===`source-${d}`);p?r=p.target:console.log(`No matching edge, falling back to first: ${r}`)}return so(e,r)}async function Ie(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}},f=r==null?void 0:r.stateVersion,d=typeof f=="number"&&f!==((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 Te(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 Ne=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 tt(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,p=await z(t,e),l=(i=o.state)==null?void 0:i.user,m={flowData:{...p,tenant:d,flowId:t,chatId:n},executedNodes:[],context:l?{user:l}:{}};return o.setState({...o.state,engineState:m}),m}catch(f){return console.error("Failed to initialize engine state:",f),null}}async function et(o){var O,k,b,M,F;let{agent:e,env:s,ctx:t,payload:n,connection:r}=o,i=Date.now(),f=[],d=async()=>await J(e),p=async A=>{await oe(e,A)},l=async A=>{if(e.state.modelsCache&&e.state.modelsCache[A])return e.state.modelsCache[A];try{let{fetchOraModel:N}=await import("./oraApi-YIJGMXX7.js"),L=await N(A,s);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[A]:L}}),L}catch(N){throw console.error(`Error fetching model ${A}:`,N),N}},m={id:ro(),role:"user",type:"text",content:n.text,images:n.images,ts:Date.now()};await p(m);let c={onChangeState:A=>{e.setState({...e.state,engineState:A})},onServerEvent:async A=>{var N;await((N=o.onServerEvent)==null?void 0:N.call(o,A)),f.push(A)},onTelemetry:async A=>{var N,L,U,q,Q,Z;await Ne({...A,userId:o.resolveUserId(),tenant:((L=(N=e.state.engineState)==null?void 0:N.flowData)==null?void 0:L.tenant)||"",flowId:((q=(U=e.state.engineState)==null?void 0:U.flowData)==null?void 0:q.flowId)||"",sessionId:((Z=(Q=e.state.engineState)==null?void 0:Q.flowData)==null?void 0:Z.chatId)||""},s)},onError:A=>{var N;(N=o.onError)==null||N.call(o,A),e.setState({...e.state,error:A})}},u=e.state.engineState?{...e.state.engineState}:null;if(u){let{engineState:A,refreshed:N}=await Ie(s,u);u=A,N&&e.setState({...e.state,engineState:u,modelsCache:{}})}else if(u=await tt(e,s),!u){let A="Failed to initialize agent";return c.onError(A),{status:"failed",error:A}}let a=o.secrets;if(!a||Object.keys(a).length===0){let A=(O=u.flowData)==null?void 0:O.tenant;a=A?await yt(s,A):{},(k=o.onSecretsLoaded)==null||k.call(o,a)}let y=o.user??e.state.user??void 0;y&&!((b=u.context)!=null&&b.user)&&(u.context={...u.context||{},user:y});let w=it(v(u)),h=typeof u.cycle=="number"?u.cycle:0;w.enabled&&(h=await fe(e,u),u.cycle=h,e.setState({...e.state,engineState:u}));let g=pe(e,{env:s,ctx:t,conn:r,getMessages:d,setMessages:p,getOraModel:l,secrets:a,userAuth:o.userAuth,user:y,composioSessions:o.composioSessions,publicOrigin:o.publicOrigin,skillRefCache:o.skillRefCache},u,h,o.onMemoryRef),x=await Re(g,u,c)(n),{tenant:I,flowId:R,chatId:$}=u.flowData??{};return I&&R&&$&&t.waitUntil(Te(s,{id:`${R}::${$}`,tenant:I,flowId:R,sessionId:$,userId:o.resolveUserId(),title:(M=n.text)==null?void 0:M.slice(0,120),turnTs:i,events:f})),x.status==="completed"&&((F=g.memoryConfig)!=null&&F.enabled)&&g.memoryConfig.mode==="summarize"&&t&&t.waitUntil(Gt(e,g,h)),e.setState({...e.state,lastUpdated:new Date}),{status:x.status,error:x.error,engineState:u}}import{nanoid as io}from"nanoid";function ao(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"?S(s.email):null;return t?{...s,email:t}:null}catch{return null}}async function Ce(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 f=typeof r.userId=="string"?S(r.userId):null,d=ao(e),p=d==null?void 0:d.email;d?o.setState({...o.state,user:d,injectedUserId:p}):f&&!((n=o.state.user)!=null&&n.email)&&o.setState({...o.state,injectedUserId:f});let l=()=>p??f??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 tt(o,s))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let c=p?`run-${io(12)}`:null;c&&await o.registerManualRun(c,i,p);let u=await et({agent:o,env:s,ctx:t,payload:{text:i,inputs:m},skillRefCache:o.skillRefCache,user:d??void 0,resolveUserId:l});if(c&&t.waitUntil(o.completeManualRun(c,u.status==="completed"?"succeeded":"failed",u.error)),u.status==="failed")return new Response(JSON.stringify({error:u.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});let y=(await J(o)).reverse().find(w=>w.role==="assistant");return new Response(JSON.stringify({answer:(y==null?void 0:y.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 Ae(o){try{return await dt(o),await pt(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 _e="trigger:nonce:",uo=900*1e3,Oe=class extends co{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 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 J(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 ut(this);return new Response(JSON.stringify({entries:r}),{headers:t})}return e.method==="POST"&&s.pathname.endsWith("/message")?Ce(this,e,this.env,this.ctx):e.method==="DELETE"&&s.pathname.endsWith("/clear")?Ae(this):new Response("Ready to assist.")}async onConnect(e,s){var c,u,a,y,w;let[t,n]=e.server.split("::"),i=(c=(await V(t,this.env)).metadata)==null?void 0:c.tenant;this.secrets=await yt(this.env,i),this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let f=null;if(s.request){try{this.publicOrigin=new URL(s.request.url).origin}catch{}let h=s.request.headers.get("X-User-Payload");if(h)try{f=JSON.parse(h)}catch(g){console.warn("Failed to parse X-User-Payload",g)}}let d=await z(t,this.env);this.setState({...this.state,user:f||null,sessionId:n,engineState:{flowData:{...d,tenant:i,flowId:t,chatId:n},executedNodes:[],context:f?{user:f}:{}}}),f||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let p=await J(this);D(e,P.SERVER_HISTORY,JSON.stringify({messages:p}));let m=(((u=d==null?void 0:d.state)==null?void 0:u.nodes)??(d==null?void 0:d.nodes)??[]).find(h=>h.type==="startNode");if(m){let h={allow_images:((a=m.data)==null?void 0:a.allow_images)??!1,allow_documents:((y=m.data)==null?void 0:y.allow_documents)??!1,greeting:(w=m.data)==null?void 0:w.greeting};D(e,P.SERVER_CONFIG,JSON.stringify(h))}}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 f={[P.USER_MESSAGE]:d=>this.onUserMessage(e,d),[P.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[P.USER_AUTH]:d=>this.onUserAuth(e,d),[P.USER_IDENTITY]:d=>this.onUserIdentity(e,d)}[n];f&&await f(r)}async onUserMessage(e,s){let t=nt(s),n=this.hasAuditableUser()?`run-${lo(12)}`:null;n&&await this.registerManualRun(n,t.text);let r=await et({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(),onServerEvent:i=>{D(e,P.SERVER_EVENT,JSON.stringify(i))},onError:i=>{D(e,P.SERVER_ERROR,i)},onMemoryRef:i=>{D(e,P.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":"failed",r.error))}hasAuditableUser(e){var s;return!!(e||(s=this.state.user)!=null&&s.email)}registerManualRun(e,s,t){var d,p;let{tenant:n,flowId:r,chatId:i}=((d=this.state.engineState)==null?void 0:d.flowData)??{},f=t||((p=this.state.user)==null?void 0:p.email);return!n||!r||!i||!f?Promise.resolve():de(this.env,{id:e,tenant:n,flowId:r,userId:f,sessionId:i,label:s==null?void 0:s.slice(0,120)})}completeManualRun(e,s,t){return gt(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=`${_e}${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:_e})).entries()].filter(([,i])=>t-i>uo).map(([i])=>i);return r.length>0&&await this.ctx.storage.delete(r),!0}async processTrigger(e){if(!(await le(this.env,e.runId)).claimed){console.warn(`[AgentDO] activation ${e.activationId} skipped \u2014 run ${e.runId} already claimed`);return}try{this.state.engineState||await tt(this,this.env);let t=B(v(this.state.engineState)),n=Dt(t,e.inputs||{},e.label),r=await et({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(),onSecretsLoaded:i=>{this.secrets=i}});await gt(this.env,e.runId,{status:r.status==="completed"?"succeeded":"failed",error:r.error})}catch(t){let n=t instanceof Error?t.message:"Trigger execution failed";throw await gt(this.env,e.runId,{status:"failed",error:n}),t}}async onUserIdentity(e,s){let t=S(s);if(!t){D(e,P.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:t}),D(e,P.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,s){let t=bt(s);if(!t){D(e,P.SERVER_ERROR,"Invalid auth payload");return}let n=t.value.trim();n===""?delete this.userAuth[t.name]:this.userAuth[t.name]=t.value,D(e,P.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:t.name,set:n!==""}}))}async onClearHistory(e){await dt(this),await pt(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&&D(e,P.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await ce(this);let e=await J(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 vn(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 fo,jwtVerify as po}from"jose";function $e(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 mo(o){return(typeof o.email=="string"?o.email.trim():"")||null}async function X(o,e,s){let t=$e(o.headers.get("cookie")),n=new URL(o.url),r=t.access_token||n.searchParams.get("access_token"),i=await go(e,r);if(i.ok){let f=i.payload,d=mo(f);return d?{id:f.sub,email:d,name:f.name,first_name:f.given_name,last_name:f.family_name,tenant:f.tenant,roles:f["ora-roles"],db_name:f.db_name||null,user_id:f.user_id||null}:null}return null}async function go(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:R,user_images:x,files:_},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},(u=s==null?void 0:s.onServerEvent)==null||u.call(s,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:P,error:b}=so(t.flowData);if(!P)d="failed",m=b||"Flow Format Error",(f=s==null?void 0:s.onError)==null||f.call(s,m);else{let F=B(P.data),{values:$,errors:A}=Ut(F,y==null?void 0:y.inputs);if(A.length>0)return d="failed",m=`Invalid flow inputs: ${A.join("; ")}`,(a=s==null?void 0:s.onError)==null||a.call(s,m),{status:d,error:m};t.context={...t.context,inputs:$,...$},t.context.user_input||(t.context.user_input=R),await n(P),(g=s==null?void 0:s.onServerEvent)==null||g.call(s,{type:"agent:telemetry",content:{durationMs:Date.now()-p,tokenUsage:t.tokenUsage},timestamp:Date.now()})}}catch(y){d="failed",m=y instanceof Error?y.message:"Agent execution failed",(h=s==null?void 0:s.onError)==null||h.call(s,m)}finally{(w=s==null?void 0:s.onServerEvent)==null||w.call(s,{type:"agent:complete",content:{status:d,durationMs:Date.now()-p},timestamp:Date.now()})}return{status:d,error:m}},c={startNode:Mt,classifierNode:At,llmNode:Ot,memoNode:$t,answerNode:Tt,apiNode:Ct};return i}function so(o){var d;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 c=Ie(t.id,r),l=new Set;for(let m of n){let u=Ie(m.id,i);for(let f of u)l.add(f)}let p=[];for(let m of c)if(!l.has(m)){let u=e.nodes.find(f=>f.id===m);if(u){let f=((d=u.data)==null?void 0:d.label)||"";p.push(`${m}(${f},${u.type})`)}}return p.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${p.join(", ")}`}:{startNode:t}}function Ie(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 no(o,e){var s;return((s=o.state)==null?void 0:s.nodes.find(t=>t.id===e))||null}function ro(o,e,s){var c;let t=e==null?void 0:e.state;if(!t)return null;let n=t.edges.filter(l=>l.source===o.id);if(n.length===0)return null;let r=n[0].target;if(o.type==="classifierNode"&&((c=s==null?void 0:s.context)!=null&&c.classified_id)){let l=s.context.classified_id,p=n.find(d=>d.sourceHandle===`source-${l}`);p?r=p.target:console.log(`No matching edge, falling back to first: ${r}`)}return no(e,r)}async function Ne(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}},c=r==null?void 0:r.stateVersion,l=typeof c=="number"&&c!==((n=e.flowData)==null?void 0:n.stateVersion);return{engineState:i,refreshed:l}}catch(r){return console.error(`[flowRefresh] fetch failed for flow ${s}:`,r),{engineState:e,refreshed:!1}}}function Ce(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 Ae=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 tt(o,e){var r,i;let s=o.id||o.name||"",[t,n]=String(s).split("::");if(!t||!n)return null;try{let l=(r=(await X(t,e)).metadata)==null?void 0:r.tenant,p=await W(t,e),d=(i=o.state)==null?void 0:i.user,m={flowData:{...p,tenant:l,flowId:t,chatId:n},executedNodes:[],context:d?{user:d}:{}};return o.setState({...o.state,engineState:m}),m}catch(c){return console.error("Failed to initialize engine state:",c),null}}async function et(o){var _,P,b,F,$;let{agent:e,env:s,ctx:t,payload:n,connection:r}=o,i=Date.now(),c=[],l=async()=>await V(e),p=async A=>{await se(e,A)},d=async A=>{if(e.state.modelsCache&&e.state.modelsCache[A])return e.state.modelsCache[A];try{let{fetchOraModel:N}=await import("./oraApi-YIJGMXX7.js"),L=await N(A,s);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[A]:L}}),L}catch(N){throw console.error(`Error fetching model ${A}:`,N),N}},m={id:io(),role:"user",type:"text",content:n.text,images:n.images,ts:Date.now()};await p(m);let u={onChangeState:A=>{e.setState({...e.state,engineState:A})},onServerEvent:async A=>{var N;await((N=o.onServerEvent)==null?void 0:N.call(o,A)),c.push(A)},onTelemetry:async A=>{var N,L,D,K,S,Q;await Ae({...A,userId:o.resolveUserId(),tenant:((L=(N=e.state.engineState)==null?void 0:N.flowData)==null?void 0:L.tenant)||"",flowId:((K=(D=e.state.engineState)==null?void 0:D.flowData)==null?void 0:K.flowId)||"",sessionId:((Q=(S=e.state.engineState)==null?void 0:S.flowData)==null?void 0:Q.chatId)||""},s)},onError:A=>{var N;(N=o.onError)==null||N.call(o,A),e.setState({...e.state,error:A})}},f=e.state.engineState?{...e.state.engineState}:null;if(f){let{engineState:A,refreshed:N}=await Ne(s,f);f=A,N&&e.setState({...e.state,engineState:f,modelsCache:{}})}else if(f=await tt(e,s),!f){let A="Failed to initialize agent";return u.onError(A),{status:"failed",error:A}}let a=o.secrets;if(!a||Object.keys(a).length===0){let A=(_=f.flowData)==null?void 0:_.tenant;a=A?await yt(s,A):{},(P=o.onSecretsLoaded)==null||P.call(o,a)}let g=o.user??e.state.user??void 0;g&&!((b=f.context)!=null&&b.user)&&(f.context={...f.context||{},user:g});let h=it(v(f)),w=typeof f.cycle=="number"?f.cycle:0;h.enabled&&(w=await me(e,f),f.cycle=w,e.setState({...e.state,engineState:f}));let y=ge(e,{env:s,ctx:t,conn:r,getMessages:l,setMessages:p,getOraModel:d,secrets:a,userAuth:o.userAuth,user:g,composioSessions:o.composioSessions,publicOrigin:o.publicOrigin,skillRefCache:o.skillRefCache},f,w,o.onMemoryRef),R=await Te(y,f,u)(n),{tenant:x,flowId:I,chatId:M}=f.flowData??{};return x&&I&&M&&t.waitUntil(Ce(s,{id:`${I}::${M}`,tenant:x,flowId:I,sessionId:M,userId:o.resolveUserId(),title:(F=n.text)==null?void 0:F.slice(0,120),turnTs:i,events:c})),R.status==="completed"&&(($=y.memoryConfig)!=null&&$.enabled)&&y.memoryConfig.mode==="summarize"&&t&&t.waitUntil(zt(e,y,w)),e.setState({...e.state,lastUpdated:new Date}),{status:R.status,error:R.error,engineState:f}}import{nanoid as ao}from"nanoid";function co(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 c=typeof r.userId=="string"?Z(r.userId):null,l=co(e),p=l==null?void 0:l.email;l?o.setState({...o.state,user:l,injectedUserId:p}):c&&!((n=o.state.user)!=null&&n.email)&&o.setState({...o.state,injectedUserId:c});let d=()=>p??c??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 tt(o,s))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let u=p?`run-${ao(12)}`:null;u&&await o.registerManualRun(u,i,p);let f=await et({agent:o,env:s,ctx:t,payload:{text:i,inputs:m},skillRefCache:o.skillRefCache,user:l??void 0,resolveUserId:d});if(u&&t.waitUntil(o.completeManualRun(u,f.status==="completed"?"succeeded":"failed",f.error)),f.status==="failed")return new Response(JSON.stringify({error:f.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});let g=(await V(o)).reverse().find(h=>h.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 Oe(o){try{return await dt(o),await pt(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 $e="trigger:nonce:",fo=900*1e3,Me=class extends lo{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 re(this)}}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 ut(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")?Oe(this):new Response("Ready to assist.")}async onConnect(e,s){var u,f,a,g,h;let[t,n]=e.server.split("::"),i=(u=(await X(t,this.env)).metadata)==null?void 0:u.tenant;this.secrets=await yt(this.env,i),this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let c=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{c=JSON.parse(w)}catch(y){console.warn("Failed to parse X-User-Payload",y)}}let l=await W(t,this.env);this.setState({...this.state,user:c||null,sessionId:n,engineState:{flowData:{...l,tenant:i,flowId:t,chatId:n},executedNodes:[],context:c?{user:c}:{}}}),c||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let p=await V(this);U(e,k.SERVER_HISTORY,JSON.stringify({messages:p}));let m=(((f=l==null?void 0:l.state)==null?void 0:f.nodes)??(l==null?void 0:l.nodes)??[]).find(w=>w.type==="startNode");if(m){let w={allow_images:((a=m.data)==null?void 0:a.allow_images)??!1,allow_documents:((g=m.data)==null?void 0:g.allow_documents)??!1,greeting:(h=m.data)==null?void 0:h.greeting};U(e,k.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 c={[k.USER_MESSAGE]:l=>this.onUserMessage(e,l),[k.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[k.USER_AUTH]:l=>this.onUserAuth(e,l),[k.USER_IDENTITY]:l=>this.onUserIdentity(e,l)}[n];c&&await c(r)}async onUserMessage(e,s){let t=nt(s),n=this.hasAuditableUser()?`run-${uo(12)}`:null;n&&await this.registerManualRun(n,t.text);let r=await et({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(),onServerEvent:i=>{U(e,k.SERVER_EVENT,JSON.stringify(i))},onError:i=>{U(e,k.SERVER_ERROR,i)},onMemoryRef:i=>{U(e,k.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":"failed",r.error))}hasAuditableUser(e){var s;return!!(e||(s=this.state.user)!=null&&s.email)}registerManualRun(e,s,t){var l,p;let{tenant:n,flowId:r,chatId:i}=((l=this.state.engineState)==null?void 0:l.flowData)??{},c=t||((p=this.state.user)==null?void 0:p.email);return!n||!r||!i||!c?Promise.resolve():fe(this.env,{id:e,tenant:n,flowId:r,userId:c,sessionId:i,label:s==null?void 0:s.slice(0,120)})}completeManualRun(e,s,t){return gt(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=`${$e}${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:$e})).entries()].filter(([,i])=>t-i>fo).map(([i])=>i);return r.length>0&&await this.ctx.storage.delete(r),!0}async processTrigger(e){if(!(await ue(this.env,e.runId)).claimed){console.warn(`[AgentDO] activation ${e.activationId} skipped \u2014 run ${e.runId} already claimed`);return}try{this.state.engineState||await tt(this,this.env);let t=B(v(this.state.engineState)),n=bt(t,e.inputs||{},e.label),r=await et({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(),onSecretsLoaded:i=>{this.secrets=i}});await gt(this.env,e.runId,{status:r.status==="completed"?"succeeded":"failed",error:r.error})}catch(t){let n=t instanceof Error?t.message:"Trigger execution failed";throw await gt(this.env,e.runId,{status:"failed",error:n}),t}}async onUserIdentity(e,s){let t=Z(s);if(!t){U(e,k.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:t}),U(e,k.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,s){let t=Lt(s);if(!t){U(e,k.SERVER_ERROR,"Invalid auth payload");return}let n=t.value.trim();n===""?delete this.userAuth[t.name]:this.userAuth[t.name]=t.value,U(e,k.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:t.name,set:n!==""}}))}async onClearHistory(e){await dt(this),await pt(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&&U(e,k.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await de(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 or(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 po,jwtVerify as mo}from"jose";function Fe(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 go(o){return(typeof o.email=="string"?o.email.trim():"")||null}async function J(o,e,s){let t=Fe(o.headers.get("cookie")),n=new URL(o.url),r=t.access_token||n.searchParams.get("access_token"),i=await yo(e,r);if(i.ok){let c=i.payload,l=go(c);return l?{id:c.sub,email:l,name:c.name,first_name:c.given_name,last_name:c.family_name,tenant:c.tenant,roles:c["ora-roles"],db_name:c.db_name||null,user_id:c.user_id||null}:null}return null}async function yo(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 Le(o,e){let s=await crypto.subtle.importKey("raw",Me.encode(o),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return ho(await crypto.subtle.sign("HMAC",s,Me.encode(e)))}function xo(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 ur(o){let e=String(o.timestamp??Math.floor(Date.now()/1e3)),s=await Le(o.secret,be({timestamp:e,nonce:o.nonce,tenant:o.tenant,destination:o.destination,body:o.body}));return{"content-type":"application/json",[De]:o.tenant,[Pe]:e,[Ue]:o.nonce,[ke]:`v1=${s}`}}async function je(o){var p,l,m,c,u;if(!((p=o.secret)!=null&&p.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(l=o.headers.get(De))==null?void 0:l.trim(),s=(m=o.headers.get(Pe))==null?void 0:m.trim(),t=(c=o.headers.get(Ue))==null?void 0:c.trim(),n=(u=o.headers.get(ke))==null?void 0:u.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),f=o.toleranceSeconds??300;if(Math.abs(i-r)>f)return{ok:!1,error:"stale timestamp"};let d=await Le(o.secret.trim(),be({timestamp:s,nonce:t,tenant:e,destination:o.url,body:o.body}));return xo(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 Ee(o,e,s){var p;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 je({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 f;try{f=await V(i.flowId,e)}catch{return K({error:"Flow not found"},404)}if(!((p=f==null?void 0:f.metadata)!=null&&p.tenant)||f.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 Fe(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 Ro=/^[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}$/;async function Ir(o,e,s){var r,i,f,d;let t=new URL(o.url),n=await Ee(o,e,s);if(n instanceof Response)return n;if(t.pathname.startsWith("/a/")){let p=t.pathname.split("/"),l=p[2],m=p[3];try{if(!l)return Response.redirect(new URL("/",t.origin).toString(),302);let c;try{c=await V(l,e)}catch{return new Response("Flow not found",{status:404})}if(!c.metadata||((r=c.metadata)==null?void 0:r.status)!=="active")return new Response("NO chat",{status:404});if(((i=c.metadata)==null?void 0:i.visibility)==="private"&&!await X(o,e,s)){let a=new URL("/login",t.origin);return a.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(a.toString(),302)}if(!m){let u=crypto.randomUUID(),a=new URL(`/a/${l}/${u}`,t.origin);return Response.redirect(a.toString(),302)}if(!Ro.test(m))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 p=t.pathname.split("/"),l=p[4],m=p[5],c=`${l}::${m}`;try{let u=await X(o,e,s);if(!u){let g=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${g}) \u2014 Composio connections from tool editor will not apply`)}let a=new Headers(o.headers);a.delete("X-User-Payload"),u&&a.set("X-User-Payload",JSON.stringify(u));let y=new Request(o,{headers:a});return(await He(e.AGENT,c)).fetch(y)}catch(u){return console.error("Error accessing agent:",u),new Response("Agent error",{status:500})}}if(t.pathname.startsWith("/api/ora/connect")){let p=t.pathname.split("/"),l=p[4],m=p[5];if(!l||!m)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 u=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${l}`,y=await(await fetch(u,{method:"GET",headers:{Authorization:c}})).json();if(((f=y.payload)==null?void 0:f.flowId)!==l)return console.error("FlowId mismatch:",(d=y.payload)==null?void 0:d.flowId,"!==",l),new Response("Validation error",{status:403});let w=`${l}::${m}`,h=await X(o,e,s);if(!h){let $=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${$}) \u2014 Composio connections from tool editor will not apply`)}let g=new Headers(o.headers);g.delete("X-User-Payload"),h&&g.set("X-User-Payload",JSON.stringify(h));let x=new Request(o,{headers:g});return(await He(e.AGENT,w)).fetch(x)}catch(u){return console.error("Error in /api/ora/connect:",u),new Response("Internal error",{status:500})}}}async function Cr(o,e,s){let t=new URL(o.url),n=o.method;if(!t.pathname.startsWith("/api/instances"))return;let r=await X(o,e,s);if(!r)return new Response("Unauthorized",{status:401});let i=e.HX_CORE_URL,f=e.HX_API_KEY;if(!i||!f)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let p=t.pathname.slice("/api/instances".length);p.startsWith("/")&&(p=p.slice(1)),p.endsWith("/")&&(p=p.slice(0,-1));let l="/ora/instances";p&&(l+=`/${p}`);let m=i.endsWith("/")?i.slice(0,-1):i,c=new URL(`${m}${l}`);t.searchParams.forEach((y,w)=>{c.searchParams.set(w,y)}),n==="GET"&&!p&&c.searchParams.set("filter_user_id",r.email);let u=new Headers;u.set("Authorization",f),u.set("Content-Type","application/json"),u.set("X-User-Payload",JSON.stringify(r));let a={method:n,headers:u};if(["POST","PATCH","PUT"].includes(n))try{a.body=await o.text()}catch(y){console.error("Error reading request body:",y)}try{let y=await fetch(c.toString(),a),w=await y.text();return new Response(w,{status:y.status,headers:{"Content-Type":"application/json"}})}catch(y){return console.error("Error proxying to flow instance backend:",y),new Response("Internal Server Error",{status:500})}}async function Or(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"),f=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 p=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(!p.ok)return new Response("Unauthorized",{status:401});let l=await p.json(),m=new Response(null,{status:302,headers:{Location:f}}),c=(u,a,y)=>{m.headers.append("Set-Cookie",`${u}=${a}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${y}`)};return l.access_token&&c("access_token",l.access_token,l.expires_in),l.refresh_token&&c("refresh_token",l.refresh_token,l.refresh_expires_in||3600*24*30),l.id_token&&c("id_token",l.id_token,l.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 X(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{Oe as AgentDO,$o as FLOW_INPUT_NAME_RE,Mo as GENERATION_PARAM_KEYS,Po as GENERATION_PRESETS,Fo as MAX_USER_IDENTITY_LENGTH,Bo as MODEL_REGISTRY_SNAPSHOT,Y as NodeType,ko as PRESET_PARAM_KEYS,Vo as REASONING_EFFORT_LEVELS,Bt as TOOL_REGISTRY_SNAPSHOT,Ue as TRIGGER_NONCE_HEADER,ke as TRIGGER_SIGNATURE_HEADER,dr as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,De as TRIGGER_TENANT_HEADER,Pe as TRIGGER_TIMESTAMP_HEADER,bo as applyPresetToOverrides,qt as buildReasoningProviderOptions,ur as buildSignedTriggerHeaders,Dt as buildTriggerMessageText,Co as buildUrl,mo as canonicalUserEmail,le as claimRun,pt as clearAllContext,dt as clearAllMessages,gt as completeRun,Io as convertTempMessure,Rt as createRun,ie as deleteContextToolsUpToCycle,Uo as deriveParamSupport,Fe as dispatchTrigger,Pt as embedText,ce as ensureAgentTables,Je as ensureContextTable,Ve as ensureMessagesTable,J as getAllMessages,ft as getContext,ne as getContextData,ut as getContextIndex,Yo as getDefaultOutVars,at as getEffectiveOutVars,B as getFlowInputDefs,ae as getMaxContextCycle,Qo as getModelEntry,Ir as handleAgentsRoutes,Or as handleAuthRoutes,rr as handleCommonRoutes,Cr as handleIntancesRoutes,Ee as handleTriggerRoutes,_o as hashText,tt as initializeEngineState,Zt as jsonSchemaToZod,st as logc,P as messageTypes,wo as normalizeDestination,Lo as normalizeEffectiveParams,Ut as normalizeFlowInputs,Go as normalizeModelEntry,Jo as normalizeReasoning,Eo as openAiReasoningParamSupport,jo as openAiStandardParamSupport,$e as parseCookies,bt as parseUserAuth,nt as parseUserMessage,Lt as pickNodeOverrides,Xo as reasoningEffortLevels,Et as reasoningExposable,de as recordRun,Wo as registerProvider,re as resolveContextRef,rt as resolveModelById,ct as resolveOutVarRef,Do as resolvePreset,Ht as resolveReasoningEffort,zt as resolveTemplate,et as runAgentTurn,No as safeParseJSON,S as sanitizeUserIdentity,Ne as sendEvent,D as serverSend,se as setContext,oe as setMessage,Le as signTriggerMaterial,Re as startEngine,Ko as stripUnsupportedFromNodeData,To as tempTool,xo as timingSafeEqualHex,jt as toStreamTextSettings,be as triggerSignatureMaterial,Ao as twitter,vn as validateFlowStart,Oo as vectorize,go as verifyToken,je as verifyTriggerRequest,X as verifyUser,zo as walkPath,qo as workersAiParamSupport,Ho as xaiParamSupport};
|
|
41
|
+
-----END PUBLIC KEY-----`,t=await po(s,"RS256");try{let{payload:n,protectedHeader:r}=await mo(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 cr(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 Ft}from"agents";import{getAgentByName as ho}from"agents";async function Pe(o,e){let s=e.sessionId||e.runAsUserId,t=e.inputs||{},n=e.runId;if(!n){let l=await xt(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(!l)return{status:"error",error:"Failed to register run"};if(!l.created&&l.run.status!=="queued")return{status:"deduped",runId:l.run.id};n=l.run.id}let r={...e,sessionId:s,runId:n,inputs:t},c=await(await ho(o.AGENT,`${e.flowId}::${s}`)).enqueueTrigger(r);return c.duplicate?{status:"deduped",runId:n}:c.queued?{status:"queued",runId:n,activation:r,taskId:c.taskId}:{status:"error",error:"Failed to queue trigger"}}var De="x-ora-signature",Ue="x-ora-timestamp",be="x-ora-nonce",Le="x-ora-tenant",pr=300,ke=new TextEncoder;function wo(o){return[...new Uint8Array(o)].map(e=>e.toString(16).padStart(2,"0")).join("")}function Ro(o){try{let e=new URL(o);return`${e.origin}${e.pathname.replace(/\/$/,"")}`}catch{return o.replace(/\/$/,"")}}function je(o){return["v1",o.timestamp,o.nonce,o.tenant,Ro(o.destination),o.body].join(`
|
|
42
|
+
`)}async function Ee(o,e){let s=await crypto.subtle.importKey("raw",ke.encode(o),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return wo(await crypto.subtle.sign("HMAC",s,ke.encode(e)))}function xo(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 mr(o){let e=String(o.timestamp??Math.floor(Date.now()/1e3)),s=await Ee(o.secret,je({timestamp:e,nonce:o.nonce,tenant:o.tenant,destination:o.destination,body:o.body}));return{"content-type":"application/json",[Le]:o.tenant,[Ue]:e,[be]:o.nonce,[De]:`v1=${s}`}}async function He(o){var p,d,m,u,f;if(!((p=o.secret)!=null&&p.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(d=o.headers.get(Le))==null?void 0:d.trim(),s=(m=o.headers.get(Ue))==null?void 0:m.trim(),t=(u=o.headers.get(be))==null?void 0:u.trim(),n=(f=o.headers.get(De))==null?void 0:f.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),c=o.toleranceSeconds??300;if(Math.abs(i-r)>c)return{ok:!1,error:"stale timestamp"};let l=await Ee(o.secret.trim(),je({timestamp:s,nonce:t,tenant:e,destination:o.url,body:o.body}));return xo(n.slice(3),l)?{ok:!0,tenant:e,nonce:t,timestamp:r}:{ok:!1,error:"signature mismatch"}}var q=(o,e=200)=>new Response(JSON.stringify(o),{status:e,headers:{"content-type":"application/json"}});async function Ke(o,e,s){var p;if(new URL(o.url).pathname!=="/api/triggers/dispatch")return;if(o.method!=="POST")return q({error:"Method not allowed"},405);let n=await o.text(),r=await He({secret:e.HX_API_KEY,body:n,url:o.url,headers:o.headers});if(!r.ok)return console.warn(`[triggers] rejected dispatch: ${r.error}`),q({error:"Invalid signature"},401);let i;try{i=JSON.parse(n)}catch{return q({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 q({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(i.tenant!==r.tenant)return q({error:"Tenant mismatch"},403);let c;try{c=await X(i.flowId,e)}catch{return q({error:"Flow not found"},404)}if(!((p=c==null?void 0:c.metadata)!=null&&p.tenant)||c.metadata.tenant!==i.tenant)return console.warn(`[triggers] flow ${i.flowId} does not belong to tenant ${i.tenant}`),q({error:"Tenant mismatch"},403);let l=await Pe(e,{...i,sessionId:i.sessionId||i.runAsUserId,nonce:r.nonce});return l.status==="error"?q({error:l.error},502):l.status==="deduped"?q({deduped:!0,runId:l.runId},200):q({accepted:!0,runId:l.runId,taskId:l.taskId},202)}var Io=/^[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}$/,To=new Set(["state","messages","context"]);async function No(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]||""),c=n[6];if(!r||!i||!c||!To.has(c))return new Response("Not found",{status:404});try{let p=await(await Ft(e.AGENT,`${r}::${i}`)).inspectPersistedSession(c);return Response.json(p)}catch(l){return console.error("[agents] failed to inspect persisted session",l),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function Cr(o,e,s){var i,c,l,p;let t=new URL(o.url),n=await Ke(o,e,s);if(n instanceof Response)return n;let r=await No(o,e);if(r instanceof Response)return r;if(t.pathname.startsWith("/a/")){let d=t.pathname.split("/"),m=d[2],u=d[3];try{if(!m)return Response.redirect(new URL("/",t.origin).toString(),302);let f;try{f=await X(m,e)}catch{return new Response("Flow not found",{status:404})}if(!f.metadata||((i=f.metadata)==null?void 0:i.status)!=="active")return new Response("NO chat",{status:404});if(((c=f.metadata)==null?void 0:c.visibility)==="private"&&!await J(o,e,s)){let g=new URL("/login",t.origin);return g.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(g.toString(),302)}if(!u){let a=crypto.randomUUID(),g=new URL(`/a/${m}/${a}`,t.origin);return Response.redirect(g.toString(),302)}if(!Io.test(u))return new Response("Id del chat no v\xE1lido",{status:400})}catch(f){return console.error("Error accessing flow KV:",f),new Response("Flow error",{status:500})}}if(t.pathname.startsWith("/api/agent/flow")){let d=t.pathname.split("/"),m=d[4],u=d[5],f=`${m}::${u}`;try{let a=await J(o,e,s);if(!a){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 g=new Headers(o.headers);g.delete("X-User-Payload"),a&&g.set("X-User-Payload",JSON.stringify(a));let h=new Request(o,{headers:g});return(await Ft(e.AGENT,f)).fetch(h)}catch(a){return console.error("Error accessing agent:",a),new Response("Agent error",{status:500})}}if(t.pathname.startsWith("/api/ora/connect")){let d=t.pathname.split("/"),m=d[4],u=d[5];if(!m||!u)return new Response("Missing flowId or sessionId",{status:400});let f=o.headers.get("Authorization")||t.searchParams.get("authorization");if(!f)return new Response("Missing Authorization header",{status:401});try{let a=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${m}`,h=await(await fetch(a,{method:"GET",headers:{Authorization:f}})).json();if(((l=h.payload)==null?void 0:l.flowId)!==m)return console.error("FlowId mismatch:",(p=h.payload)==null?void 0:p.flowId,"!==",m),new Response("Validation error",{status:403});let w=`${m}::${u}`,y=await J(o,e,s);if(!y){let _=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${_}) \u2014 Composio connections from tool editor will not apply`)}let R=new Headers(o.headers);R.delete("X-User-Payload"),y&&R.set("X-User-Payload",JSON.stringify(y));let x=new Request(o,{headers:R});return(await Ft(e.AGENT,w)).fetch(x)}catch(a){return console.error("Error in /api/ora/connect:",a),new Response("Internal error",{status:500})}}}async function Or(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,c=e.HX_API_KEY;if(!i||!c)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let p=t.pathname.slice("/api/instances".length);p.startsWith("/")&&(p=p.slice(1)),p.endsWith("/")&&(p=p.slice(0,-1));let d="/ora/instances";p&&(d+=`/${p}`);let m=i.endsWith("/")?i.slice(0,-1):i,u=new URL(`${m}${d}`);t.searchParams.forEach((g,h)=>{u.searchParams.set(h,g)}),n==="GET"&&!p&&u.searchParams.set("filter_user_id",r.email);let f=new Headers;f.set("Authorization",c),f.set("Content-Type","application/json"),f.set("X-User-Payload",JSON.stringify(r));let a={method:n,headers:f};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(u.toString(),a),h=await g.text();return new Response(h,{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 Fr(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"),c=n.get("nextURL")||"/";if(!r||!i)return new Response("Missing username or password",{status:400});let l=new URLSearchParams;l.append("username",r),l.append("password",i),l.append("grant_type","password"),l.append("client_id",e.KC_CLIENT_ID),l.append("client_secret",e.KC_CLIENT_SECRET);let p=await fetch(`${e.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:l});if(!p.ok)return new Response("Unauthorized",{status:401});let d=await p.json(),m=new Response(null,{status:302,headers:{Location:c}}),u=(f,a,g)=>{m.headers.append("Set-Cookie",`${f}=${a}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${g}`)};return d.access_token&&u("access_token",d.access_token,d.expires_in),d.refresh_token&&u("refresh_token",d.refresh_token,d.refresh_expires_in||3600*24*30),d.id_token&&u("id_token",d.id_token,d.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,Po as FLOW_INPUT_NAME_RE,Do as GENERATION_PARAM_KEYS,bo as GENERATION_PRESETS,ko as MAX_USER_IDENTITY_LENGTH,Zo as MODEL_REGISTRY_SNAPSHOT,Y as NodeType,Uo as PRESET_PARAM_KEYS,Go as REASONING_EFFORT_LEVELS,St as TOOL_REGISTRY_SNAPSHOT,be as TRIGGER_NONCE_HEADER,De as TRIGGER_SIGNATURE_HEADER,pr as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,Le as TRIGGER_TENANT_HEADER,Ue as TRIGGER_TIMESTAMP_HEADER,Eo as applyPresetToOverrides,qt as buildReasoningProviderOptions,mr as buildSignedTriggerHeaders,bt as buildTriggerMessageText,Oo as buildUrl,go as canonicalUserEmail,ue as claimRun,pt as clearAllContext,dt as clearAllMessages,gt as completeRun,Co as convertTempMessure,xt as createRun,ce as deleteContextToolsUpToCycle,Lo as deriveParamSupport,Pe as dispatchTrigger,Dt as embedText,de as ensureAgentTables,Je as ensureContextTable,Xe as ensureMessagesTable,re as getAllContext,V as getAllMessages,ft as getContext,ie as getContextData,ut as getContextIndex,Qo as getDefaultOutVars,at as getEffectiveOutVars,B as getFlowInputDefs,le as getMaxContextCycle,vo as getModelEntry,Cr as handleAgentsRoutes,Fr as handleAuthRoutes,cr as handleCommonRoutes,Or as handleIntancesRoutes,No as handlePersistedSessionInspection,Ke as handleTriggerRoutes,Mo as hashText,tt as initializeEngineState,Zt as jsonSchemaToZod,st as logc,k as messageTypes,Ro as normalizeDestination,Ho as normalizeEffectiveParams,Ut as normalizeFlowInputs,Yo as normalizeModelEntry,zo as normalizeReasoning,qo as openAiReasoningParamSupport,Ko as openAiStandardParamSupport,Fe as parseCookies,Lt as parseUserAuth,nt as parseUserMessage,jt as pickNodeOverrides,Wo as reasoningEffortLevels,Ht as reasoningExposable,fe as recordRun,Bo as registerProvider,ae as resolveContextRef,rt as resolveModelById,ct as resolveOutVarRef,jo as resolvePreset,Kt as resolveReasoningEffort,Yt as resolveTemplate,et as runAgentTurn,_o as safeParseJSON,Z as sanitizeUserIdentity,Ae as sendEvent,U as serverSend,ne as setContext,se as setMessage,Ee as signTriggerMaterial,Te as startEngine,Jo as stripUnsupportedFromNodeData,Ao as tempTool,xo as timingSafeEqualHex,Et as toStreamTextSettings,je as triggerSignatureMaterial,$o as twitter,or as validateFlowStart,Fo as vectorize,yo as verifyToken,He as verifyTriggerRequest,J as verifyUser,So as walkPath,Xo as workersAiParamSupport,Vo as xaiParamSupport};
|
|
@@ -47,6 +47,14 @@ export interface State {
|
|
|
47
47
|
error?: string;
|
|
48
48
|
modelsCache?: Record<string, any>;
|
|
49
49
|
}
|
|
50
|
+
export type PersistedSessionSection = 'state' | 'messages' | 'context';
|
|
51
|
+
export type PersistedSessionSectionResult = {
|
|
52
|
+
state: State;
|
|
53
|
+
} | {
|
|
54
|
+
messages: Message[];
|
|
55
|
+
} | {
|
|
56
|
+
context: ContextRow[];
|
|
57
|
+
};
|
|
50
58
|
export declare class AgentDO extends Agent<Env, State> {
|
|
51
59
|
initialState: State;
|
|
52
60
|
/** JWT email wins; explicit client identity is fallback only. */
|
|
@@ -59,6 +67,12 @@ export declare class AgentDO extends Agent<Env, State> {
|
|
|
59
67
|
private skillRefCache;
|
|
60
68
|
/** Public origin from the active socket upgrade (used for OAuth callback URLs). */
|
|
61
69
|
private publicOrigin?;
|
|
70
|
+
/**
|
|
71
|
+
* Internal audit surface used by the tenant runtime. Only functional persisted data is
|
|
72
|
+
* returned: Agents SDK state plus the DO SQLite messages/context tables. Runtime secrets,
|
|
73
|
+
* user-provided credentials, queues and nonce storage are intentionally outside this API.
|
|
74
|
+
*/
|
|
75
|
+
inspectPersistedSession(section: PersistedSessionSection): Promise<PersistedSessionSectionResult>;
|
|
62
76
|
onRequest(request: Request): Promise<Response>;
|
|
63
77
|
onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
|
|
64
78
|
onMessage(connection: Connection, message: WSMessage): Promise<void>;
|
|
@@ -10,6 +10,7 @@ export declare function clearAllMessages(ctx: SqlContext): Promise<void>;
|
|
|
10
10
|
export declare function ensureContextTable(ctx: SqlContext): Promise<void>;
|
|
11
11
|
export declare function setContext(ctx: SqlContext, row: ContextUpsertInput): Promise<void>;
|
|
12
12
|
export declare function getContextIndex(ctx: SqlContext): Promise<ContextIndexEntry[]>;
|
|
13
|
+
export declare function getAllContext(ctx: SqlContext): Promise<ContextRow[]>;
|
|
13
14
|
export declare function getContext(ctx: SqlContext, ref: string): Promise<ContextRow | null>;
|
|
14
15
|
export declare function getContextData(ctx: SqlContext, ref: string): Promise<string | null>;
|
|
15
16
|
/**
|