@hugex/ai 2.8.15 → 2.9.4

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.
Files changed (89) hide show
  1. package/dist/chunk-3TXHFKDN.js +1 -0
  2. package/dist/{chunk-TUI5H3ZB.js → chunk-G3SGJ7XJ.js} +1 -1
  3. package/dist/chunk-R6EKV3WR.js +1 -0
  4. package/dist/{chunk-43NDF544.js → chunk-RYHQGPX5.js} +1 -1
  5. package/dist/client/hooks/useAgent.d.ts +31 -0
  6. package/dist/client/states/agent-store.d.ts +95 -0
  7. package/dist/client.d.ts +4 -129
  8. package/dist/client.js +1 -1
  9. package/dist/common/constants/ai-models.d.ts +10 -0
  10. package/dist/common/constants/tools-registry.d.ts +8 -0
  11. package/dist/common/types/agent-types.d.ts +61 -0
  12. package/dist/common/types/ai-models-types.d.ts +94 -0
  13. package/dist/common/types/memory-types.d.ts +28 -0
  14. package/dist/common/types/node-types.d.ts +9 -0
  15. package/dist/common/types/user-types.d.ts +11 -0
  16. package/dist/common/types/var-mapping.d.ts +29 -0
  17. package/dist/common/types/ws-message.d.ts +58 -0
  18. package/dist/common/utils/agent-utils.d.ts +0 -0
  19. package/dist/common/utils/generationParams.d.ts +19 -0
  20. package/dist/common/utils/logc.d.ts +17 -0
  21. package/dist/common/utils/reasoning.d.ts +32 -0
  22. package/dist/common/utils/templateUtils.d.ts +7 -0
  23. package/dist/common.d.ts +12 -362
  24. package/dist/common.js +1 -1
  25. package/dist/{composioTool-EXCSM6F4.js → composioTool-TVURCFXP.js} +1 -1
  26. package/dist/convertTempMessure-5CAGRLBY.js +1 -0
  27. package/dist/{httpTool-EU63HPF5.js → httpTool-NTDDXZZE.js} +1 -1
  28. package/dist/index.d.ts +27 -431
  29. package/dist/index.js +13 -13
  30. package/dist/{oraApi-3JWDQQUE.js → oraApi-YIJGMXX7.js} +1 -1
  31. package/dist/{recall-SD6FENAS.js → recall-IABRCSHY.js} +1 -1
  32. package/dist/server/api/agents.d.ts +1 -0
  33. package/dist/server/api/auth.d.ts +1 -0
  34. package/dist/server/api/commons.d.ts +1 -0
  35. package/dist/server/api/composio.d.ts +1 -0
  36. package/dist/server/api/instances.d.ts +1 -0
  37. package/dist/server/core/AgentDO.d.ts +80 -0
  38. package/dist/server/core/AgentHTTP.d.ts +2 -0
  39. package/dist/server/logic/FlowEngine.d.ts +38 -0
  40. package/dist/server/logic/llm/files.d.ts +2 -0
  41. package/dist/server/logic/llm/images.d.ts +5 -0
  42. package/dist/server/logic/serverMessages.d.ts +13 -0
  43. package/dist/server/runners/answerNodeRunner.d.ts +4 -0
  44. package/dist/server/runners/apiNodeRunner.d.ts +4 -0
  45. package/dist/server/runners/classifierNodeRunner.d.ts +6 -0
  46. package/dist/server/runners/llmNodeRunner.d.ts +6 -0
  47. package/dist/server/runners/memoNodeRunner.d.ts +4 -0
  48. package/dist/server/runners/startNodeRunner.d.ts +4 -0
  49. package/dist/server/sql/agentSQL.d.ts +24 -0
  50. package/dist/server/tools/composioTool.d.ts +4 -0
  51. package/dist/server/tools/convertTempMessure.d.ts +15 -0
  52. package/dist/server/tools/httpTool.d.ts +18 -0
  53. package/dist/server/tools/recall.d.ts +7 -0
  54. package/dist/server/tools/skillTool.d.ts +6 -0
  55. package/dist/server/tools/tempTool.d.ts +4 -0
  56. package/dist/server/tools/twitter.d.ts +5 -0
  57. package/dist/server/tools/vectorize.d.ts +6 -0
  58. package/dist/server/types/node.d.ts +25 -0
  59. package/dist/server/utils/apiUtils.d.ts +14 -0
  60. package/dist/server/utils/auth.d.ts +3 -0
  61. package/dist/server/utils/composio.d.ts +114 -0
  62. package/dist/server/utils/contextMemory.d.ts +25 -0
  63. package/dist/server/utils/cookies.d.ts +1 -0
  64. package/dist/server/utils/coreApi.d.ts +7 -0
  65. package/dist/server/utils/embeddings.d.ts +3 -0
  66. package/dist/server/utils/flowRefresh.d.ts +22 -0
  67. package/dist/server/utils/flowValidation.d.ts +2 -0
  68. package/dist/server/utils/jsonSchemaToZod.d.ts +12 -0
  69. package/dist/server/utils/modelProvider.d.ts +20 -0
  70. package/dist/server/utils/oraApi.d.ts +6 -0
  71. package/dist/server/utils/oraExtract.d.ts +11 -0
  72. package/dist/server/utils/secrets.d.ts +2 -0
  73. package/dist/server/utils/secretsRefs.d.ts +6 -0
  74. package/dist/server/utils/sessionEnvMemory.d.ts +12 -0
  75. package/dist/server/utils/sessionIndex.d.ts +16 -0
  76. package/dist/server/utils/telemetry.d.ts +10 -0
  77. package/dist/server/utils/templateUtils.d.ts +7 -0
  78. package/dist/{skillTool-Y5GZ4ZAR.js → skillTool-BSQFKZGK.js} +1 -1
  79. package/dist/tempTool-2RXAF56M.js +1 -0
  80. package/dist/{twitter-QNCTAE4E.js → twitter-OMDEG7T2.js} +1 -1
  81. package/dist/vectorize-UJXIDL2E.js +1 -0
  82. package/package.json +19 -19
  83. package/dist/chunk-2JN3IX2Y.js +0 -1
  84. package/dist/chunk-6BYZCJPP.js +0 -1
  85. package/dist/convertTempMessure-TT7DIP6C.js +0 -1
  86. package/dist/magic-string.es-S3C7UPCH.js +0 -13
  87. package/dist/skillTool.test-6UDHQARG.js +0 -190
  88. package/dist/tempTool-6Q6C4HEJ.js +0 -1
  89. package/dist/vectorize-SQROWLSU.js +0 -1
package/dist/index.js CHANGED
@@ -1,26 +1,26 @@
1
- import{a as it,b as Pt,c as Jt,d as Xt}from"./chunk-26SLPOG6.js";import{a as Wt}from"./chunk-GOWQA2OT.js";import{a as fo,b as at,c as uo,d as G,e as wt,f as Gt,g as Bt,h as Et,i as Qt,j as rt,k as xt,l as Zt}from"./chunk-57TCP6J4.js";import{a as zt,b as Yt}from"./chunk-4FUIFBZO.js";import{a as b,b as et,c as Ge,d as ot,e as bt,f as qt,g as mo,h as yo}from"./chunk-HAYNUZZB.js";import{a as Y,b as Be,c as Ee,d as st,e as nt,f as Dt}from"./chunk-OYP6D5VN.js";import{a as Qe,b as Ze,c as Se,d as ve,e as to,f as eo,g as Ut,h as oo,i as Lt,j as so,k as no,l as io,m as ao,n as ro,o as lo,p as co,q as po,r as jt,s as Ht,t as Vt}from"./chunk-GRZ6ZRHM.js";import{a as qe}from"./chunk-43NDF544.js";import{a as Je}from"./chunk-2JN3IX2Y.js";import{a as We}from"./chunk-6HY7QUMP.js";import{a as Ke,b as Xe}from"./chunk-V6JSMX5A.js";import{a as z,b as tt,c as ze,d as Mt,e as Ye}from"./chunk-TUI5H3ZB.js";import{a as v}from"./chunk-U56YWPSI.js";import{a as Kt}from"./chunk-YHXUBVN2.js";import{a as S}from"./chunk-6BYZCJPP.js";import{Agent as Pe}from"agents";import{nanoid as Ue}from"nanoid";async function St(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 l=await n.json();return{name:t.name,text:l.text||""}}catch(n){return console.error(`extractDocuments: ${t.name} threw`,n),{name:t.name,text:""}}})):[]}async function Rt(o,e,s,t,n,l,m){var c,d,f;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});try{let r=await((c=o.getMessages)==null?void 0:c.call(o))??[],{flowId:p,chatId:a,tenant:u}=s.flowData,i=((d=r[r.length-1])==null?void 0:d.type)==="text"?r[r.length-1].content:"NO-TEXT";m==null||m({type:"answer_node",payload:{userMessage:(f=s==null?void 0:s.context)==null?void 0:f.user_input,answer:i}})}catch(r){console.error("answerNodeRunner: failed to emit answer telemetry:",r),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(r)}})}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 K(o,e,s,t,n){var c,d,f;let l=(n==null?void 0:n.callerTag)??"llmNodeRunner",m=(n==null?void 0:n.serializeNonStrings)??!1;try{return Dt(o,e,{context:s.context??{},results:s.results??{},nodes:((d=(c=s.flowData)==null?void 0:c.state)==null?void 0:d.nodes)??[],secrets:(f=n==null?void 0:n.sessionEnv)==null?void 0:f.secrets},{callerTag:l,serializeNonStrings:m,onError:r=>{t==null||t({type:`error:${l}`,content:r})}})}catch(r){return console.error(r),"error"}}var vt="[redacted]",Nt=(o,e,s,t,n)=>K(o,e,s,n,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function Ct(o,e,s,t,n,l,m){var f,r,p,a,u,i;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=null,d=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(s.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(s.results||{}));let g=((f=e.data)==null?void 0:f.url)||"",h=Nt(g,e,s,o,t);if(console.log("[apiNodeRunner] resolved url:",it(g)?Pt(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=(((r=e.data)==null?void 0:r.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",w);let y=((p=e.data)==null?void 0:p.headers)||{},x={},C={};for(let M in y)if(Object.prototype.hasOwnProperty.call(y,M)){let q=String(y[M]??"");C[M]=it(q),x[M]=Nt(q,e,s,o,t)}let N,$=!1;if(w!=="GET"&&w!=="HEAD"&&((a=e.data)==null?void 0:a.body)!==void 0){let M=typeof e.data.body=="string"?e.data.body:JSON.stringify(e.data.body);$=it(M),N=Nt(M,e,s,o,t),!x["Content-Type"]&&!x["content-type"]&&(x["Content-Type"]="application/json")}let R={};for(let M in x)R[M]=C[M]?vt:x[M];console.log("[apiNodeRunner] headers:",JSON.stringify(R)),console.log("[apiNodeRunner] body:",$?vt:N),t==null||t({type:"info:apiNodeRunner",content:`${w} ${h}`});let k=Number((u=e.data)==null?void 0:u.timeoutMs),D=new AbortController,A=Number.isFinite(k)&&k>0?setTimeout(()=>D.abort(),k):null,F;try{console.log("[apiNodeRunner] fetching..."),F=await fetch(h,{method:w,headers:x,body:N,signal:D.signal}),console.log("[apiNodeRunner] fetch returned status:",F.status)}finally{A&&clearTimeout(A)}let j=F.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",j);let T;j.includes("application/json")?T=await F.json():T=await F.text(),console.log("[apiNodeRunner] payload preview:",typeof T=="string"?T.slice(0,200):JSON.stringify(T).slice(0,200)),c={ok:F.ok,status:F.status,data:T};let U=Date.now()-d;m==null||m({type:"api_call",payload:{nodeId:e.id,url:h,method:w,status:F.status,latencyMs:U}}),t==null||t({type:"info:apiNodeRunner",content:`Response ${F.status} (${U}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:",(i=JSON.stringify(c))==null?void 0:i.slice(0,300)),n==null||n(e.id,c)}}import{generateObject as he}from"ai";import{z as te}from"zod";async function Tt(o,e,s,t,n,l,m){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)??{},d=String(((g=e==null?void 0:e.data)==null?void 0:g.input_variable)||"user_input").trim(),f=(c==null?void 0:c[d])??"",r=Array.isArray((h=e==null?void 0:e.data)==null?void 0:h.items)?e.data.items:[];if(r.length===0){t==null||t({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let p=String((w=r[r.length-1])==null?void 0:w.id);if(!f||String(f).trim().length===0){t==null||t({type:"warning:classifier",content:"No input for classification \u2014 falling back to last item."}),n==null||n(e.id,{classification:p}),s.context=s.context||{},s.context.classified_id=p,l==null||l(s);return}let u=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
1
+ import{a as it,b as Ut,c as Kt,d as Wt}from"./chunk-26SLPOG6.js";import{a as zt}from"./chunk-GOWQA2OT.js";import{a as Yt,b as Gt}from"./chunk-4FUIFBZO.js";import{a as uo,b as at,c as mo,d as E,e as xt,f as Et,g as Bt,h as Qt,i as Zt,j as rt,k as Rt,l as St}from"./chunk-57TCP6J4.js";import{a as b,b as et,c as Ee,d as ot,e as bt,f as Jt,g as yo,h as go}from"./chunk-HAYNUZZB.js";import{a as G,b as Be,c as Qe,d as st,e as nt,f as Pt}from"./chunk-OYP6D5VN.js";import{a as Ze,b as Se,c as ve,d as to,e as eo,f as oo,g as Lt,h as so,i as jt,j as no,k as io,l as ao,m as ro,n as lo,o as co,p as fo,q as po,r as Ht,s as Vt,t as qt}from"./chunk-GRZ6ZRHM.js";import{a as Je}from"./chunk-RYHQGPX5.js";import{a as Ke}from"./chunk-R6EKV3WR.js";import{a as ze}from"./chunk-6HY7QUMP.js";import{a as Xe,b as We}from"./chunk-V6JSMX5A.js";import{a as z,b as Y,c as Ye,d as Dt,e as Ge}from"./chunk-G3SGJ7XJ.js";import{a as tt}from"./chunk-U56YWPSI.js";import{a as Xt}from"./chunk-YHXUBVN2.js";import{a as v}from"./chunk-3TXHFKDN.js";import{Agent as Ue}from"agents";import{nanoid as Le}from"nanoid";async function vt(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 a=await n.json();return{name:t.name,text:a.text||""}}catch(n){return console.error(`extractDocuments: ${t.name} threw`,n),{name:t.name,text:""}}})):[]}async function Nt(o,e,s,t,n,a,p){var c,d,u;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});try{let l=await((c=o.getMessages)==null?void 0:c.call(o))??[],{flowId:f,chatId:r,tenant:m}=s.flowData,i=((d=l[l.length-1])==null?void 0:d.type)==="text"?l[l.length-1].content:"NO-TEXT";p==null||p({type:"answer_node",payload:{userMessage:(u=s==null?void 0:s.context)==null?void 0:u.user_input,answer:i}})}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 K(o,e,s,t,n){var c,d,u;let a=(n==null?void 0:n.callerTag)??"llmNodeRunner",p=(n==null?void 0:n.serializeNonStrings)??!1;try{return Pt(o,e,{context:s.context??{},results:s.results??{},nodes:((d=(c=s.flowData)==null?void 0:c.state)==null?void 0:d.nodes)??[],secrets:(u=n==null?void 0:n.sessionEnv)==null?void 0:u.secrets},{callerTag:a,serializeNonStrings:p,onError:l=>{t==null||t({type:`error:${a}`,content:l})}})}catch(l){return console.error(l),"error"}}var te="[redacted]",Ct=(o,e,s,t,n)=>K(o,e,s,n,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function Tt(o,e,s,t,n,a,p){var u,l,f,r,m,i;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=null,d=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(s.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(s.results||{}));let g=((u=e.data)==null?void 0:u.url)||"",h=Ct(g,e,s,o,t);if(console.log("[apiNodeRunner] resolved url:",it(g)?Ut(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=(((l=e.data)==null?void 0:l.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",w);let y=((f=e.data)==null?void 0:f.headers)||{},x={},C={};for(let M in y)if(Object.prototype.hasOwnProperty.call(y,M)){let q=String(y[M]??"");C[M]=it(q),x[M]=Ct(q,e,s,o,t)}let R,k=!1;if(w!=="GET"&&w!=="HEAD"&&((r=e.data)==null?void 0:r.body)!==void 0){let M=typeof e.data.body=="string"?e.data.body:JSON.stringify(e.data.body);k=it(M),R=Ct(M,e,s,o,t),!x["Content-Type"]&&!x["content-type"]&&(x["Content-Type"]="application/json")}let _={};for(let M in x)_[M]=C[M]?te:x[M];console.log("[apiNodeRunner] headers:",JSON.stringify(_)),console.log("[apiNodeRunner] body:",k?te:R),t==null||t({type:"info:apiNodeRunner",content:`${w} ${h}`});let P=Number((m=e.data)==null?void 0:m.timeoutMs),I=new AbortController,$=Number.isFinite(P)&&P>0?setTimeout(()=>I.abort(),P):null,A;try{console.log("[apiNodeRunner] fetching..."),A=await fetch(h,{method:w,headers:x,body:R,signal:I.signal}),console.log("[apiNodeRunner] fetch returned status:",A.status)}finally{$&&clearTimeout($)}let j=A.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",j);let N;j.includes("application/json")?N=await A.json():N=await A.text(),console.log("[apiNodeRunner] payload preview:",typeof N=="string"?N.slice(0,200):JSON.stringify(N).slice(0,200)),c={ok:A.ok,status:A.status,data:N};let D=Date.now()-d;p==null||p({type:"api_call",payload:{nodeId:e.id,url:h,method:w,status:A.status,latencyMs:D}}),t==null||t({type:"info:apiNodeRunner",content:`Response ${A.status} (${D}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:",(i=JSON.stringify(c))==null?void 0:i.slice(0,300)),n==null||n(e.id,c)}}import{generateObject as we}from"ai";import{z as ee}from"zod";async function It(o,e,s,t,n,a,p){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)??{},d=String(((g=e==null?void 0:e.data)==null?void 0:g.input_variable)||"user_input").trim(),u=(c==null?void 0:c[d])??"",l=Array.isArray((h=e==null?void 0:e.data)==null?void 0:h.items)?e.data.items:[];if(l.length===0){t==null||t({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let f=String((w=l[l.length-1])==null?void 0:w.id);if(!u||String(u).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:f}),s.context=s.context||{},s.context.classified_id=f,a==null||a(s);return}let m=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
2
2
  If the message is ambiguous or none clearly matches, choose the LAST category in the list.
3
3
 
4
4
  Categories:
5
- ${r.map(y=>{let x=y.keywords??y["keywords/topics"]??"",C=Array.isArray(x)?x.join(", "):String(x||"");return`- id: ${y.id}
5
+ ${l.map(y=>{let x=y.keywords??y["keywords/topics"]??"",C=Array.isArray(x)?x.join(", "):String(x||"");return`- id: ${y.id}
6
6
  label: ${y.label}
7
7
  keywords/topics: ${C}`}).join(`
8
8
  `)}
9
9
  `,i=`User message:
10
- """${String(f).trim()}"""
10
+ """${String(u).trim()}"""
11
11
 
12
- Select the best matching category id.`;try{let y=Date.now(),x=r.map(F=>String(F.id)),C="gpt_4_1_mini",N=await at(C,o);if(!N)throw new Error(`Model '${C}' not found in registry`);let{modelHandle:$,effectiveParams:R}=N,k=await he({model:$,messages:[{role:"system",content:u},{role:"user",content:i}],schema:te.object({classification:te.enum(x).describe("The id of the best matching category")}),temperature:R.temperature??0}),D=Date.now()-y,A=k.object.classification;m==null||m({type:"class_telemetry",payload:{nodeId:e.id,totalLatency:D,model:k.response.modelId,usage:k.usage,options:x}}),m==null||m({type:"class_result",payload:{result:k}}),n==null||n(e.id,{classification:A}),s.context=s.context||{},s.context.classified_id=A,l==null||l(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 Re,streamText as Ne}from"ai";import{nanoid as Ce}from"nanoid";import"zod";var P=(o,e,s)=>{o.send(e+"::"+s)};function ee(o,e){var t,n,l,m,c,d;let s="";if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let f of o.data.varMapping){let r=f.from;if(!r)continue;let p=!1;if(r==="files"||r==="file_content")p=!0;else{let a=r.indexOf(".");if(a!==-1){let u=r.substring(0,a),i=r.substring(a+1).split(".")[0],g=(m=(l=(n=e.flowData)==null?void 0:n.state)==null?void 0:l.nodes)==null?void 0:m.find(h=>h.id===u);if(g){let w=st(g).find(y=>y.name===i);(w==null?void 0:w.type)==="file"&&(p=!0)}}}if(p){let a=nt(r,{context:e.context||{},results:e.results||{},nodes:((d=(c=e.flowData)==null?void 0:c.state)==null?void 0:d.nodes)||[]});typeof a=="string"&&a.trim()&&(s+=(s?`
12
+ Select the best matching category id.`;try{let y=Date.now(),x=l.map(A=>String(A.id)),C="gpt_4_1_mini",R=await at(C,o);if(!R)throw new Error(`Model '${C}' not found in registry`);let{modelHandle:k,effectiveParams:_}=R,P=await we({model:k,messages:[{role:"system",content:m},{role:"user",content:i}],schema:ee.object({classification:ee.enum(x).describe("The id of the best matching category")}),temperature:_.temperature??0}),I=Date.now()-y,$=P.object.classification;p==null||p({type:"class_telemetry",payload:{nodeId:e.id,totalLatency:I,model:P.response.modelId,usage:P.usage,options:x}}),p==null||p({type:"class_result",payload:{result:P}}),n==null||n(e.id,{classification:$}),s.context=s.context||{},s.context.classified_id=$,a==null||a(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 Ne,streamText as Ce}from"ai";import{nanoid as Te}from"nanoid";import"zod";var U=(o,e,s)=>{o.send(e+"::"+s)};function oe(o,e){var t,n,a,p,c,d;let s="";if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let u of o.data.varMapping){let l=u.from;if(!l)continue;let f=!1;if(l==="files"||l==="file_content")f=!0;else{let r=l.indexOf(".");if(r!==-1){let m=l.substring(0,r),i=l.substring(r+1).split(".")[0],g=(p=(a=(n=e.flowData)==null?void 0:n.state)==null?void 0:a.nodes)==null?void 0:p.find(h=>h.id===m);if(g){let w=st(g).find(y=>y.name===i);(w==null?void 0:w.type)==="file"&&(f=!0)}}}if(f){let r=nt(l,{context:e.context||{},results:e.results||{},nodes:((d=(c=e.flowData)==null?void 0:c.state)==null?void 0:d.nodes)||[]});typeof r=="string"&&r.trim()&&(s+=(s?`
13
13
 
14
- `:"")+a)}}return s}function oe(o,e){var t,n,l,m,c,d;let s=[];if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let f of o.data.varMapping){let r=f.from;if(!r)continue;let p=!1;if(r==="images")p=!0;else{let a=r.indexOf(".");if(a!==-1){let u=r.substring(0,a),i=r.substring(a+1).split(".")[0],g=(m=(l=(n=e.flowData)==null?void 0:n.state)==null?void 0:l.nodes)==null?void 0:m.find(h=>h.id===u);if(g){let w=st(g).find(y=>y.name===i);(w==null?void 0:w.type)==="image"&&(p=!0)}}}if(p){let a=nt(r,{context:e.context||{},results:e.results||{},nodes:((d=(c=e.flowData)==null?void 0:c.state)==null?void 0:d.nodes)||[]});Array.isArray(a)&&s.push(...a)}}return s}var we=S({"../tools/composioTool.ts":()=>import("./composioTool-EXCSM6F4.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-TT7DIP6C.js"),"../tools/httpTool.ts":()=>import("./httpTool-EU63HPF5.js"),"../tools/recall.ts":()=>import("./recall-SD6FENAS.js"),"../tools/skillTool.test.ts":()=>import("./skillTool.test-6UDHQARG.js"),"../tools/skillTool.ts":()=>import("./skillTool-Y5GZ4ZAR.js"),"../tools/tempTool.ts":()=>import("./tempTool-6Q6C4HEJ.js"),"../tools/twitter.ts":()=>import("./twitter-QNCTAE4E.js"),"../tools/vectorize.ts":()=>import("./vectorize-SQROWLSU.js")});var xe=S({});function It(o,e,s,t,n){var m;if(!((m=t.memoryConfig)!=null&&m.enabled)||!t.memoryConfig.toolCache||!s.cacheable||!e||typeof e.execute!="function")return e;let l=e.execute.bind(e);return e.execute=async(c,...d)=>{var a;if(!t.getContextIndex)return l(c,...d);let f=await wt(c),p=(await t.getContextIndex()).find(u=>{if(u.domain!=="tool")return!1;let i=xt(u.meta);return i.toolName===o&&i.paramsHash===f});if(p){let u=await((a=t.getContext)==null?void 0:a.call(t,p.ref));if((u==null?void 0:u.data)!=null&&xt(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 l(c,...d)},e}async function Te(o,e,s,t){var r,p;if(!((r=s.memoryConfig)!=null&&r.enabled)||!s.setContext||s.cycle==null)return;let n=o.toolCalls??[],l=o.toolResults??[];if(!n.length||!l.length)return;let m=new Map;for(let a of l)a!=null&&a.toolCallId&&m.set(a.toolCallId,a);let c=Array.isArray((p=e==null?void 0:e.data)==null?void 0:p.tools)?e.data.tools:[],d=new Map;for(let a of c)a&&typeof a.id=="string"&&d.set(a.id,a);let f=new Map;for(let a of Object.values(s.toolDefs??{}))a&&a.name&&f.set(a.name,a);for(let a of n){let u=a.toolCallId,i=a.toolName,g=m.get(u);if(!i||!g||i==="readSkillRef")continue;let h=a.args??a.input,w=g.result??g.output,y=!1,x="",C="tool",N="",$=f.get(i);$&&$.kind==="skill"&&(y=!0,x=`skill:${i}`,C="skill",N=`Skill instructions for ${i}`),x||(x=await Bt(i,h),N=Gt(h,w));let R=d.get(i)??c.find(A=>A.id===i),k=await wt(h),D=typeof w=="string"?w:JSON.stringify(w??null);await s.setContext({ref:x,domain:C,description:N,data:D,cycle:s.cycle,meta:JSON.stringify({toolName:i,paramsHash:k,cacheable:(R==null?void 0:R.cacheable)===!0})}),t==null||t({type:"info:memory:updated",content:{ref:x}})}}async function Ie(o,e,s,t){var p;let n=Array.isArray((p=s==null?void 0:s.data)==null?void 0:p.tools)?s.data.tools:[];if(n.length===0)return{};let l={},m=a=>{var x,C;let u=typeof(a==null?void 0:a.description)=="string"?a.description:"",i=a==null?void 0:a.inputSchema,g;try{let N=(i==null?void 0:i.shape)??(typeof((x=i==null?void 0:i._def)==null?void 0:x.shape)=="function"?i._def.shape():(C=i==null?void 0:i._def)==null?void 0:C.shape);N&&typeof N=="object"&&(g=N)}catch{}let h=g?Object.keys(g):[],w=u?`description="${u.length>120?u.slice(0,120)+"\u2026":u}"`:"description=(none)",y=h.length?`inputSchema={${h.join(", ")}}`:"inputSchema=(none)";return`${w} ${y}`},c=(()=>{let a=[],u=[],i=[],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"?a.push(y.id):y.kind==="skill"?i.push(y.id):y.kind==="http"||y.kind==="mcp"||y.kind==="composio"?u.push(y.id):g.push(w)}let h=[];return a.length&&h.push(`builtin[${a.join(", ")}]`),u.length&&h.push(`custom[${u.join(", ")}]`),i.length&&h.push(`skill[${i.join(", ")}]`),g.length&&h.push(`invalid@[${g.join(", ")}]`),h.join(" ")||"(none)"})();console.log(`[tools] node ${s.id} requested (${n.length}): ${c}`);let d=!1,f=async()=>{if(d&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},d=!0,o.toolDefs;try{let a=await Kt(o.env),u={};for(let i of a)i&&i.id&&(u[i.id]=i);o.toolDefs=u}catch(a){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(a)}`}),o.toolDefs=o.toolDefs||{}}return d=!0,o.toolDefs},r=[];for(let a=0;a<n.length;a++){let u=n[a];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 ${a}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let i=u;if(i.kind!=="builtin"){let h=(await f())[i.id];if(!h){console.error(`[tools] \u2717 custom '${i.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${i.id}' not found for this tenant`});continue}if(i.kind==="composio"){try{let y=await Wt(h,o,e,t),x=Object.keys(y);for(let[C,N]of Object.entries(y))l[C]=It(C,N,i,o,t);console.log(`[tools] \u2713 composio '${i.id}' \u2192 ${x.length} tool(s)`)}catch(y){console.error(`[tools] \u2717 composio '${i.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${i.id}': ${String(y)}`})}continue}if(i.kind==="skill"){if(h.kind!=="skill"){console.error(`[tools] \u2717 skill '${i.id}': row is of kind '${h.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${i.id}' is not a skill`});continue}let y=h.name;if(l[y]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${y}' \u2014 builtin/other already registered, skipping skill '${i.id}'`});continue}try{l[y]=zt(h,o,e,t),r.push(h);let x=typeof h.execution=="string"?JSON.parse(h.execution):h.execution||{},C=Array.isArray(x.references)?x.references.map(N=>N==null?void 0:N.name):[];console.log(`[tools] \u2713 skill '${i.id}' \u2192 '${y}' (refs: ${C.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:y,refCount:C.length,refs:C}})}catch(x){console.error(`[tools] \u2717 skill '${i.id}': ${String(x)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${i.id}': ${String(x)}`})}continue}let w=h.name;if(l[w]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin already registered, skipping custom tool '${i.id}'`});continue}try{let y=Xt(h,o,e,t);l[w]=It(w,y,i,o,t),console.log(`[tools] \u2713 custom '${i.id}' \u2192 '${w}'`),console.log(`[tools] ${m(l[w])}`)}catch(y){console.error(`[tools] \u2717 custom '${i.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${i.id}': ${String(y)}`})}continue}if(!qt[i.id]){console.error(`[tools] \u2717 builtin '${i.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${i.id}' not found in registry`});continue}try{let g;try{g=await we(`../tools/${i.id}.ts`)}catch{g=await xe(`../tools/${i.id}.js`)}let h;if(g[i.id])h=g[i.id];else if(g.default)h=g.default;else if(g.create)h=g.create;else{let R=Object.values(g);R.length>0&&(h=R[0])}if(!h){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${i.id}'`});continue}let w,y,x={};if(i.params&&typeof i.params=="object"){if(typeof i.params.description=="string"?w=i.params.description:i.params.description!==void 0&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${i.id}' \u2014 must be a string`})),i.params.inputSchema!==void 0){let R=i.params.inputSchema;typeof R=="object"&&(typeof R.safeParse=="function"||R._def)?y=R:typeof R=="object"&&R!==null&&R.type==="object"&&R.properties?(y=Jt(R),y||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${i.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${i.id}' \u2014 must be a Zod schema or JSON Schema object`})}i.params.defaults!==void 0?typeof i.params.defaults=="object"&&i.params.defaults!==null&&!Array.isArray(i.params.defaults)?x=i.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${i.id}' \u2014 must be an object`}),x={}):i.params.source!==void 0||i.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${i.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),x={}):x={}}let C=h(o,e,x,t);w&&C&&typeof C=="object"&&(C.description=w),y&&C&&typeof C=="object"&&(C.inputSchema=y),l[i.id]=It(i.id,C,i,o,t);let N=[];w&&N.push("description"),y&&N.push("inputSchema"),Object.keys(x).length&&N.push(`defaults(${Object.keys(x).join(",")})`);let $=N.length?` [overrides: ${N.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${i.id}'${$}`),console.log(`[tools] ${m(C)}`)}catch(g){console.error(`[tools] \u2717 builtin '${i.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${i.id}': ${String(g)}`});continue}}if(r.length>0)if(l.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{l.readSkillRef=Yt(o,r,e,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${r.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:r.map(a=>a.name)}})}catch(a){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(a)}`)}return l}async function Ot(o,e,s,t,n,l,m){var k,D,A,F,j;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=!1;try{let T=(k=s.flowData)==null?void 0:k.state;if(T&&T.edges&&T.nodes){let U=T.edges.filter(M=>M.source===e.id);if(U.length>0){let M=T.nodes.find(q=>q.id===U[0].target);M&&M.type==="answerNode"&&(c=!0)}}}catch(T){console.error("Error determining next node for streaming:",T)}let d=K(e.data.template,e,s,t,{sessionEnv:o});(!d||!d.trim())&&(d="Answer straight forward to the user, dont offer any other option to continue");let f=d,r="";if((D=o.memoryConfig)!=null&&D.enabled){let T=await((A=o.getContextIndex)==null?void 0:A.call(o))??[];r=Qt(T),d+=r}let p=K(e.data.user_template||"",e,s,t,{sessionEnv:o}),a=T=>T&&Object.fromEntries(Object.keys(T).map(U=>[U,"[redacted]"])),u=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:a(o.secrets),userAuth:a(o.userAuth)}:o,i=K(e.data.template,e,s,void 0,{sessionEnv:u})||f;i+=r;let g=K(e.data.user_template||"",e,s,void 0,{sessionEnv:u});t==null||t({type:`info:llmNodeRunner:${e.id}`,content:i}),t==null||t({type:`info:llmNodeRunner:${e.id}`,content:g});let h=(F=e==null?void 0:e.data)==null?void 0:F.window_size,w=Number(h);(!Number.isInteger(w)||w<=0)&&(w=5);let y=oe(e,s),x=ee(e,s),N=(await((j=o.getMessages)==null?void 0:j.call(o))??[]).slice(-w),$=N.filter(T=>T&&typeof T.role=="string"&&typeof T.content=="string");$.length!==N.length&&console.warn(`Filtered ${N.length-$.length} invalid messages from history`);let R=_e($,p,y,x);await Oe(d,R,o.conn,t,e,c,n,s,l,o,m)}async function Oe(o,e,s,t,n,l,m,c,d,f,r){var a;let p=Date.now();if(!((a=f.env)!=null&&a.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(u,i)=>{var j,T,U,M,q,B,E;let g,h={},w,y="none",x=!1,C,N=!1,$=!1,R=0,k=0,D=(j=n==null?void 0:n.data)==null?void 0:j.sendReasoning,A=D!==!1;try{let L=(T=n==null?void 0:n.data)==null?void 0:T.model,W=Array.isArray(L)?L[0]:L||"gpt_5_nano",I=Ut(n==null?void 0:n.data),_=await at(W,f,I);if(!_)throw new Error(`Model '${W}' not found in registry`);g=_.modelHandle,h=_.effectiveParams||{},y=_.reasoning.kind;let O=Ht(_.reasoning,(U=n==null?void 0:n.data)==null?void 0:U.reasoningEffort);x=A&&jt(_.reasoning);let V=typeof((M=n==null?void 0:n.data)==null?void 0:M.reasoningMaxTokens)=="number"?n.data.reasoningMaxTokens:void 0;w=Vt(_.provider,{effort:O,exposeReasoning:x,maxTokens:V}),O&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:O})),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:O??null,sendReasoning:A,exposeReasoning:x,providerOptions:w??null},null,2)}`);for(let H of _.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:H});t==null||t({type:"info:llmNodeRunner:model",content:W}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(B=n==null?void 0:n.data)!=null&&B.generationPreset?{preset:n.data.generationPreset}:{},...h,...y!=="none"?{reasoning:y,configuredSendReasoning:D,sendReasoning:A,exposeReasoning:x,...O?{effort:O}:{}}:{}}})}catch(L){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(L)}`}),L}let F=await Ie(f,c,n,t);if((E=f.memoryConfig)!=null&&E.enabled){let{recall:L}=await import("./recall-SD6FENAS.js");F.recall=L(f,c,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 L=Ne({model:g,system:o,messages:e,stopWhen:(()=>{var H;let _=!!F.readSkillRef?10:5,O=Number(((H=n.data)==null?void 0:H.max_steps)??_),V=Number.isFinite(O)?Math.max(1,Math.min(30,O)):_;return Re(V)})(),...Lt(h),...w?{providerOptions:w}:{},tools:F,onFinish:async I=>{var At,Ft;let _=I.text||"",O=I.reasoningText??((At=I.reasoning)==null?void 0:At.text)??"";if(console.log(`[reasoning] done: deltas=${R} chars=${k} result.reasoningText=${O.length} finishReason=${I.finishReason??"n/a"} reasoningTokens=${((Ft=I.usage)==null?void 0:Ft.reasoningTokens)??"n/a"}`),A&&x&&!N&&O&&s){N=!0;try{P(s,b.SERVER_REASONING_STREAM,O)}catch(ge){console.warn("Failed to send finished reasoning over connection",ge)}}let V={id:Ce(),role:"assistant",type:"text",content:_,ts:Date.now()};l&&(f.setMessages?await f.setMessages(V):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),s&&A&&N&&!$&&($=!0,P(s,b.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),l&&s&&P(s,b.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),m==null||m((n==null?void 0:n.id)||"llm_result",_),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(I)});let H=Date.now()-p,ye=C?C-p:void 0;r==null||r({type:"llm_telemetry",payload:{nodeId:n.id,totalLatency:H,timeToFirstToken:ye,model:I.response.modelId,usage:I.usage}}),r==null||r({type:"llm_result",payload:{result:I}})},onStepFinish:async I=>{let _=(O,V=200)=>{let H=typeof O=="string"?O:JSON.stringify(O);return H?H.length>V?`${H.slice(0,V)}\u2026(+${H.length-V})`:H:""};if(I.toolCalls&&I.toolCalls.length>0){for(let O of I.toolCalls)console.log(`[tools] \u2192 ${O.toolName}(${_(O.args??O.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${n.id}`,content:JSON.stringify(I.toolCalls)})}if(I.toolResults&&I.toolResults.length>0){for(let O of I.toolResults)console.log(`[tools] \u2190 ${O.toolName} \u2192 ${_(O.result??O.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${n.id}`,content:JSON.stringify(I.toolResults)})}await Te(I,n,f,t)},experimental_onToolCallStart:I=>{var _;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(_=I==null?void 0:I.toolCall)==null?void 0:_.toolName,status:"start"}})},experimental_onToolCallFinish:I=>{var _;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(_=I==null?void 0:I.toolCall)==null?void 0:_.toolName,status:I!=null&&I.success?"success":"error"}})},onError:I=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),i(I)},onChunk:I=>{if(I.chunk.type==="reasoning-delta"){let O=I.chunk.text??I.chunk.delta??"";if(O&&(N=!0,R+=1,k+=O.length,R===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),A&&s&&O)try{P(s,b.SERVER_REASONING_STREAM,O)}catch(V){console.warn("Failed to send reasoning chunk over connection",V)}return}if(I.chunk.type==="text-delta"){if(C||(C=Date.now()),s&&A&&N&&!$){$=!0;try{P(s,b.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to send reasoning complete over connection",O)}}return}r==null||r({type:I.chunk.type,payload:{nodeId:n.id,chunk:I.chunk}});let _=`llm_chunk:${I.chunk.type}`;t==null||t({type:_,content:{...I}})}}),W=async()=>{let I="";for await(let _ of L.fullStream)if(_.type==="text-delta"){if(I+=_.text,l&&s)try{P(s,b.SERVER_TEXT_STREAM,_.text)}catch(O){console.warn("Failed to send chunk over connection",O)}}else if(_.type==="finish-step"&&_.finishReason==="tool-calls"){if(l&&s&&I.trim())try{P(s,b.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to flush text segment over connection",O)}I=""}};await Promise.all([L,W()]),u(),t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"success"}})}catch(L){t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"error",error:String(L)}}),i(L)}})}function _e(o,e,s,t){let n=!!(s&&s.length>0),l=!!t,m=n||l,d=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,f=r=>{let p=[],a="";if(l&&(a+=`[Attached files]
14
+ `:"")+r)}}return s}function se(o,e){var t,n,a,p,c,d;let s=[];if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let u of o.data.varMapping){let l=u.from;if(!l)continue;let f=!1;if(l==="images")f=!0;else{let r=l.indexOf(".");if(r!==-1){let m=l.substring(0,r),i=l.substring(r+1).split(".")[0],g=(p=(a=(n=e.flowData)==null?void 0:n.state)==null?void 0:a.nodes)==null?void 0:p.find(h=>h.id===m);if(g){let w=st(g).find(y=>y.name===i);(w==null?void 0:w.type)==="image"&&(f=!0)}}}if(f){let r=nt(l,{context:e.context||{},results:e.results||{},nodes:((d=(c=e.flowData)==null?void 0:c.state)==null?void 0:d.nodes)||[]});Array.isArray(r)&&s.push(...r)}}return s}var xe=v({"../tools/composioTool.ts":()=>import("./composioTool-TVURCFXP.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-NTDDXZZE.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 Re=v({});function Ot(o,e,s,t,n){var p;if(!((p=t.memoryConfig)!=null&&p.enabled)||!t.memoryConfig.toolCache||!s.cacheable||!e||typeof e.execute!="function")return e;let a=e.execute.bind(e);return e.execute=async(c,...d)=>{var r;if(!t.getContextIndex)return a(c,...d);let u=await xt(c),f=(await t.getContextIndex()).find(m=>{if(m.domain!=="tool")return!1;let i=Rt(m.meta);return i.toolName===o&&i.paramsHash===u});if(f){let m=await((r=t.getContext)==null?void 0:r.call(t,f.ref));if((m==null?void 0:m.data)!=null&&Rt(m.meta).truncated!==!0){n==null||n({type:"info:memory:cacheHit",content:{ref:m.ref,toolName:o}});try{return JSON.parse(m.data)}catch{return m.data}}}return a(c,...d)},e}async function Ie(o,e,s,t){var l,f;if(!((l=s.memoryConfig)!=null&&l.enabled)||!s.setContext||s.cycle==null)return;let n=o.toolCalls??[],a=o.toolResults??[];if(!n.length||!a.length)return;let p=new Map;for(let r of a)r!=null&&r.toolCallId&&p.set(r.toolCallId,r);let c=Array.isArray((f=e==null?void 0:e.data)==null?void 0:f.tools)?e.data.tools:[],d=new Map;for(let r of c)r&&typeof r.id=="string"&&d.set(r.id,r);let u=new Map;for(let r of Object.values(s.toolDefs??{}))r&&r.name&&u.set(r.name,r);for(let r of n){let m=r.toolCallId,i=r.toolName,g=p.get(m);if(!i||!g||i==="readSkillRef")continue;let h=r.args??r.input,w=g.result??g.output,y=!1,x="",C="tool",R="",k=u.get(i);k&&k.kind==="skill"&&(y=!0,x=`skill:${i}`,C="skill",R=`Skill instructions for ${i}`),x||(x=await Bt(i,h),R=Et(h,w));let _=d.get(i)??c.find($=>$.id===i),P=await xt(h),I=typeof w=="string"?w:JSON.stringify(w??null);await s.setContext({ref:x,domain:C,description:R,data:I,cycle:s.cycle,meta:JSON.stringify({toolName:i,paramsHash:P,cacheable:(_==null?void 0:_.cacheable)===!0})}),t==null||t({type:"info:memory:updated",content:{ref:x}})}}async function Oe(o,e,s,t){var f;let n=Array.isArray((f=s==null?void 0:s.data)==null?void 0:f.tools)?s.data.tools:[];if(n.length===0)return{};let a={},p=r=>{var x,C;let m=typeof(r==null?void 0:r.description)=="string"?r.description:"",i=r==null?void 0:r.inputSchema,g;try{let R=(i==null?void 0:i.shape)??(typeof((x=i==null?void 0:i._def)==null?void 0:x.shape)=="function"?i._def.shape():(C=i==null?void 0:i._def)==null?void 0:C.shape);R&&typeof R=="object"&&(g=R)}catch{}let h=g?Object.keys(g):[],w=m?`description="${m.length>120?m.slice(0,120)+"\u2026":m}"`:"description=(none)",y=h.length?`inputSchema={${h.join(", ")}}`:"inputSchema=(none)";return`${w} ${y}`},c=(()=>{let r=[],m=[],i=[],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"?r.push(y.id):y.kind==="skill"?i.push(y.id):y.kind==="http"||y.kind==="mcp"||y.kind==="composio"?m.push(y.id):g.push(w)}let h=[];return r.length&&h.push(`builtin[${r.join(", ")}]`),m.length&&h.push(`custom[${m.join(", ")}]`),i.length&&h.push(`skill[${i.join(", ")}]`),g.length&&h.push(`invalid@[${g.join(", ")}]`),h.join(" ")||"(none)"})();console.log(`[tools] node ${s.id} requested (${n.length}): ${c}`);let d=!1,u=async()=>{if(d&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},d=!0,o.toolDefs;try{let r=await Xt(o.env),m={};for(let i of r)i&&i.id&&(m[i.id]=i);o.toolDefs=m}catch(r){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(r)}`}),o.toolDefs=o.toolDefs||{}}return d=!0,o.toolDefs},l=[];for(let r=0;r<n.length;r++){let m=n[r];if(!m||typeof m!="object"||typeof m.id!="string"||m.kind!=="builtin"&&m.kind!=="http"&&m.kind!=="mcp"&&m.kind!=="composio"&&m.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${r}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let i=m;if(i.kind!=="builtin"){let h=(await u())[i.id];if(!h){console.error(`[tools] \u2717 custom '${i.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${i.id}' not found for this tenant`});continue}if(i.kind==="composio"){try{let y=await zt(h,o,e,t),x=Object.keys(y);for(let[C,R]of Object.entries(y))a[C]=Ot(C,R,i,o,t);console.log(`[tools] \u2713 composio '${i.id}' \u2192 ${x.length} tool(s)`)}catch(y){console.error(`[tools] \u2717 composio '${i.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${i.id}': ${String(y)}`})}continue}if(i.kind==="skill"){if(h.kind!=="skill"){console.error(`[tools] \u2717 skill '${i.id}': row is of kind '${h.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${i.id}' is not a skill`});continue}let y=h.name;if(a[y]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${y}' \u2014 builtin/other already registered, skipping skill '${i.id}'`});continue}try{a[y]=Yt(h,o,e,t),l.push(h);let x=typeof h.execution=="string"?JSON.parse(h.execution):h.execution||{},C=Array.isArray(x.references)?x.references.map(R=>R==null?void 0:R.name):[];console.log(`[tools] \u2713 skill '${i.id}' \u2192 '${y}' (refs: ${C.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:y,refCount:C.length,refs:C}})}catch(x){console.error(`[tools] \u2717 skill '${i.id}': ${String(x)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${i.id}': ${String(x)}`})}continue}let w=h.name;if(a[w]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin already registered, skipping custom tool '${i.id}'`});continue}try{let y=Wt(h,o,e,t);a[w]=Ot(w,y,i,o,t),console.log(`[tools] \u2713 custom '${i.id}' \u2192 '${w}'`),console.log(`[tools] ${p(a[w])}`)}catch(y){console.error(`[tools] \u2717 custom '${i.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${i.id}': ${String(y)}`})}continue}if(!Jt[i.id]){console.error(`[tools] \u2717 builtin '${i.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${i.id}' not found in registry`});continue}try{let g;try{g=await xe(`../tools/${i.id}.ts`)}catch{g=await Re(`../tools/${i.id}.js`)}let h;if(g[i.id])h=g[i.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 '${i.id}'`});continue}let w,y,x={};if(i.params&&typeof i.params=="object"){if(typeof i.params.description=="string"?w=i.params.description:i.params.description!==void 0&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${i.id}' \u2014 must be a string`})),i.params.inputSchema!==void 0){let _=i.params.inputSchema;typeof _=="object"&&(typeof _.safeParse=="function"||_._def)?y=_:typeof _=="object"&&_!==null&&_.type==="object"&&_.properties?(y=Kt(_),y||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${i.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${i.id}' \u2014 must be a Zod schema or JSON Schema object`})}i.params.defaults!==void 0?typeof i.params.defaults=="object"&&i.params.defaults!==null&&!Array.isArray(i.params.defaults)?x=i.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${i.id}' \u2014 must be an object`}),x={}):i.params.source!==void 0||i.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${i.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),x={}):x={}}let C=h(o,e,x,t);w&&C&&typeof C=="object"&&(C.description=w),y&&C&&typeof C=="object"&&(C.inputSchema=y),a[i.id]=Ot(i.id,C,i,o,t);let R=[];w&&R.push("description"),y&&R.push("inputSchema"),Object.keys(x).length&&R.push(`defaults(${Object.keys(x).join(",")})`);let k=R.length?` [overrides: ${R.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${i.id}'${k}`),console.log(`[tools] ${p(C)}`)}catch(g){console.error(`[tools] \u2717 builtin '${i.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${i.id}': ${String(g)}`});continue}}if(l.length>0)if(a.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{a.readSkillRef=Gt(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(r=>r.name)}})}catch(r){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(r)}`)}return a}async function _t(o,e,s,t,n,a,p){var P,I,$,A,j;`${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 D=N.edges.filter(M=>M.source===e.id);if(D.length>0){let M=N.nodes.find(q=>q.id===D[0].target);M&&M.type==="answerNode"&&(c=!0)}}}catch(N){console.error("Error determining next node for streaming:",N)}let d=K(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 u=d,l="";if((I=o.memoryConfig)!=null&&I.enabled){let N=await(($=o.getContextIndex)==null?void 0:$.call(o))??[];l=Zt(N),d+=l}let f=K(e.data.user_template||"",e,s,t,{sessionEnv:o}),r=N=>N&&Object.fromEntries(Object.keys(N).map(D=>[D,"[redacted]"])),m=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:r(o.secrets),userAuth:r(o.userAuth)}:o,i=K(e.data.template,e,s,void 0,{sessionEnv:m})||u;i+=l;let g=K(e.data.user_template||"",e,s,void 0,{sessionEnv:m});t==null||t({type:`info:llmNodeRunner:${e.id}`,content:i}),t==null||t({type:`info:llmNodeRunner:${e.id}`,content:g});let h=(A=e==null?void 0:e.data)==null?void 0:A.window_size,w=Number(h);(!Number.isInteger(w)||w<=0)&&(w=5);let y=se(e,s),x=oe(e,s),R=(await((j=o.getMessages)==null?void 0:j.call(o))??[]).slice(-w),k=R.filter(N=>N&&typeof N.role=="string"&&typeof N.content=="string");k.length!==R.length&&console.warn(`Filtered ${R.length-k.length} invalid messages from history`);let _=Fe(k,f,y,x);await _e(d,_,o.conn,t,e,c,n,s,a,o,p)}async function _e(o,e,s,t,n,a,p,c,d,u,l){var r;let f=Date.now();if(!((r=u.env)!=null&&r.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(m,i)=>{var j,N,D,M,q,B,Q;let g,h={},w,y="none",x=!1,C,R=!1,k=!1,_=0,P=0,I=(j=n==null?void 0:n.data)==null?void 0:j.sendReasoning,$=I!==!1;try{let L=(N=n==null?void 0:n.data)==null?void 0:N.model,W=Array.isArray(L)?L[0]:L||"gpt_5_nano",T=Lt(n==null?void 0:n.data),F=await at(W,u,T);if(!F)throw new Error(`Model '${W}' not found in registry`);g=F.modelHandle,h=F.effectiveParams||{},y=F.reasoning.kind;let O=Vt(F.reasoning,(D=n==null?void 0:n.data)==null?void 0:D.reasoningEffort);x=$&&Ht(F.reasoning);let V=typeof((M=n==null?void 0:n.data)==null?void 0:M.reasoningMaxTokens)=="number"?n.data.reasoningMaxTokens:void 0;w=qt(F.provider,{effort:O,exposeReasoning:x,maxTokens:V}),O&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:O})),console.log(`[reasoning] ${JSON.stringify({model:W,provider:F.provider,capability:F.reasoning,requestedEffort:((q=n==null?void 0:n.data)==null?void 0:q.reasoningEffort)??null,resolvedEffort:O??null,sendReasoning:$,exposeReasoning:x,providerOptions:w??null},null,2)}`);for(let H of F.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:H});t==null||t({type:"info:llmNodeRunner:model",content:W}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(B=n==null?void 0:n.data)!=null&&B.generationPreset?{preset:n.data.generationPreset}:{},...h,...y!=="none"?{reasoning:y,configuredSendReasoning:I,sendReasoning:$,exposeReasoning:x,...O?{effort:O}:{}}:{}}})}catch(L){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(L)}`}),L}let A=await Oe(u,c,n,t);if((Q=u.memoryConfig)!=null&&Q.enabled){let{recall:L}=await import("./recall-IABRCSHY.js");A.recall=L(u,c,void 0,t)}console.log(`[tools] node ${n.id} loaded ${Object.keys(A).length}: ${Object.keys(A).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:n.id,tools:Object.keys(A)}});try{let L=Ce({model:g,system:o,messages:e,stopWhen:(()=>{var H;let F=!!A.readSkillRef?10:5,O=Number(((H=n.data)==null?void 0:H.max_steps)??F),V=Number.isFinite(O)?Math.max(1,Math.min(30,O)):F;return Ne(V)})(),...jt(h),...w?{providerOptions:w}:{},tools:A,onFinish:async T=>{var At,Mt;let F=T.text||"",O=T.reasoningText??((At=T.reasoning)==null?void 0:At.text)??"";if(console.log(`[reasoning] done: deltas=${_} chars=${P} result.reasoningText=${O.length} finishReason=${T.finishReason??"n/a"} reasoningTokens=${((Mt=T.usage)==null?void 0:Mt.reasoningTokens)??"n/a"}`),$&&x&&!R&&O&&s){R=!0;try{U(s,b.SERVER_REASONING_STREAM,O)}catch(he){console.warn("Failed to send finished reasoning over connection",he)}}let V={id:Te(),role:"assistant",type:"text",content:F,ts:Date.now()};a&&(u.setMessages?await u.setMessages(V):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),s&&$&&R&&!k&&(k=!0,U(s,b.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),a&&s&&U(s,b.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),p==null||p((n==null?void 0:n.id)||"llm_result",F),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(T)});let H=Date.now()-f,ge=C?C-f:void 0;l==null||l({type:"llm_telemetry",payload:{nodeId:n.id,totalLatency:H,timeToFirstToken:ge,model:T.response.modelId,usage:T.usage}}),l==null||l({type:"llm_result",payload:{result:T}})},onStepFinish:async T=>{let F=(O,V=200)=>{let H=typeof O=="string"?O:JSON.stringify(O);return H?H.length>V?`${H.slice(0,V)}\u2026(+${H.length-V})`:H:""};if(T.toolCalls&&T.toolCalls.length>0){for(let O of T.toolCalls)console.log(`[tools] \u2192 ${O.toolName}(${F(O.args??O.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${n.id}`,content:JSON.stringify(T.toolCalls)})}if(T.toolResults&&T.toolResults.length>0){for(let O of T.toolResults)console.log(`[tools] \u2190 ${O.toolName} \u2192 ${F(O.result??O.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${n.id}`,content:JSON.stringify(T.toolResults)})}await Ie(T,n,u,t)},experimental_onToolCallStart:T=>{var F;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(F=T==null?void 0:T.toolCall)==null?void 0:F.toolName,status:"start"}})},experimental_onToolCallFinish:T=>{var F;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(F=T==null?void 0:T.toolCall)==null?void 0:F.toolName,status:T!=null&&T.success?"success":"error"}})},onError:T=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),i(T)},onChunk:T=>{if(T.chunk.type==="reasoning-delta"){let O=T.chunk.text??T.chunk.delta??"";if(O&&(R=!0,_+=1,P+=O.length,_===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),$&&s&&O)try{U(s,b.SERVER_REASONING_STREAM,O)}catch(V){console.warn("Failed to send reasoning chunk over connection",V)}return}if(T.chunk.type==="text-delta"){if(C||(C=Date.now()),s&&$&&R&&!k){k=!0;try{U(s,b.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to send reasoning complete over connection",O)}}return}l==null||l({type:T.chunk.type,payload:{nodeId:n.id,chunk:T.chunk}});let F=`llm_chunk:${T.chunk.type}`;t==null||t({type:F,content:{...T}})}}),W=async()=>{let T="";for await(let F of L.fullStream)if(F.type==="text-delta"){if(T+=F.text,a&&s)try{U(s,b.SERVER_TEXT_STREAM,F.text)}catch(O){console.warn("Failed to send chunk over connection",O)}}else if(F.type==="finish-step"&&F.finishReason==="tool-calls"){if(a&&s&&T.trim())try{U(s,b.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to flush text segment over connection",O)}T=""}};await Promise.all([L,W()]),m(),t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"success"}})}catch(L){t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"error",error:String(L)}}),i(L)}})}function Fe(o,e,s,t){let n=!!(s&&s.length>0),a=!!t,p=n||a,d=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,u=l=>{let f=[],r="";if(a&&(r+=`[Attached files]
15
15
  ${t}
16
16
  [End of attached files]
17
17
 
18
- `),r&&(a+=r),a&&p.push({type:"text",text:a}),n)for(let u of s)p.push({type:"image",image:u.data,mimeType:u.mimeType});return p};return e&&d&&d.content===e?[...o.slice(0,-1).map(p=>({role:p.role,content:p.content})),{role:"user",content:f(e)}]:e?[...o.map(r=>({role:r.role,content:r.content})),{role:"user",content:f(e)}]:m&&d?[...o.slice(0,-1).map(p=>({role:p.role,content:p.content})),{role:"user",content:f(d.content)}]:o.map(r=>({role:r.role,content:r.content}))}async function _t(o,e,s,t,n,l,m){var f,r,p,a;console.log(`**** MEMO Node id: ${e.id} ****`),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c="",d=Date.now();try{if(t==null||t({type:"info:memoNodeRunner",content:"Starting memo node execution"}),((f=s==null?void 0:s.context)==null?void 0:f[e.data.query_key])===void 0){t==null||t({type:"error:memoNodeRunner",content:`Query key ${e.data.query_key} not found in context`}),n==null||n(e.id,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 u=((r=s==null?void 0:s.context)==null?void 0:r[e.data.query_key])||"";t==null||t({type:"info:memoNodeRunner",content:`Query text: ${u}`}),t==null||t({type:"info:memoNodeRunner",content:"Generating embedding for query"});let i=await Mt(o,u,!0);t==null||t({type:"info:memoNodeRunner",content:`Embedding generated successfully, length: ${i.data[0].length}`});let g=Array.isArray(e.data.rag_id)?e.data.rag_id:[e.data.rag_id],h=[];for(let C of g){t==null||t({type:"info:memoNodeRunner",content:`Executing RAG query with namespace: ${C}`});let N=await o.env[`VDB_${(p=s.flowData)==null?void 0:p.tenant}_1024`].query(i.data[0],{namespace:C,topK:e.data.topk,returnMetadata:"all"});t==null||t({type:"info:memoNodeRunner",content:`RAG query completed for namespace ${C}, matches: ${((a=N.matches)==null?void 0:a.length)||0}`}),Array.isArray(N.matches)&&h.push(...N.matches)}let w=Date.now()-d;c=h.map(C=>{var N;return(N=C.metadata)==null?void 0:N.value}).filter(C=>typeof C=="string").join(`
18
+ `),l&&(r+=l),r&&f.push({type:"text",text:r}),n)for(let m of s)f.push({type:"image",image:m.data,mimeType:m.mimeType});return f};return e&&d&&d.content===e?[...o.slice(0,-1).map(f=>({role:f.role,content:f.content})),{role:"user",content:u(e)}]:e?[...o.map(l=>({role:l.role,content:l.content})),{role:"user",content:u(e)}]:p&&d?[...o.slice(0,-1).map(f=>({role:f.role,content:f.content})),{role:"user",content:u(d.content)}]:o.map(l=>({role:l.role,content:l.content}))}async function Ft(o,e,s,t,n,a,p){var u,l,f,r;console.log(`**** MEMO Node id: ${e.id} ****`),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c="",d=Date.now();try{if(t==null||t({type:"info:memoNodeRunner",content:"Starting memo node execution"}),((u=s==null?void 0:s.context)==null?void 0:u[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 m=((l=s==null?void 0:s.context)==null?void 0:l[e.data.query_key])||"";t==null||t({type:"info:memoNodeRunner",content:`Query text: ${m}`}),t==null||t({type:"info:memoNodeRunner",content:"Generating embedding for query"});let i=await Dt(o,m,!0);t==null||t({type:"info:memoNodeRunner",content:`Embedding generated successfully, length: ${i.data[0].length}`});let g=Array.isArray(e.data.rag_id)?e.data.rag_id:[e.data.rag_id],h=[];for(let C of g){t==null||t({type:"info:memoNodeRunner",content:`Executing RAG query with namespace: ${C}`});let R=await o.env[`VDB_${(f=s.flowData)==null?void 0:f.tenant}_1024`].query(i.data[0],{namespace:C,topK:e.data.topk,returnMetadata:"all"});t==null||t({type:"info:memoNodeRunner",content:`RAG query completed for namespace ${C}, matches: ${((r=R.matches)==null?void 0:r.length)||0}`}),Array.isArray(R.matches)&&h.push(...R.matches)}let w=Date.now()-d;c=h.map(C=>{var R;return(R=C.metadata)==null?void 0:R.value}).filter(C=>typeof C=="string").join(`
19
19
 
20
- `),m==null||m({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(u){console.error("Error processing MemoNode:",u),t==null||t({type:"error:memoNodeRunner",content:`Memo node execution failed: ${u}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(u)}})}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 $t(o,e,s,t,n,l,m){var f,r,p,a,u,i;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}),m==null||m({type:"start_node",payload:{userMessage:(f=s==null?void 0:s.context)==null?void 0:f.user_input}});let c=((r=e.data)==null?void 0:r.allow_images)!==!1,d=((p=e.data)==null?void 0:p.allow_documents)!==!1;!c&&(s!=null&&s.context)&&(s.context.user_images=[],l==null||l({...s})),!d&&(s!=null&&s.context)&&(s.context.files="",l==null||l({...s})),n==null||n(e.id,{user_input:(a=s==null?void 0:s.context)==null?void 0:a.user_input,images:c?(u=s==null?void 0:s.context)==null?void 0:u.user_images:[],files:d?(i=s==null?void 0:s.context)==null?void 0:i.files:""}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}function lt(o,e,s){let t=e;async function n(d){let f=d;for(t.executedNodes=t.executedNodes||[],t.context=t.context||{},t.results=t.results||{};f&&f.id;)await l(f),f=Ae(f,t.flowData,t)}async function l(d){var u;let f=c[d.type];if(!f){(u=s==null?void 0:s.onError)==null||u.call(s,`Unknown node type: ${d.type}`);return}let r=i=>{var g;return(g=s==null?void 0:s.onServerEvent)==null?void 0:g.call(s,{...i,ts:Date.now()})},p=i=>{var g,h;if((g=s==null?void 0:s.onTelemetry)==null||g.call(s,i),i.type==="llm_telemetry"||i.type==="class_telemetry"){let w=(h=i.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 f(o,d,t,r,(i,g)=>{t.results[i]=g},s==null?void 0:s.onChangeState,p)}let m=async d=>{var x,C,N;let f=Date.now(),r=typeof d=="string"?et(d):d,p=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.images)||[],u=(r==null?void 0:r.documents)||[],i=await St(u,o.env),g=i.length>0?i.map($=>`--- file: ${$.name} ---
21
- ${$.text}`).join(`
20
+ `),p==null||p({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(m){console.error("Error processing MemoNode:",m),t==null||t({type:"error:memoNodeRunner",content:`Memo node execution failed: ${m}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(m)}})}finally{n==null||n(e.id,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 $t(o,e,s,t,n,a,p){var u,l,f,r,m,i;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}),p==null||p({type:"start_node",payload:{userMessage:(u=s==null?void 0:s.context)==null?void 0:u.user_input}});let c=((l=e.data)==null?void 0:l.allow_images)!==!1,d=((f=e.data)==null?void 0:f.allow_documents)!==!1;!c&&(s!=null&&s.context)&&(s.context.user_images=[],a==null||a({...s})),!d&&(s!=null&&s.context)&&(s.context.files="",a==null||a({...s})),n==null||n(e.id,{user_input:(r=s==null?void 0:s.context)==null?void 0:r.user_input,images:c?(m=s==null?void 0:s.context)==null?void 0:m.user_images:[],files:d?(i=s==null?void 0:s.context)==null?void 0:i.files:""}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}function lt(o,e,s){let t=e;async function n(d){let u=d;for(t.executedNodes=t.executedNodes||[],t.context=t.context||{},t.results=t.results||{};u&&u.id;)await a(u),u=Ae(u,t.flowData,t)}async function a(d){var m;let u=c[d.type];if(!u){(m=s==null?void 0:s.onError)==null||m.call(s,`Unknown node type: ${d.type}`);return}let l=i=>{var g;return(g=s==null?void 0:s.onServerEvent)==null?void 0:g.call(s,{...i,ts:Date.now()})},f=i=>{var g,h;if((g=s==null?void 0:s.onTelemetry)==null||g.call(s,i),i.type==="llm_telemetry"||i.type==="class_telemetry"){let w=(h=i.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 u(o,d,t,l,(i,g)=>{t.results[i]=g},s==null?void 0:s.onChangeState,f)}let p=async d=>{var x,C,R;let u=Date.now(),l=typeof d=="string"?et(d):d,f=(l==null?void 0:l.text)||"",r=(l==null?void 0:l.images)||[],m=(l==null?void 0:l.documents)||[],i=await vt(m,o.env),g=i.length>0?i.map(k=>`--- file: ${k.name} ---
21
+ ${k.text}`).join(`
22
22
 
23
- `):"";t.context={user_input:p,user_images:a,files:g},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},(x=s==null?void 0:s.onServerEvent)==null||x.call(s,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:h,error:w}=$e(t.flowData);if(!h){(C=s==null?void 0:s.onError)==null||C.call(s,w||"Flow Format Error");return}await n(h);let y=Date.now()-f;(N=s==null?void 0:s.onServerEvent)==null||N.call(s,{type:"agent:telemetry",content:{durationMs:y,tokenUsage:t.tokenUsage},timestamp:Date.now()})},c={startNode:$t,classifierNode:Tt,llmNode:Ot,memoNode:_t,answerNode:Rt,apiNode:Ct};return m}function $e(o){var r;let e=(o==null?void 0:o.state)??o;if(!e||!e.nodes||!e.edges||e.edges.length===0)return{error:"Flow is missing state, nodes, or edges."};let s=e.nodes.filter(p=>p.type==="startNode");if(s.length!==1)return{error:`Flow must include exactly one START node, found ${s.length}.`};let t=s[0],n=e.nodes.filter(p=>p.type==="answerNode");if(n.length===0)return{error:"Flow must include at least one ANSWER node."};let l=new Map;for(let p of e.edges)l.has(p.source)||l.set(p.source,[]),l.get(p.source).push(p.target);let m=new Map;for(let p of e.edges)m.has(p.target)||m.set(p.target,[]),m.get(p.target).push(p.source);let c=se(t.id,l),d=new Set;for(let p of n){let a=se(p.id,m);for(let u of a)d.add(u)}let f=[];for(let p of c)if(!d.has(p)){let a=e.nodes.find(u=>u.id===p);if(a){let u=((r=a.data)==null?void 0:r.label)||"";f.push(`${p}(${u},${a.type})`)}}return f.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${f.join(", ")}`}:{startNode:t}}function se(o,e){let s=new Set,t=[o];for(s.add(o);t.length>0;){let n=t.shift(),l=e.get(n)||[];for(let m of l)s.has(m)||(s.add(m),t.push(m))}return s}function ke(o,e){var s;return((s=o.state)==null?void 0:s.nodes.find(t=>t.id===e))||null}function Ae(o,e,s){var c;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 l=n[0].target;if(o.type==="classifierNode"&&((c=s==null?void 0:s.context)!=null&&c.classified_id)){let d=s.context.classified_id,f=n.find(r=>r.sourceHandle===`source-${d}`);f?l=f.target:console.log(`No matching edge, falling back to first: ${l}`)}return ke(e,l)}async function Fe(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 ct(o,e){o.sql`INSERT INTO messages (id, role, type, content, ts) VALUES (${e.id}, ${e.role}, ${e.type}, ${e.content}, ${e.ts})`}async function X(o){return o.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function dt(o){o.sql`DELETE FROM messages`}async function Me(o){o.sql`CREATE TABLE IF NOT EXISTS context (
23
+ `):"";t.context={user_input:f,user_images:r,files:g},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},(x=s==null?void 0:s.onServerEvent)==null||x.call(s,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:h,error:w}=$e(t.flowData);if(!h){(C=s==null?void 0:s.onError)==null||C.call(s,w||"Flow Format Error");return}await n(h);let y=Date.now()-u;(R=s==null?void 0:s.onServerEvent)==null||R.call(s,{type:"agent:telemetry",content:{durationMs:y,tokenUsage:t.tokenUsage},timestamp:Date.now()})},c={startNode:$t,classifierNode:It,llmNode:_t,memoNode:Ft,answerNode:Nt,apiNode:Tt};return p}function $e(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(f=>f.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(f=>f.type==="answerNode");if(n.length===0)return{error:"Flow must include at least one ANSWER node."};let a=new Map;for(let f of e.edges)a.has(f.source)||a.set(f.source,[]),a.get(f.source).push(f.target);let p=new Map;for(let f of e.edges)p.has(f.target)||p.set(f.target,[]),p.get(f.target).push(f.source);let c=ne(t.id,a),d=new Set;for(let f of n){let r=ne(f.id,p);for(let m of r)d.add(m)}let u=[];for(let f of c)if(!d.has(f)){let r=e.nodes.find(m=>m.id===f);if(r){let m=((l=r.data)==null?void 0:l.label)||"";u.push(`${f}(${m},${r.type})`)}}return u.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${u.join(", ")}`}:{startNode:t}}function ne(o,e){let s=new Set,t=[o];for(s.add(o);t.length>0;){let n=t.shift(),a=e.get(n)||[];for(let p of a)s.has(p)||(s.add(p),t.push(p))}return s}function ke(o,e){var s;return((s=o.state)==null?void 0:s.nodes.find(t=>t.id===e))||null}function Ae(o,e,s){var c;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 a=n[0].target;if(o.type==="classifierNode"&&((c=s==null?void 0:s.context)!=null&&c.classified_id)){let d=s.context.classified_id,u=n.find(l=>l.sourceHandle===`source-${d}`);u?a=u.target:console.log(`No matching edge, falling back to first: ${a}`)}return ke(e,a)}async function Me(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 ct(o,e){o.sql`INSERT INTO messages (id, role, type, content, ts) VALUES (${e.id}, ${e.role}, ${e.type}, ${e.content}, ${e.ts})`}async function X(o){return o.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function dt(o){o.sql`DELETE FROM messages`}async function De(o){o.sql`CREATE TABLE IF NOT EXISTS context (
24
24
  ref TEXT PRIMARY KEY,
25
25
  domain TEXT NOT NULL,
26
26
  description TEXT NOT NULL,
@@ -28,14 +28,14 @@ ${$.text}`).join(`
28
28
  cycle INTEGER NOT NULL,
29
29
  meta TEXT,
30
30
  ts INTEGER NOT NULL
31
- )`}async function ne(o,e){let s=e.data??null,t=s!=null?Et(s):{data:null,truncated:!1},n=t.truncated?Zt(e.meta,{truncated:!0}):e.meta??null,l=e.ts??Date.now();o.sql`INSERT INTO context (ref, domain, description, data, cycle, meta, ts)
32
- VALUES (${e.ref}, ${e.domain}, ${e.description}, ${t.data}, ${e.cycle}, ${n}, ${l})
31
+ )`}async function ie(o,e){let s=e.data??null,t=s!=null?Qt(s):{data:null,truncated:!1},n=t.truncated?St(e.meta,{truncated:!0}):e.meta??null,a=e.ts??Date.now();o.sql`INSERT INTO context (ref, domain, description, data, cycle, meta, ts)
32
+ VALUES (${e.ref}, ${e.domain}, ${e.description}, ${t.data}, ${e.cycle}, ${n}, ${a})
33
33
  ON CONFLICT(ref) DO UPDATE SET
34
34
  domain = excluded.domain,
35
35
  description = excluded.description,
36
36
  data = excluded.data,
37
37
  cycle = excluded.cycle,
38
38
  meta = excluded.meta,
39
- ts = excluded.ts`}async function pt(o){return o.sql`SELECT ref, domain, description, cycle, meta, ts FROM context ORDER BY ts ASC`}async function 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 re(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 ut(o){o.sql`DELETE FROM context`}async function ce(o){await Fe(o),await Me(o)}var kt=Object.freeze({});async function Q(o,e){if(!e)return kt;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 l=await n.json();if(l.secrets)return Object.freeze(l.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 kt;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 l=await Promise.all(n.keys.map(async c=>{let d=await s.get(c.name);return d!==null?[c.name.slice(t.length),d]:null})),m={};for(let c of l){if(!c)continue;let[d,f]=c;d&&(m[d]=f)}return Object.freeze(m)}catch(n){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,err:n}),kt}}import{nanoid as As}from"nanoid";function Z(o){var n,l;let e=(n=o==null?void 0:o.flowData)==null?void 0:n.state,t=((e==null?void 0:e.nodes)??((l=o==null?void 0:o.flowData)==null?void 0:l.nodes)??[]).find(m=>m.type==="startNode");return t==null?void 0:t.data}async function mt(o,e){return typeof e.cycle=="number"&&Number.isFinite(e.cycle)?e.cycle+1:await le(o)+1}function yt(o,e,s,t,n){let l=G(Z(s));return{...e,memoryConfig:l,cycle:t,setContext:async c=>{await ne(o,c),await(n==null?void 0:n(c.ref))},getContextIndex:async()=>pt(o),getContextData:async c=>ie(o,c),getContext:async c=>ft(o,c),resolveContext:async c=>ae(o,c),pruneContext:async c=>re(o,c)}}function gt(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 ht=async(o,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),`${JSON.stringify(o)}`};import{nanoid as be}from"nanoid";async function De(o,e){var l,m;let s=o.id||o.name||"",[t,n]=s.split("::");if(!t||!n)return null;try{let d=(l=(await z(t,e)).metadata)==null?void 0:l.tenant,f=await tt(t,e),r=(m=o.state)==null?void 0:m.user,p={flowData:{...f,tenant:d,flowId:t,chatId:n},executedNodes:[],context:r?{user:r}:{}};return o.setState({...o.state,engineState:p}),p}catch(c){return console.error("Failed to initialize engine state:",c),null}}async function de(o,e,s,t){var n,l,m;try{let c=await e.json(),d=c.message;if(!d||typeof d!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let f=typeof c.userId=="string"?ot(c.userId):null;f&&!((n=o.state.user)!=null&&n.email)&&o.setState({...o.state,injectedUserId:f});let r=()=>{var T;return((T=o.state.user)==null?void 0:T.email)??f??o.state.injectedUserId??void 0},p=Date.now(),a=[],u=async()=>await X(o),i=async T=>{await ct(o,T)},g={id:be(),role:"user",type:"text",content:d,ts:Date.now()};await i(g);let h={onChangeState:T=>{o.setState({...o.state,engineState:T})},onServerEvent:async T=>{a.push(T)},onTelemetry:async T=>{var U,M,q,B,E,L;await ht({...T,userId:r(),tenant:((M=(U=o.state.engineState)==null?void 0:U.flowData)==null?void 0:M.tenant)||"",flowId:((B=(q=o.state.engineState)==null?void 0:q.flowData)==null?void 0:B.flowId)||"",sessionId:((L=(E=o.state.engineState)==null?void 0:E.flowData)==null?void 0:L.chatId)||""},s)},onError:T=>{o.setState({...o.state,error:T})}},w=async T=>{if(o.state.modelsCache&&o.state.modelsCache[T])return o.state.modelsCache[T];try{let{fetchOraModel:U}=await import("./oraApi-3JWDQQUE.js"),M=await U(T,s);return o.setState({...o.state,modelsCache:{...o.state.modelsCache||{},[T]:M}}),M}catch(U){throw console.error(`Error fetching model ${T}:`,U),U}},y=o.state.engineState;if(!y&&(y=await De(o,s),!y))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let x=(l=y==null?void 0:y.flowData)==null?void 0:l.tenant,C=await Q(s,x),N=G(Z(y)),$=typeof y.cycle=="number"?y.cycle:0;N.enabled&&($=await mt(o,y),y={...y,cycle:$},o.setState({...o.state,engineState:y})),o.skillRefCache||(o.skillRefCache=new Map);let R=yt(o,{env:s,ctx:t,conn:void 0,getMessages:u,setMessages:i,getOraModel:w,secrets:C,skillRefCache:o.skillRefCache},y,$);await lt(R,y,h)(d);let{tenant:k,flowId:D,chatId:A}=y.flowData??{};k&&D&&A&&t.waitUntil(gt(s,{id:`${D}::${A}`,tenant:k,flowId:D,sessionId:A,userId:r(),title:d.slice(0,120),turnTs:p,events:a})),(m=R.memoryConfig)!=null&&m.enabled&&R.memoryConfig.mode==="summarize"&&t&&t.waitUntil(rt(o,R,$)),o.setState({...o.state,lastUpdated:new Date});let j=(await u()).reverse().find(T=>T.role==="assistant");return new Response(JSON.stringify({answer:(j==null?void 0:j.content)||""}),{headers:{"content-type":"application/json"}})}catch(c){return new Response(JSON.stringify({error:c.message}),{status:500,headers:{"content-type":"application/json"}})}}async function pe(o){try{return await dt(o),await ut(o),o.skillRefCache&&o.skillRefCache.clear(),o.setState({...o.state,error:"",engineState:void 0,lastUpdated:new Date}),new Response(JSON.stringify({success:!0,messages:[]}),{headers:{"content-type":"application/json"}})}catch(e){return new Response(JSON.stringify({error:e.message}),{status:500,headers:{"content-type":"application/json"}})}}var fe=class extends Pe{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 X(this);return new Response(JSON.stringify(t),{headers:{"content-type":"application/json"}})}if(s.pathname.endsWith("/context")){let t={"content-type":"application/json","access-control-allow-origin":"*"};if(!e.headers.get("X-User-Payload"))return new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:t});let n=s.searchParams.get("ref");if(n){let m=await ft(this,n);return m?new Response(JSON.stringify({entry:m}),{headers:t}):new Response(JSON.stringify({error:"Not found"}),{status:404,headers:t})}let l=await pt(this);return new Response(JSON.stringify({entries:l}),{headers:t})}return e.method==="POST"&&s.pathname.endsWith("/message")?de(this,e,this.env,this.ctx):e.method==="DELETE"&&s.pathname.endsWith("/clear")?pe(this):new Response("Ready to assist.")}async onConnect(e,s){var a,u,i,g,h;let[t,n]=e.server.split("::"),m=(a=(await z(t,this.env)).metadata)==null?void 0:a.tenant;this.secrets=await Q(this.env,m),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 d=await tt(t,this.env);this.setState({...this.state,user:c||null,sessionId:n,engineState:{flowData:{...d,tenant:m,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 f=await X(this);P(e,b.SERVER_HISTORY,JSON.stringify({messages:f}));let p=(((u=d==null?void 0:d.state)==null?void 0:u.nodes)??(d==null?void 0:d.nodes)??[]).find(w=>w.type==="startNode");if(p){let w={allow_images:((i=p.data)==null?void 0:i.allow_images)??!1,allow_documents:((g=p.data)==null?void 0:g.allow_documents)??!1,greeting:(h=p.data)==null?void 0:h.greeting};P(e,b.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),l=s.substring(t+1);if(!n||!l)return;let c={[b.USER_MESSAGE]:d=>this.onUserMessage(e,d),[b.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[b.USER_AUTH]:d=>this.onUserAuth(e,d),[b.USER_IDENTITY]:d=>this.onUserIdentity(e,d)}[n];c&&await c(l)}async onUserMessage(e,s){var y,x,C,N,$;let t=Date.now(),n=[],l=async()=>await X(this),m=async R=>{await ct(this,R)},c=async R=>{if(this.state.modelsCache&&this.state.modelsCache[R])return this.state.modelsCache[R];try{let{fetchOraModel:k}=await import("./oraApi-3JWDQQUE.js"),D=await k(R,this.env);return this.setState({...this.state,modelsCache:{...this.state.modelsCache,[R]:D}}),D}catch(k){throw console.error(`Error fetching model ${R}:`,k),k}},d=et(s),f={id:Ue(),role:"user",type:"text",content:d.text,images:d.images,ts:Date.now()};await m(f);let r={onChangeState:R=>{this.setState({...this.state,engineState:R})},onServerEvent:async R=>{P(e,b.SERVER_EVENT,JSON.stringify(R)),n.push(R)},onTelemetry:async R=>{var k,D,A,F,j,T;await ht({...R,userId:this.resolveSessionUserId(),tenant:((D=(k=this.state.engineState)==null?void 0:k.flowData)==null?void 0:D.tenant)||"",flowId:((F=(A=this.state.engineState)==null?void 0:A.flowData)==null?void 0:F.flowId)||"",sessionId:((T=(j=this.state.engineState)==null?void 0:j.flowData)==null?void 0:T.chatId)||""},this.env)},onError:R=>{P(e,b.SERVER_ERROR,R),this.setState({...this.state,error:R})}};if(Object.keys(this.secrets).length===0){let R=(x=(y=this.state.engineState)==null?void 0:y.flowData)==null?void 0:x.tenant;R&&(this.secrets=await Q(this.env,R))}let p={...this.state.engineState};this.state.user&&!((C=p.context)!=null&&C.user)&&(p.context={...p.context||{},user:this.state.user});let a=G(Z(p)),u=typeof p.cycle=="number"?p.cycle:0;a.enabled&&(u=await mt(this,p),p.cycle=u,this.setState({...this.state,engineState:p}));let i=yt(this,{env:this.env,ctx:this.ctx,conn:e,getMessages:l,setMessages:m,getOraModel:c,secrets:this.secrets,userAuth:this.userAuth,user:this.state.user,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache},p,u,async R=>{P(e,b.SERVER_EVENT,JSON.stringify({type:"info:memory:updated",content:{ref:R}}))});await lt(i,p,r)(d);let{tenant:g,flowId:h,chatId:w}=p.flowData??{};g&&h&&w&&this.ctx.waitUntil(gt(this.env,{id:`${h}::${w}`,tenant:g,flowId:h,sessionId:w,userId:this.resolveSessionUserId(),title:(N=d.text)==null?void 0:N.slice(0,120),turnTs:t,events:n})),($=i.memoryConfig)!=null&&$.enabled&&i.memoryConfig.mode==="summarize"&&this.ctx&&this.ctx.waitUntil(rt(this,i,u)),this.setState({...this.state,lastUpdated:new Date})}async onUserIdentity(e,s){let t=ot(s);if(!t){P(e,b.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:t}),P(e,b.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,s){let t=bt(s);if(!t){P(e,b.SERVER_ERROR,"Invalid auth payload");return}let n=t.value.trim();n===""?delete this.userAuth[t.name]:this.userAuth[t.name]=t.value,P(e,b.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:t.name,set:n!==""}}))}async onClearHistory(e){await dt(this),await ut(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,lastUpdated:new Date}),e&&P(e,b.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await ce(this);let e=await X(this);`${JSON.stringify(e)}`}async onClose(e,s,t,n){console.log(`Session closed: ${this.state.sessionId} ${s} - ${t}`)}async onError(e){console.error("AgentDO encountered an error:",e)}};function mn(o){let e=o.state;if(!e)return null;let s=["startNode","answerNode"];for(let t of s)if(!e.nodes.some(l=>l.type===t))return!1;return e.nodes.find(t=>t.type==="startNode")}import{importSPKI as Le,jwtVerify as je}from"jose";function ue(o){let e={};if(!o)return e;let s=o.split(";");for(let t of s){let n=t.indexOf("=");if(n>-1){let l=t.slice(0,n).trim(),m=t.slice(n+1).trim();l&&(e[l]=decodeURIComponent(m))}}return e}async function J(o,e,s){let t=ue(o.headers.get("cookie")),n=new URL(o.url),l=t.access_token||n.searchParams.get("access_token"),m=await He(e,l);if(m.ok){let c=m.payload,d=typeof c.preferred_username=="string"?c.preferred_username.trim():"",f=typeof c.email=="string"?c.email.trim():"";return{id:c.sub,email:d||f,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}}return null}async function He(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
+ ts = excluded.ts`}async function ft(o){return o.sql`SELECT ref, domain, description, cycle, meta, ts FROM context ORDER BY ts ASC`}async function pt(o,e){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${e} LIMIT 1`[0]??null}async function ae(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 le(o,e){o.sql`DELETE FROM context WHERE domain = 'tool' AND cycle <= ${e}`}async function ce(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 ut(o){o.sql`DELETE FROM context`}async function de(o){await Me(o),await De(o)}async function mt(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 a=await Y(s,o),p={...e,flowData:{...a,tenant:e.flowData.tenant,flowId:s,chatId:e.flowData.chatId}},c=a==null?void 0:a.stateVersion,d=typeof c=="number"&&c!==((n=e.flowData)==null?void 0:n.stateVersion);return{engineState:p,refreshed:d}}catch(a){return console.error(`[flowRefresh] fetch failed for flow ${s}:`,a),{engineState:e,refreshed:!1}}}var kt=Object.freeze({});async function Z(o,e){if(!e)return kt;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 a=await n.json();if(a.secrets)return Object.freeze(a.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 kt;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 a=await Promise.all(n.keys.map(async c=>{let d=await s.get(c.name);return d!==null?[c.name.slice(t.length),d]:null})),p={};for(let c of a){if(!c)continue;let[d,u]=c;d&&(p[d]=u)}return Object.freeze(p)}catch(n){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,err:n}),kt}}import{nanoid as Ds}from"nanoid";function S(o){var n,a;let e=(n=o==null?void 0:o.flowData)==null?void 0:n.state,t=((e==null?void 0:e.nodes)??((a=o==null?void 0:o.flowData)==null?void 0:a.nodes)??[]).find(p=>p.type==="startNode");return t==null?void 0:t.data}async function yt(o,e){return typeof e.cycle=="number"&&Number.isFinite(e.cycle)?e.cycle+1:await ce(o)+1}function gt(o,e,s,t,n){let a=E(S(s));return{...e,memoryConfig:a,cycle:t,setContext:async c=>{await ie(o,c),await(n==null?void 0:n(c.ref))},getContextIndex:async()=>ft(o),getContextData:async c=>ae(o,c),getContext:async c=>pt(o,c),resolveContext:async c=>re(o,c),pruneContext:async c=>le(o,c)}}function ht(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 wt=async(o,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),`${JSON.stringify(o)}`};import{nanoid as be}from"nanoid";async function Pe(o,e){var a,p;let s=o.id||o.name||"",[t,n]=s.split("::");if(!t||!n)return null;try{let d=(a=(await z(t,e)).metadata)==null?void 0:a.tenant,u=await Y(t,e),l=(p=o.state)==null?void 0:p.user,f={flowData:{...u,tenant:d,flowId:t,chatId:n},executedNodes:[],context:l?{user:l}:{}};return o.setState({...o.state,engineState:f}),f}catch(c){return console.error("Failed to initialize engine state:",c),null}}async function fe(o,e,s,t){var n,a,p;try{let c=await e.json(),d=c.message;if(!d||typeof d!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let u=typeof c.userId=="string"?ot(c.userId):null;u&&!((n=o.state.user)!=null&&n.email)&&o.setState({...o.state,injectedUserId:u});let l=()=>{var N;return((N=o.state.user)==null?void 0:N.email)??u??o.state.injectedUserId??void 0},f=Date.now(),r=[],m=async()=>await X(o),i=async N=>{await ct(o,N)},g={id:be(),role:"user",type:"text",content:d,ts:Date.now()};await i(g);let h={onChangeState:N=>{o.setState({...o.state,engineState:N})},onServerEvent:async N=>{r.push(N)},onTelemetry:async N=>{var D,M,q,B,Q,L;await wt({...N,userId:l(),tenant:((M=(D=o.state.engineState)==null?void 0:D.flowData)==null?void 0:M.tenant)||"",flowId:((B=(q=o.state.engineState)==null?void 0:q.flowData)==null?void 0:B.flowId)||"",sessionId:((L=(Q=o.state.engineState)==null?void 0:Q.flowData)==null?void 0:L.chatId)||""},s)},onError:N=>{o.setState({...o.state,error:N})}},w=async N=>{if(o.state.modelsCache&&o.state.modelsCache[N])return o.state.modelsCache[N];try{let{fetchOraModel:D}=await import("./oraApi-YIJGMXX7.js"),M=await D(N,s);return o.setState({...o.state,modelsCache:{...o.state.modelsCache||{},[N]:M}}),M}catch(D){throw console.error(`Error fetching model ${N}:`,D),D}},y=o.state.engineState;if(y){let{engineState:N,refreshed:D}=await mt(s,y);y=N,D&&o.setState({...o.state,engineState:y,modelsCache:{}})}else if(y=await Pe(o,s),!y)return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let x=(a=y==null?void 0:y.flowData)==null?void 0:a.tenant,C=await Z(s,x),R=E(S(y)),k=typeof y.cycle=="number"?y.cycle:0;R.enabled&&(k=await yt(o,y),y={...y,cycle:k},o.setState({...o.state,engineState:y})),o.skillRefCache||(o.skillRefCache=new Map);let _=gt(o,{env:s,ctx:t,conn:void 0,getMessages:m,setMessages:i,getOraModel:w,secrets:C,skillRefCache:o.skillRefCache},y,k);await lt(_,y,h)(d);let{tenant:P,flowId:I,chatId:$}=y.flowData??{};P&&I&&$&&t.waitUntil(ht(s,{id:`${I}::${$}`,tenant:P,flowId:I,sessionId:$,userId:l(),title:d.slice(0,120),turnTs:f,events:r})),(p=_.memoryConfig)!=null&&p.enabled&&_.memoryConfig.mode==="summarize"&&t&&t.waitUntil(rt(o,_,k)),o.setState({...o.state,lastUpdated:new Date});let j=(await m()).reverse().find(N=>N.role==="assistant");return new Response(JSON.stringify({answer:(j==null?void 0:j.content)||""}),{headers:{"content-type":"application/json"}})}catch(c){return new Response(JSON.stringify({error:c.message}),{status:500,headers:{"content-type":"application/json"}})}}async function pe(o){try{return await dt(o),await ut(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 ue=class extends Ue{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 X(this);return new Response(JSON.stringify(t),{headers:{"content-type":"application/json"}})}if(s.pathname.endsWith("/context")){let t={"content-type":"application/json","access-control-allow-origin":"*"};if(!e.headers.get("X-User-Payload"))return new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:t});let n=s.searchParams.get("ref");if(n){let p=await pt(this,n);return p?new Response(JSON.stringify({entry:p}),{headers:t}):new Response(JSON.stringify({error:"Not found"}),{status:404,headers:t})}let a=await ft(this);return new Response(JSON.stringify({entries:a}),{headers:t})}return e.method==="POST"&&s.pathname.endsWith("/message")?fe(this,e,this.env,this.ctx):e.method==="DELETE"&&s.pathname.endsWith("/clear")?pe(this):new Response("Ready to assist.")}async onConnect(e,s){var r,m,i,g,h;let[t,n]=e.server.split("::"),p=(r=(await z(t,this.env)).metadata)==null?void 0:r.tenant;this.secrets=await Z(this.env,p),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 d=await Y(t,this.env);this.setState({...this.state,user:c||null,sessionId:n,engineState:{flowData:{...d,tenant:p,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 u=await X(this);U(e,b.SERVER_HISTORY,JSON.stringify({messages:u}));let f=(((m=d==null?void 0:d.state)==null?void 0:m.nodes)??(d==null?void 0:d.nodes)??[]).find(w=>w.type==="startNode");if(f){let w={allow_images:((i=f.data)==null?void 0:i.allow_images)??!1,allow_documents:((g=f.data)==null?void 0:g.allow_documents)??!1,greeting:(h=f.data)==null?void 0:h.greeting};U(e,b.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),a=s.substring(t+1);if(!n||!a)return;let c={[b.USER_MESSAGE]:d=>this.onUserMessage(e,d),[b.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[b.USER_AUTH]:d=>this.onUserAuth(e,d),[b.USER_IDENTITY]:d=>this.onUserIdentity(e,d)}[n];c&&await c(a)}async onUserMessage(e,s){var C,R,k,_,P;let t=Date.now(),n=[],a=async()=>await X(this),p=async I=>{await ct(this,I)},c=async I=>{if(this.state.modelsCache&&this.state.modelsCache[I])return this.state.modelsCache[I];try{let{fetchOraModel:$}=await import("./oraApi-YIJGMXX7.js"),A=await $(I,this.env);return this.setState({...this.state,modelsCache:{...this.state.modelsCache,[I]:A}}),A}catch($){throw console.error(`Error fetching model ${I}:`,$),$}},d=et(s),u={id:Le(),role:"user",type:"text",content:d.text,images:d.images,ts:Date.now()};await p(u);let l={onChangeState:I=>{this.setState({...this.state,engineState:I})},onServerEvent:async I=>{U(e,b.SERVER_EVENT,JSON.stringify(I)),n.push(I)},onTelemetry:async I=>{var $,A,j,N,D,M;await wt({...I,userId:this.resolveSessionUserId(),tenant:((A=($=this.state.engineState)==null?void 0:$.flowData)==null?void 0:A.tenant)||"",flowId:((N=(j=this.state.engineState)==null?void 0:j.flowData)==null?void 0:N.flowId)||"",sessionId:((M=(D=this.state.engineState)==null?void 0:D.flowData)==null?void 0:M.chatId)||""},this.env)},onError:I=>{U(e,b.SERVER_ERROR,I),this.setState({...this.state,error:I})}};if(Object.keys(this.secrets).length===0){let I=(R=(C=this.state.engineState)==null?void 0:C.flowData)==null?void 0:R.tenant;I&&(this.secrets=await Z(this.env,I))}let f={...this.state.engineState},{engineState:r,refreshed:m}=await mt(this.env,f);f=r,m&&this.setState({...this.state,engineState:f,modelsCache:{}}),this.state.user&&!((k=f.context)!=null&&k.user)&&(f.context={...f.context||{},user:this.state.user});let i=E(S(f)),g=typeof f.cycle=="number"?f.cycle:0;i.enabled&&(g=await yt(this,f),f.cycle=g,this.setState({...this.state,engineState:f}));let h=gt(this,{env:this.env,ctx:this.ctx,conn:e,getMessages:a,setMessages:p,getOraModel:c,secrets:this.secrets,userAuth:this.userAuth,user:this.state.user,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache},f,g,async I=>{U(e,b.SERVER_EVENT,JSON.stringify({type:"info:memory:updated",content:{ref:I}}))});await lt(h,f,l)(d);let{tenant:w,flowId:y,chatId:x}=f.flowData??{};w&&y&&x&&this.ctx.waitUntil(ht(this.env,{id:`${y}::${x}`,tenant:w,flowId:y,sessionId:x,userId:this.resolveSessionUserId(),title:(_=d.text)==null?void 0:_.slice(0,120),turnTs:t,events:n})),(P=h.memoryConfig)!=null&&P.enabled&&h.memoryConfig.mode==="summarize"&&this.ctx&&this.ctx.waitUntil(rt(this,h,g)),this.setState({...this.state,lastUpdated:new Date})}async onUserIdentity(e,s){let t=ot(s);if(!t){U(e,b.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:t}),U(e,b.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,s){let t=bt(s);if(!t){U(e,b.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,b.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:t.name,set:n!==""}}))}async onClearHistory(e){await dt(this),await ut(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,b.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await de(this);let e=await X(this);`${JSON.stringify(e)}`}async onClose(e,s,t,n){console.log(`Session closed: ${this.state.sessionId} ${s} - ${t}`)}async onError(e){console.error("AgentDO encountered an error:",e)}};function xn(o){let e=o.state;if(!e)return null;let s=["startNode","answerNode"];for(let t of s)if(!e.nodes.some(a=>a.type===t))return!1;return e.nodes.find(t=>t.type==="startNode")}import{importSPKI as je,jwtVerify as He}from"jose";function me(o){let e={};if(!o)return e;let s=o.split(";");for(let t of s){let n=t.indexOf("=");if(n>-1){let a=t.slice(0,n).trim(),p=t.slice(n+1).trim();a&&(e[a]=decodeURIComponent(p))}}return e}async function J(o,e,s){let t=me(o.headers.get("cookie")),n=new URL(o.url),a=t.access_token||n.searchParams.get("access_token"),p=await Ve(e,a);if(p.ok){let c=p.payload,d=typeof c.preferred_username=="string"?c.preferred_username.trim():"",u=typeof c.email=="string"?c.email.trim():"";return{id:c.sub,email:d||u,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}}return null}async function Ve(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 Le(s,"RS256");try{let{payload:n,protectedHeader:l}=await je(e,t);return{ok:!0,payload:n,protectedHeader:l}}catch(n){return console.error("JWT verification failed:",n),{ok:!1,payload:null,protectedHeader:null}}}async function Rn(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 me}from"agents";var Ve=/^[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 On(o,e,s){var n,l,m,c;let t=new URL(o.url);if(t.pathname.startsWith("/a/")){let d=t.pathname.split("/"),f=d[2],r=d[3];try{if(!f)return Response.redirect(new URL("/",t.origin).toString(),302);let p;try{p=await z(f,e)}catch{return new Response("Flow not found",{status:404})}if(!p.metadata||((n=p.metadata)==null?void 0:n.status)!=="active")return new Response("NO chat",{status:404});if(((l=p.metadata)==null?void 0:l.visibility)==="private"&&!await J(o,e,s)){let u=new URL("/login",t.origin);return u.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(u.toString(),302)}if(!r){let a=crypto.randomUUID(),u=new URL(`/a/${f}/${a}`,t.origin);return Response.redirect(u.toString(),302)}if(!Ve.test(r))return new Response("Id del chat no v\xE1lido",{status:400})}catch(p){return console.error("Error accessing flow KV:",p),new Response("Flow error",{status:500})}}if(t.pathname.startsWith("/api/agent/flow")){let d=t.pathname.split("/"),f=d[4],r=d[5],p=`${f}::${r}`;try{let a=await J(o,e,s);if(!a){let w=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${w}) \u2014 Composio connections from tool editor will not apply`)}let u=new Headers(o.headers);a&&u.set("X-User-Payload",JSON.stringify(a));let i=new Request(o,{headers:u});return(await me(e.AGENT,p)).fetch(i)}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("/"),f=d[4],r=d[5];if(!f||!r)return new Response("Missing flowId or sessionId",{status:400});let p=o.headers.get("Authorization")||t.searchParams.get("authorization");if(!p)return new Response("Missing Authorization header",{status:401});try{let a=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${f}`,i=await(await fetch(a,{method:"GET",headers:{Authorization:p}})).json();if(((m=i.payload)==null?void 0:m.flowId)!==f)return console.error("FlowId mismatch:",(c=i.payload)==null?void 0:c.flowId,"!==",f),new Response("Validation error",{status:403});let g=`${f}::${r}`,h=await J(o,e,s);if(!h){let N=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${N}) \u2014 Composio connections from tool editor will not apply`)}let w=new Headers(o.headers);h&&w.set("X-User-Payload",JSON.stringify(h));let y=new Request(o,{headers:w});return(await me(e.AGENT,g)).fetch(y)}catch(a){return console.error("Error in /api/ora/connect:",a),new Response("Internal error",{status:500})}}}async function kn(o,e,s){let t=new URL(o.url),n=o.method;if(!t.pathname.startsWith("/api/instances"))return;let l=await J(o,e,s);if(!l)return new Response("Unauthorized",{status:401});let m=e.HX_CORE_URL,c=e.HX_API_KEY;if(!m||!c)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let f=t.pathname.slice("/api/instances".length);f.startsWith("/")&&(f=f.slice(1)),f.endsWith("/")&&(f=f.slice(0,-1));let r="/ora/instances";f&&(r+=`/${f}`);let p=m.endsWith("/")?m.slice(0,-1):m,a=new URL(`${p}${r}`);t.searchParams.forEach((g,h)=>{a.searchParams.set(h,g)}),n==="GET"&&!f&&a.searchParams.set("filter_user_id",l.email);let u=new Headers;u.set("Authorization",c),u.set("Content-Type","application/json"),u.set("X-User-Payload",JSON.stringify(l));let i={method:n,headers:u};if(["POST","PATCH","PUT"].includes(n))try{i.body=await o.text()}catch(g){console.error("Error reading request body:",g)}try{let g=await fetch(a.toString(),i),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 Mn(o,e,s){let t=new URL(o.url);if(o.method==="POST"&&t.pathname==="/auth/login")try{let n=await o.formData(),l=n.get("username"),m=n.get("password"),c=n.get("nextURL")||"/";if(!l||!m)return new Response("Missing username or password",{status:400});let d=new URLSearchParams;d.append("username",l),d.append("password",m),d.append("grant_type","password"),d.append("client_id",e.KC_CLIENT_ID),d.append("client_secret",e.KC_CLIENT_SECRET);let f=await fetch(`${e.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:d});if(!f.ok)return new Response("Unauthorized",{status:401});let r=await f.json(),p=new Response(null,{status:302,headers:{Location:c}}),a=(u,i,g)=>{p.headers.append("Set-Cookie",`${u}=${i}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${g}`)};return r.access_token&&a("access_token",r.access_token,r.expires_in),r.refresh_token&&a("refresh_token",r.refresh_token,r.refresh_expires_in||3600*24*30),r.id_token&&a("id_token",r.id_token,r.expires_in),p}catch(n){return console.error("Auth error:",n),new Response("Internal Server Error",{status:500})}if(t.pathname==="/auth/logout"){let n=new Response(null,{status:302,headers:{Location:"/login"}}),l=m=>{n.headers.append("Set-Cookie",`${m}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return l("access_token"),l("refresh_token"),l("id_token"),n}if(t.pathname.startsWith("/s/")){let n=await J(o,e,s);if(!n){let l=new URL("/login",t.origin);return l.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(l.toString(),302)}return{user:n}}}export{fe as AgentDO,Qe as GENERATION_PARAM_KEYS,Se as GENERATION_PRESETS,Ge as MAX_USER_IDENTITY_LENGTH,mo as MODEL_REGISTRY_SNAPSHOT,Y as NodeType,Ze as PRESET_PARAM_KEYS,lo as REASONING_EFFORT_LEVELS,qt as TOOL_REGISTRY_SNAPSHOT,eo as applyPresetToOverrides,Vt as buildReasoningProviderOptions,Xe as buildUrl,ut as clearAllContext,dt as clearAllMessages,qe as convertTempMessure,re as deleteContextToolsUpToCycle,ve as deriveParamSupport,Mt as embedText,ce as ensureAgentTables,Me as ensureContextTable,Fe as ensureMessagesTable,X as getAllMessages,ft as getContext,ie as getContextData,pt as getContextIndex,Ee as getDefaultOutVars,st as getEffectiveOutVars,le as getMaxContextCycle,yo as getModelEntry,On as handleAgentsRoutes,Mn as handleAuthRoutes,Rn as handleCommonRoutes,kn as handleIntancesRoutes,ze as hashText,Jt as jsonSchemaToZod,v as logc,b as messageTypes,oo as normalizeEffectiveParams,fo as normalizeModelEntry,co as normalizeReasoning,no as openAiReasoningParamSupport,so as openAiStandardParamSupport,ue as parseCookies,bt as parseUserAuth,et as parseUserMessage,Ut as pickNodeOverrides,po as reasoningEffortLevels,jt as reasoningExposable,uo as registerProvider,ae as resolveContextRef,at as resolveModelById,nt as resolveOutVarRef,to as resolvePreset,Ht as resolveReasoningEffort,Dt as resolveTemplate,Ke as safeParseJSON,ot as sanitizeUserIdentity,ht as sendEvent,P as serverSend,ne as setContext,ct as setMessage,lt as startEngine,ro as stripUnsupportedFromNodeData,Je as tempTool,Lt as toStreamTextSettings,We as twitter,mn as validateFlowStart,Ye as vectorize,He as verifyToken,J as verifyUser,Be as walkPath,ao as workersAiParamSupport,io as xaiParamSupport};
41
+ -----END PUBLIC KEY-----`,t=await je(s,"RS256");try{let{payload:n,protectedHeader:a}=await He(e,t);return{ok:!0,payload:n,protectedHeader:a}}catch(n){return console.error("JWT verification failed:",n),{ok:!1,payload:null,protectedHeader:null}}}async function On(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 ye}from"agents";var qe=/^[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 An(o,e,s){var n,a,p,c;let t=new URL(o.url);if(t.pathname.startsWith("/a/")){let d=t.pathname.split("/"),u=d[2],l=d[3];try{if(!u)return Response.redirect(new URL("/",t.origin).toString(),302);let f;try{f=await z(u,e)}catch{return new Response("Flow not found",{status:404})}if(!f.metadata||((n=f.metadata)==null?void 0:n.status)!=="active")return new Response("NO chat",{status:404});if(((a=f.metadata)==null?void 0:a.visibility)==="private"&&!await J(o,e,s)){let m=new URL("/login",t.origin);return m.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(m.toString(),302)}if(!l){let r=crypto.randomUUID(),m=new URL(`/a/${u}/${r}`,t.origin);return Response.redirect(m.toString(),302)}if(!qe.test(l))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("/"),u=d[4],l=d[5],f=`${u}::${l}`;try{let r=await J(o,e,s);if(!r){let w=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${w}) \u2014 Composio connections from tool editor will not apply`)}let m=new Headers(o.headers);r&&m.set("X-User-Payload",JSON.stringify(r));let i=new Request(o,{headers:m});return(await ye(e.AGENT,f)).fetch(i)}catch(r){return console.error("Error accessing agent:",r),new Response("Agent error",{status:500})}}if(t.pathname.startsWith("/api/ora/connect")){let d=t.pathname.split("/"),u=d[4],l=d[5];if(!u||!l)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 r=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${u}`,i=await(await fetch(r,{method:"GET",headers:{Authorization:f}})).json();if(((p=i.payload)==null?void 0:p.flowId)!==u)return console.error("FlowId mismatch:",(c=i.payload)==null?void 0:c.flowId,"!==",u),new Response("Validation error",{status:403});let g=`${u}::${l}`,h=await J(o,e,s);if(!h){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 w=new Headers(o.headers);h&&w.set("X-User-Payload",JSON.stringify(h));let y=new Request(o,{headers:w});return(await ye(e.AGENT,g)).fetch(y)}catch(r){return console.error("Error in /api/ora/connect:",r),new Response("Internal error",{status:500})}}}async function bn(o,e,s){let t=new URL(o.url),n=o.method;if(!t.pathname.startsWith("/api/instances"))return;let a=await J(o,e,s);if(!a)return new Response("Unauthorized",{status:401});let p=e.HX_CORE_URL,c=e.HX_API_KEY;if(!p||!c)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let u=t.pathname.slice("/api/instances".length);u.startsWith("/")&&(u=u.slice(1)),u.endsWith("/")&&(u=u.slice(0,-1));let l="/ora/instances";u&&(l+=`/${u}`);let f=p.endsWith("/")?p.slice(0,-1):p,r=new URL(`${f}${l}`);t.searchParams.forEach((g,h)=>{r.searchParams.set(h,g)}),n==="GET"&&!u&&r.searchParams.set("filter_user_id",a.email);let m=new Headers;m.set("Authorization",c),m.set("Content-Type","application/json"),m.set("X-User-Payload",JSON.stringify(a));let i={method:n,headers:m};if(["POST","PATCH","PUT"].includes(n))try{i.body=await o.text()}catch(g){console.error("Error reading request body:",g)}try{let g=await fetch(r.toString(),i),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 Ln(o,e,s){let t=new URL(o.url);if(o.method==="POST"&&t.pathname==="/auth/login")try{let n=await o.formData(),a=n.get("username"),p=n.get("password"),c=n.get("nextURL")||"/";if(!a||!p)return new Response("Missing username or password",{status:400});let d=new URLSearchParams;d.append("username",a),d.append("password",p),d.append("grant_type","password"),d.append("client_id",e.KC_CLIENT_ID),d.append("client_secret",e.KC_CLIENT_SECRET);let u=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(!u.ok)return new Response("Unauthorized",{status:401});let l=await u.json(),f=new Response(null,{status:302,headers:{Location:c}}),r=(m,i,g)=>{f.headers.append("Set-Cookie",`${m}=${i}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${g}`)};return l.access_token&&r("access_token",l.access_token,l.expires_in),l.refresh_token&&r("refresh_token",l.refresh_token,l.refresh_expires_in||3600*24*30),l.id_token&&r("id_token",l.id_token,l.expires_in),f}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"}}),a=p=>{n.headers.append("Set-Cookie",`${p}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return a("access_token"),a("refresh_token"),a("id_token"),n}if(t.pathname.startsWith("/s/")){let n=await J(o,e,s);if(!n){let a=new URL("/login",t.origin);return a.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(a.toString(),302)}return{user:n}}}export{ue as AgentDO,Ze as GENERATION_PARAM_KEYS,ve as GENERATION_PRESETS,Ee as MAX_USER_IDENTITY_LENGTH,yo as MODEL_REGISTRY_SNAPSHOT,G as NodeType,Se as PRESET_PARAM_KEYS,co as REASONING_EFFORT_LEVELS,Jt as TOOL_REGISTRY_SNAPSHOT,oo as applyPresetToOverrides,qt as buildReasoningProviderOptions,We as buildUrl,ut as clearAllContext,dt as clearAllMessages,Je as convertTempMessure,le as deleteContextToolsUpToCycle,to as deriveParamSupport,Dt as embedText,de as ensureAgentTables,De as ensureContextTable,Me as ensureMessagesTable,X as getAllMessages,pt as getContext,ae as getContextData,ft as getContextIndex,Qe as getDefaultOutVars,st as getEffectiveOutVars,ce as getMaxContextCycle,go as getModelEntry,An as handleAgentsRoutes,Ln as handleAuthRoutes,On as handleCommonRoutes,bn as handleIntancesRoutes,Ye as hashText,Kt as jsonSchemaToZod,tt as logc,b as messageTypes,so as normalizeEffectiveParams,uo as normalizeModelEntry,fo as normalizeReasoning,io as openAiReasoningParamSupport,no as openAiStandardParamSupport,me as parseCookies,bt as parseUserAuth,et as parseUserMessage,Lt as pickNodeOverrides,po as reasoningEffortLevels,Ht as reasoningExposable,mo as registerProvider,re as resolveContextRef,at as resolveModelById,nt as resolveOutVarRef,eo as resolvePreset,Vt as resolveReasoningEffort,Pt as resolveTemplate,Xe as safeParseJSON,ot as sanitizeUserIdentity,wt as sendEvent,U as serverSend,ie as setContext,ct as setMessage,lt as startEngine,lo as stripUnsupportedFromNodeData,Ke as tempTool,jt as toStreamTextSettings,ze as twitter,xn as validateFlowStart,Ge as vectorize,Ve as verifyToken,J as verifyUser,Be as walkPath,ro as workersAiParamSupport,ao as xaiParamSupport};
@@ -1 +1 @@
1
- import{a,b,c}from"./chunk-YHXUBVN2.js";import"./chunk-6BYZCJPP.js";export{b as fetchOraModel,c as fetchSkillRef,a as fetchToolDefs};
1
+ import{a,b,c}from"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";export{b as fetchOraModel,c as fetchSkillRef,a as fetchToolDefs};
@@ -1 +1 @@
1
- import{k as a}from"./chunk-57TCP6J4.js";import"./chunk-GRZ6ZRHM.js";import"./chunk-6BYZCJPP.js";import{tool as i}from"ai";import{z as m}from"zod";function y(r,c,l,t){return i({description:"Retrieve full stored data for a working-memory reference from a prior tool call or summary. Use the ref from the ## Working memory block.",inputSchema:m.object({reference:m.string().describe("The memory reference key, e.g. tool:myTool:abc123")}),execute:async({reference:o})=>{var n;let e=await((n=r.resolveContext)==null?void 0:n.call(r,o))??null;if(!e||e.data==null)return t==null||t({type:"warn:memory:recallMiss",content:{reference:o}}),{error:`No memory found for reference: ${o}`};if(a(e.meta).truncated===!0)return{ref:e.ref,truncated:!0,partial:e.data};try{return JSON.parse(e.data)}catch{return e.data}}})}export{y as recall};
1
+ import{k as a}from"./chunk-57TCP6J4.js";import"./chunk-GRZ6ZRHM.js";import"./chunk-3TXHFKDN.js";import{tool as i}from"ai";import{z as m}from"zod";function y(t,l,c,r){return i({description:"Retrieve full stored data for a working-memory reference from a prior tool call or summary. Use the ref from the ## Working memory block.",inputSchema:m.object({reference:m.string().describe("The memory reference key, e.g. tool:myTool:abc123")}),execute:async({reference:o})=>{var n;let e=await((n=t.resolveContext)==null?void 0:n.call(t,o))??null;if(!e||e.data==null)return r==null||r({type:"warn:memory:recallMiss",content:{reference:o}}),{error:`No memory found for reference: ${o}`};if(a(e.meta).truncated===!0)return{ref:e.ref,truncated:!0,partial:e.data};try{return JSON.parse(e.data)}catch{return e.data}}})}export{y as recall};
@@ -0,0 +1 @@
1
+ export declare function handleAgentsRoutes(request: Request, env: Env, ctx: ExecutionContext): Promise<Response | undefined>;
@@ -0,0 +1 @@
1
+ export declare function handleAuthRoutes(request: Request, env: Env, ctx: ExecutionContext): Promise<Response | any>;
@@ -0,0 +1 @@
1
+ export declare function handleCommonRoutes(request: Request, env: Env, ctx: ExecutionContext): Promise<Response | undefined>;
@@ -0,0 +1 @@
1
+ export declare function handleComposioRoutes(request: Request, _env: Env, _ctx: ExecutionContext): Response | null;
@@ -0,0 +1 @@
1
+ export declare function handleIntancesRoutes(request: Request, env: Env, ctx: ExecutionContext): Promise<Response | undefined>;
@@ -0,0 +1,80 @@
1
+ import { Agent, type Connection, type ConnectionContext, type WSMessage } from 'agents';
2
+ import type { UserInterface } from 'lib/common/types/user-types';
3
+ import { type Message } from '../../common/types/agent-types';
4
+ import type { ContextIndexEntry, ContextRow, ContextUpsertInput, MemoryConfig } from '../../common/types/memory-types';
5
+ import { type FlowEngineState } from '../logic/FlowEngine';
6
+ import type { ComposioSessionMeta } from '../utils/composio';
7
+ import { type SecretsMap } from '../utils/secrets';
8
+ export interface SessionEnv {
9
+ env?: Env;
10
+ ctx?: DurableObjectState;
11
+ conn?: Connection;
12
+ getMessages?: () => Promise<Message[]>;
13
+ setMessages?: (msg: Message) => Promise<void>;
14
+ getOraModel?: (modelId: string) => Promise<any>;
15
+ memoryConfig?: MemoryConfig;
16
+ cycle?: number;
17
+ setContext?: (row: ContextUpsertInput) => Promise<void>;
18
+ getContextIndex?: () => Promise<ContextIndexEntry[]>;
19
+ getContextData?: (ref: string) => Promise<string | null>;
20
+ getContext?: (ref: string) => Promise<ContextRow | null>;
21
+ resolveContext?: (ref: string) => Promise<ContextRow | null>;
22
+ pruneContext?: (upToCycle: number) => Promise<void>;
23
+ /** Tenant-scoped secrets resolved at session boot. Server-only — never copy into engineState or any client-bound event. */
24
+ secrets?: SecretsMap;
25
+ /** End-user-supplied ephemeral credentials sent live over WebSocket (`AUT`). DO memory only — never persisted, never copied into engineState/state/telemetry, masked in events. Resolved by `{{ auth.NAME }}`. */
26
+ userAuth?: SecretsMap;
27
+ /** Custom tool definitions for the tenant, lazy-loaded on first custom-tool reference and cached for the session. Keyed by row.id. */
28
+ toolDefs?: Record<string, any>;
29
+ /** In-memory cache for skill references fetched during this session. Keyed by toolId:refName. */
30
+ skillRefCache?: Map<string, string>;
31
+ /** Composio session metadata keyed by composio tool row id — reused within the agent chat session. */
32
+ composioSessions?: Record<string, ComposioSessionMeta>;
33
+ /** Logged-in user from the WebSocket upgrade (fallback when engineState.context.user is missing). */
34
+ user?: UserInterface;
35
+ /** Origin derived from the WebSocket upgrade request (preferred over ORA_PUBLIC_URL for callbacks). */
36
+ publicOrigin?: string;
37
+ }
38
+ export type { ComposioSessionMeta };
39
+ export interface State {
40
+ user: UserInterface | undefined;
41
+ /** Client-supplied identity fallback when no JWT user (via `UID` frame or HTTP body). */
42
+ injectedUserId?: string | null;
43
+ sessionId: string | null;
44
+ lastUpdated: Date | null;
45
+ engineState?: FlowEngineState;
46
+ error?: string;
47
+ modelsCache?: Record<string, any>;
48
+ }
49
+ export declare class AgentDO extends Agent<Env, State> {
50
+ initialState: State;
51
+ /** JWT email wins; explicit client identity is fallback only. */
52
+ private resolveSessionUserId;
53
+ private secrets;
54
+ private userAuth;
55
+ /** Composio tool-router session metadata keyed by composio tool row id — DO memory only. */
56
+ private composioSessions;
57
+ /** In-memory cache for skill references fetched during this session — DO memory only. */
58
+ private skillRefCache;
59
+ /** Public origin from the active socket upgrade (used for OAuth callback URLs). */
60
+ private publicOrigin?;
61
+ onRequest(request: Request): Promise<Response>;
62
+ onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
63
+ onMessage(connection: Connection, message: WSMessage): Promise<void>;
64
+ onUserMessage(connection: Connection, message: string): Promise<void>;
65
+ /**
66
+ * Store a client-supplied session identity in persisted DO state.
67
+ * Used as `sessions.userId` fallback when no JWT user is present; JWT always wins.
68
+ */
69
+ onUserIdentity(connection: Connection, content: string): Promise<void>;
70
+ /**
71
+ * Store an end-user-supplied runtime credential in DO memory only.
72
+ * MUST NOT persist to SQL/chat history, touch this.state, or start the engine.
73
+ * Empty value clears that name. ACK carries the NAME only — never the value.
74
+ */
75
+ onUserAuth(connection: Connection, content: string): Promise<void>;
76
+ onClearHistory(connection?: Connection): Promise<void>;
77
+ onStart(): Promise<void>;
78
+ onClose(connection: Connection, code: number, reason: string, wasClean: boolean): Promise<void>;
79
+ onError(error: unknown): Promise<void>;
80
+ }
@@ -0,0 +1,2 @@
1
+ export declare function handleAgentMessage(agent: any, request: Request, env: Env, ctx: DurableObjectState): Promise<Response>;
2
+ export declare function handleClearHistory(agent: any): Promise<Response>;
@@ -0,0 +1,38 @@
1
+ import { NodeType } from '../../common/types/node-types';
2
+ import { type UserMessagePayload } from '../../common/types/ws-message';
3
+ import type { SessionEnv } from '../core/AgentDO';
4
+ import type { FlowData } from '../types/node';
5
+ import type { TelemetryEvent } from '../utils/telemetry';
6
+ export type FlowEngine = (input?: string | UserMessagePayload) => Promise<void>;
7
+ export interface ExecutedNode {
8
+ id: string;
9
+ type: NodeType;
10
+ label?: string;
11
+ }
12
+ export interface FlowEngineState {
13
+ flowData?: FlowData;
14
+ executedNodes: ExecutedNode[];
15
+ context?: Record<string, any>;
16
+ results?: Record<string, any>;
17
+ lastNodeId?: string;
18
+ lastUserMessage?: string;
19
+ /** Monotonic flow-run counter for session context memory. */
20
+ cycle?: number;
21
+ tokenUsage?: {
22
+ promptTokens: number;
23
+ completionTokens: number;
24
+ totalTokens: number;
25
+ };
26
+ }
27
+ export interface FlowEngineEvent {
28
+ type: string;
29
+ content: any;
30
+ timestamp?: number;
31
+ }
32
+ export interface FlowEngineCallbacks {
33
+ onChangeState: (state: FlowEngineState) => void;
34
+ onServerEvent: (event: FlowEngineEvent) => void;
35
+ onTelemetry: (event: TelemetryEvent) => void;
36
+ onError: (error: string) => void;
37
+ }
38
+ export declare function startEngine(sessionEnv: SessionEnv, state: FlowEngineState, callbacks?: FlowEngineCallbacks): FlowEngine;
@@ -0,0 +1,2 @@
1
+ import type { FlowEngineState } from '../FlowEngine';
2
+ export declare function resolveFiles(node: any, engineState: FlowEngineState): string;
@@ -0,0 +1,5 @@
1
+ import type { FlowEngineState } from '../FlowEngine';
2
+ export declare function resolveImages(node: any, engineState: FlowEngineState): {
3
+ mimeType: string;
4
+ data: string;
5
+ }[];
@@ -0,0 +1,13 @@
1
+ import type { Connection } from "agents";
2
+ import type { MessageType } from "../../common/types/agent-types";
3
+ /**
4
+ * Sends a message to the client over the WebSocket connection.
5
+ *
6
+ * This function formats the message as "type::content" and sends it via the provided connection.
7
+ * It is the primary mechanism for server-to-client communication in the agent system.
8
+ *
9
+ * @param connection - The WebSocket connection instance to send the message over
10
+ * @param type - The message type from the MessageType enum, used to categorize the message
11
+ * @param content - The message content as a string (typically JSON.stringify'd data)
12
+ */
13
+ export declare const serverSend: (connection: Connection, type: MessageType, content: string) => void;
@@ -0,0 +1,4 @@
1
+ import type { SessionEnv } from '../core/AgentDO';
2
+ import type { FlowEngineEvent, FlowEngineState } from '../logic/FlowEngine';
3
+ import type { TelemetryEvent } from '../utils/telemetry';
4
+ export default function answerNodeRunner(sessionEnv: SessionEnv, node: any, engineState: FlowEngineState, onServerEvent?: (event: FlowEngineEvent) => void, onResult?: (key: string, result: any) => void, onChangeState?: (state: FlowEngineState) => void, onTelemetry?: (event: TelemetryEvent) => void): Promise<void>;
@@ -0,0 +1,4 @@
1
+ import type { SessionEnv } from '../core/AgentDO';
2
+ import type { FlowEngineEvent, FlowEngineState } from '../logic/FlowEngine';
3
+ import type { TelemetryEvent } from '../utils/telemetry';
4
+ export default function apiNodeRunner(sessionEnv: SessionEnv, node: any, engineState: FlowEngineState, onServerEvent?: (event: FlowEngineEvent) => void, onResult?: (key: string, result: any) => void, onChangeState?: (state: FlowEngineState) => void, onTelemetry?: (event: TelemetryEvent) => void): Promise<void>;
@@ -0,0 +1,6 @@
1
+ import type { SessionEnv } from '../core/AgentDO';
2
+ import type { FlowEngineEvent, FlowEngineState } from '../logic/FlowEngine';
3
+ export default function classifierNodeRunner(sessionEnv: SessionEnv, node: any, engineState: FlowEngineState, onServerEvent?: (event: FlowEngineEvent) => void, onResult?: (key: string, result: any) => void, onChangeState?: (state: FlowEngineState) => void, onTelemetry?: (event: {
4
+ type: string;
5
+ payload: any;
6
+ }) => void): Promise<void>;
@@ -0,0 +1,6 @@
1
+ import type { SessionEnv } from '../core/AgentDO';
2
+ import type { FlowEngineEvent, FlowEngineState } from '../logic/FlowEngine';
3
+ export default function llmNodeRunner(sessionEnv: SessionEnv, node: any, engineState: FlowEngineState, onServerEvent?: (event: FlowEngineEvent) => void, onResult?: (key: string, result: any) => void, onChangeState?: (state: FlowEngineState) => void, onTelemetry?: (event: {
4
+ type: string;
5
+ payload: any;
6
+ }) => void): Promise<void>;
@@ -0,0 +1,4 @@
1
+ import type { SessionEnv } from '../core/AgentDO';
2
+ import type { FlowEngineEvent, FlowEngineState } from '../logic/FlowEngine';
3
+ import type { TelemetryEvent } from '../utils/telemetry';
4
+ export default function memoNodeRunner(sessionEnv: SessionEnv, node: any, engineState: FlowEngineState, onServerEvent?: (event: FlowEngineEvent) => void, onResult?: (key: string, result: any) => void, onChangeState?: (state: FlowEngineState) => void, onTelemetry?: (event: TelemetryEvent) => void): Promise<void>;
@@ -0,0 +1,4 @@
1
+ import type { SessionEnv } from '../core/AgentDO';
2
+ import type { FlowEngineEvent, FlowEngineState } from '../logic/FlowEngine';
3
+ import type { TelemetryEvent } from '../utils/telemetry';
4
+ export default function startNodeRunner(sessionEnv: SessionEnv, node: any, engineState: FlowEngineState, onServerEvent?: (event: FlowEngineEvent) => void, onResult?: (key: string, result: any) => void, onChangeState?: (state: FlowEngineState) => void, onTelemetry?: (event: TelemetryEvent) => void): Promise<void>;