@hugex/ai 2.9.19 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/chunk-K4MP63XM.js +3 -0
- package/dist/{chunk-YJQNSODK.js → chunk-UBNZUUTD.js} +1 -1
- package/dist/client.js +1 -1
- package/dist/common/types/var-scope.d.ts +43 -0
- package/dist/common/utils/flowScope.d.ts +16 -0
- package/dist/common/utils/outVars.d.ts +6 -0
- package/dist/common/utils/templateUtils.d.ts +22 -4
- package/dist/common.d.ts +3 -1
- package/dist/common.js +1 -1
- package/dist/httpTool-LSNJKMPR.js +1 -0
- package/dist/index.js +16 -16
- package/dist/server/core/AgentDO.d.ts +1 -3
- package/dist/server/core/agentTurn.d.ts +1 -1
- package/dist/server/types/node.d.ts +1 -0
- package/dist/server/utils/oraTriggers.d.ts +3 -0
- package/package.json +1 -1
- package/dist/chunk-ZX5BWOUG.js +0 -3
- package/dist/common/types/var-mapping.d.ts +0 -29
- package/dist/httpTool-F3UYG6WX.js +0 -1
- /package/dist/{chunk-76OHKISD.js → chunk-E7BCWUTG.js} +0 -0
package/README.md
CHANGED
|
@@ -65,10 +65,10 @@ Design-time node data (configured in Agent Design panels):
|
|
|
65
65
|
| Node | Key data |
|
|
66
66
|
|---|---|
|
|
67
67
|
| **Start** | `greeting`, `allow_images`, `allow_documents`, `memory_*` toggles |
|
|
68
|
-
| **LLM** | `template`, `model`, `tools`, `
|
|
68
|
+
| **LLM** | `template`, `model`, `tools`, `attachments`, `outVars` |
|
|
69
69
|
| **Memo** | `rag_id`, `query_key`, `topk` |
|
|
70
70
|
| **Classifier** | `input_variable`, `items[]` |
|
|
71
|
-
| **API** | `url`, `method`, `headers`, `body`, `
|
|
71
|
+
| **API** | `url`, `method`, `headers`, `body`, `outVars` |
|
|
72
72
|
| **Answer** | Required flow terminus |
|
|
73
73
|
|
|
74
74
|
Rules: exactly one Start, at least one Answer, all paths connected.
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var g=(a=>(a.START_NODE="startNode",a.CLASSIFIER_NODE="classifierNode",a.MEMO_NODE="memoNode",a.LLM_NODE="llmNode",a.ANSWER_NODE="answerNode",a.API_NODE="apiNode",a.TOOL_NODE="toolNode",a))(g||{});var b=/^[a-zA-Z][a-zA-Z0-9_]*$/;function m(e){let t=e==null?void 0:e.inputs;if(!Array.isArray(t))return[];let n=[],o=new Set;for(let r of t){let s=typeof(r==null?void 0:r.name)=="string"?r.name.trim():"";if(!s||!b.test(s)||o.has(s))continue;o.add(s);let i=P.includes(r==null?void 0:r.type)?r.type:"string";n.push({name:s,type:i,required:(r==null?void 0:r.required)===!0,default:(r==null?void 0:r.default)??void 0})}return n}function A(e,t){let n=e.label||e.name;switch(e.type){case"number":{let o=typeof t=="number"?t:Number(String(t).trim());return Number.isFinite(o)?{value:o}:{error:`"${n}" must be a number`}}case"boolean":{if(typeof t=="boolean")return{value:t};let o=String(t).trim().toLowerCase();return["true","1","yes","si","s\xED"].includes(o)?{value:!0}:["false","0","no"].includes(o)?{value:!1}:{error:`"${n}" must be true or false`}}case"json":{if(typeof t=="object")return{value:t};try{return{value:JSON.parse(String(t))}}catch{return{error:`"${n}" must be valid JSON`}}}default:return{value:typeof t=="string"?t:String(t)}}}function S(e){return e==null||typeof e=="string"&&e.trim()===""}function B(e,t){let n={},o=[],r=t??{};for(let s of e){let i=r[s.name],a=S(i)?s.default:i;if(S(a)){s.required&&o.push(`"${s.label||s.name}" is required`);continue}let{value:c,error:u}=A(s,a);u?o.push(u):n[s.name]=c}return{values:n,errors:o}}function D(e){return typeof e=="string"?e:e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function z(e,t,n){let o=t.user_input;if(typeof o=="string"&&o.trim())return o;let r=e.filter(i=>i.name!=="user_input"&&t[i.name]!==void 0).map(i=>`- ${i.label||i.name}: ${D(t[i.name])}`),s=(n==null?void 0:n.trim())||"Automated execution";return r.length>0?`${s}
|
|
2
|
+
${r.join(`
|
|
3
|
+
`)}`:s}var P=["string","number","boolean","json"];var O=/^[A-Za-z][A-Za-z0-9_]*$/;function N(e){switch(e){case"startNode":return[{name:"user_input",path:"user_input",type:"string"},{name:"images",path:"images",type:"image"},{name:"files",path:"files",type:"file"}];case"llmNode":return[{name:"output",path:"",type:"string"}];case"apiNode":return[{name:"ok",path:"ok",type:"boolean"},{name:"status",path:"status",type:"number"},{name:"data",path:"data",type:"object"}];case"toolNode":return[{name:"ok",path:"ok",type:"boolean"},{name:"data",path:"data",type:"object"},{name:"error",path:"error",type:"string"}];case"classifierNode":return[{name:"classification",path:"classification",type:"string"}];case"memoNode":return[{name:"context",path:"",type:"string"}];default:return[]}}function T(e){return e.type!=="startNode"?[]:m(e.data).map(t=>({name:t.name,path:t.name,type:t.type==="json"?"object":t.type}))}function $(e){var r;let t=[...N(e.type),...T(e),...Array.isArray((r=e.data)==null?void 0:r.outVars)?e.data.outVars:[]],n=new Set,o=[];for(let s of t){let i=typeof(s==null?void 0:s.name)=="string"?s.name.trim():"";O.test(i)?n.has(i)?o.push(`Node ${e.id} has duplicate output name "${i}"`):n.add(i):o.push(`Node ${e.id} has an invalid output name`)}return o}function d(e){var o;let t=[...N(e.type),...T(e)],n=Array.isArray((o=e.data)==null?void 0:o.outVars)?e.data.outVars:[];return[...t.map(r=>({...r,source:"default"})),...n.map(r=>({...r,name:typeof(r==null?void 0:r.name)=="string"?r.name.trim():""})).filter(r=>O.test(r.name)).map(r=>({...r,source:"user"}))]}function w(e,t){let n=new Set,o=[t],r=new Set([t]);for(;o.length>0;){let s=o.shift();for(let i of e)i.target!==s||r.has(i.source)||(r.add(i.source),n.add(i.source),o.push(i.source))}return n}function U(e,t){var r,s;if(e.type!=="startNode")return t;let n=((r=e.data)==null?void 0:r.allow_images)===!0,o=((s=e.data)==null?void 0:s.allow_documents)===!0;return t.filter(i=>!(i.name==="images"&&!n||i.name==="files"&&!o))}function C(e,t,n){let o=w(t,n),r=[],s=new Set;for(let i of o){let a=e.find(c=>c.id===i);if(a)for(let c of U(a,d(a))){let u=a.type==="startNode"&&c.source==="default"?c.name:`${a.id}.${c.name}`;s.has(u)||(s.add(u),r.push({...c,ref:u,nodeId:a.id}))}}return r}function ne(e,t,n){return new Set(C(e,t,n).map(o=>o.ref))}function x(e,t){let n=w(t.edges,t.currentNodeId);return t.nodes.filter(o=>n.has(o.id)&&e.startsWith(`${o.id}.`)).sort((o,r)=>r.id.length-o.id.length)[0]}function I(e,t){return e.slice(t.length+1)}function re(e){return e.type==="image"||e.type==="file"}var L=new Set(["__proto__","prototype","constructor"]),E="\0__ORA_OB__\0",y="\0__ORA_CB__\0",l=class extends Error{constructor(n,o){super(o);this.code=n;this.name="VariableResolutionError"}code};function j(e){for(let t of e.split("."))if(L.has(t))throw new l("UNSAFE_PATH",`Unsafe variable path segment "${t}"`)}function R(e,t){if(!t)return e;j(t);let n=e;for(let o of t.split(".")){if(n==null||!Object.prototype.hasOwnProperty.call(Object(n),o))return;n=n[o]}return n}function k(e,t){var o,r,s,i,a,c,u;if(Object.prototype.hasOwnProperty.call(t.refOverrides??{},e))return{value:t.refOverrides[e]};let n=t.nodes.find(f=>f.type==="startNode");if(e==="user_input")return{value:(o=t.context)==null?void 0:o.user_input};if(e==="images"&&((r=n==null?void 0:n.data)==null?void 0:r.allow_images)===!0)return{value:(s=t.context)==null?void 0:s.user_images};if(e==="files"&&((i=n==null?void 0:n.data)==null?void 0:i.allow_documents)===!0)return{value:(a=t.context)==null?void 0:a.files};if(e==="classified_id")return{value:(c=t.context)==null?void 0:c.classified_id};if(n&&m(n.data).some(f=>f.name===e))return{value:(u=t.context)==null?void 0:u[e]}}function v(e,t){var h;let n=e.trim();if(!n)throw new l("INVALID_EXPRESSION","Variable reference is empty");let o=n.includes(".")?void 0:k(n,t);if(o)return o;if(!n.includes("."))throw new l("UNKNOWN_CONTEXT_REF",`Unknown run-context variable "${n}"`);let r=x(n,t);if(!r)throw new l("OUT_OF_SCOPE",`Variable "${n}" is not in this node's connection scope`);let s=I(n,r.id),[i,...a]=s.split("."),c=d(r).find(F=>F.name===i);if(!c)throw new l("UNKNOWN_OUTPUT",`Node "${r.id}" does not expose output "${i}"`);if(Object.prototype.hasOwnProperty.call(t.refOverrides??{},n))return{value:t.refOverrides[n]};let u=(h=t.results)==null?void 0:h[r.id];if(u==null)return{value:void 0,missing:"ancestor_not_executed"};let f=R(u,c.path??""),p=a.length>0?R(f,a.join(".")):f;return p==null?{value:void 0,missing:"path_not_found"}:{value:p}}function ce(e,t){return v(e,t).value}function M(e){let t=null,n=!1;for(let o=0;o<e.length-1;o+=1){let r=e[o];if(n){n=!1;continue}if(r==="\\"){n=!0;continue}if(t){r===t&&(t=null);continue}if(r==='"'||r==="'"){t=r;continue}if(r==="?"&&e[o+1]==="?")return{ref:e.slice(0,o).trim(),rawDefault:e.slice(o+2).trim()}}return{ref:e.trim()}}function W(e){if(e.length<2||!['"',"'"].includes(e[0])||e.at(-1)!==e[0])throw new l("INVALID_EXPRESSION","Template defaults must be quoted string literals");if(e[0]==='"')try{return JSON.parse(e)}catch{throw new l("INVALID_EXPRESSION","Invalid double-quoted template default")}return e.slice(1,-1).replace(/\\'/g,"'").replace(/\\\\/g,"\\")}function V(e){let{ref:t,rawDefault:n}=M(e.trim());if(!t)throw new l("INVALID_EXPRESSION","Template expression is missing a variable reference");return{ref:t,...n===void 0?{}:{defaultValue:W(n)}}}function le(e){let t=e.replace(/\\\{\{/g,E).replace(/\\\}\}/g,y),n=[],o=/\{\{\s*([^}]+?)\s*\}\}/g;for(let r of t.matchAll(o))n.push(V(r[1]).ref);return n}function X(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fe(e,t,n){let o=X(t);return e.replace(new RegExp(`(\\{\\{\\s*)${o}(?=\\.)`,"g"),`$1${n}`)}function _(e,t){return typeof e=="string"?t?JSON.stringify(e).slice(1,-1):e:typeof e=="object"&&e!==null?t?JSON.stringify(e):JSON.stringify(e,null,2):e!=null?t?JSON.stringify(e):String(e):""}function q(e,t){var n;throw(n=t==null?void 0:t.onError)==null||n.call(t,e.message),e}function pe(e,t,n,o){if(!e)return e;let r=(o==null?void 0:o.serializeNonStrings)??!1,s=e.replace(/\\\{\{/g,E).replace(/\\\}\}/g,y),i=/\{\{\s*([^}]+?)\s*\}\}/g;return s=s.replace(i,(a,c)=>{try{let u=V(c);if(u.ref.startsWith("secrets.")){let p=u.ref.slice(8);if(!Object.prototype.hasOwnProperty.call(n.secrets??{},p))throw new l("MISSING_SECRET",`Secret "${p}" is not defined for this tenant`);return _(n.secrets[p],r)}let f=v(u.ref,n);if(f.missing){if(u.defaultValue!==void 0)return _(u.defaultValue,r);let p=f.missing==="ancestor_not_executed"?`Ancestor for variable "${u.ref}" did not execute in this branch`:`Variable path "${u.ref}" did not produce a value`;throw new l(f.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",p)}return _(f.value,r)}catch(u){if(u instanceof l)return q(u,o);throw u}}),s.split(E).join("{{").split(y).join("}}")}export{g as a,b,m as c,B as d,z as e,O as f,N as g,$ as h,d as i,w as j,C as k,ne as l,x as m,I as n,re as o,l as p,R as q,v as r,ce as s,V as t,le as u,fe as v,pe as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{q as N}from"./chunk-K4MP63XM.js";import{a as J}from"./chunk-V6JSMX5A.js";import{tool as ot}from"ai";import{z as M}from"zod";import{z as p}from"zod";function j(t){if(t&&typeof t=="object"&&!t.type)return p.object({});if(t.type==="object")if(t.properties){let e={},o=t.required||[];for(let[r,n]of Object.entries(t.properties)){let a=j(n),c=n!=null&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,"default");e[r]=c?a.default(n.default):o.includes(r)?a:a.optional()}return p.object(e)}else return p.object({});else if(t.type==="array"&&t.items){let e=j(t.items);return p.array(e)}else{if(t.type==="string")return p.string();if(t.type==="number"||t.type==="integer")return p.number();if(t.type==="boolean")return p.boolean()}return p.any()}var W=/\{\{\s*secrets\.[A-Z][A-Z0-9_]*\s*\}\}/,xt=t=>W.test(t),rt=/\{\{\s*auth\.[A-Z][A-Z0-9_]*\s*\}\}/;var E=t=>W.test(t)||rt.test(t),w=t=>{let e=t.indexOf("?");return e===-1?t:`${t.slice(0,e)}?[redacted-query]`};var st=256*1024,it=3e4,ct=/\{\{\s*([^}]+?)\s*\}\}/g,at=t=>{let e=t.toLowerCase();return e.includes("token")||e.includes("secret")||e.includes("key")||e.includes("password")||e.includes("access")||e==="authorization"},ut=t=>{let e={};for(let o in t)e[o]=at(o)?"[REDACTED]":t[o];return e},I=(t,e)=>{let o=t.indexOf(".");if(o===-1)return e[t];let r=t.slice(0,o),n=t.slice(o+1);if(r in e)return N(e[r],n)},H=(t,e,o)=>t&&t.replace(ct,(r,n)=>{let a=String(n).trim();if(a.startsWith("secrets.")){let f=a.slice(8);return Object.prototype.hasOwnProperty.call(o.secrets,f)?o.secrets[f]:r}if(a.startsWith("auth.")){let f=a.slice(5);return Object.prototype.hasOwnProperty.call(o.auth,f)?o.auth[f]:r}let c=I(a,e);return c==null?"":typeof c=="string"?c:JSON.stringify(c)}),dt=/\{\{\s*((?:secrets|auth)\.[^}\s]+)\s*\}\}/g,lt=(...t)=>{let e=new Set;for(let o of t){if(o==null)continue;let r=typeof o=="string"?o:JSON.stringify(o);for(let n of r.matchAll(dt))e.add(n[1])}return[...e]},T=(t,e,o)=>{if(t==null)return t;if(typeof t=="string"){let r=t.match(/^\s*\{\{\s*([^}]+?)\s*\}\}\s*$/);if(r){let n=r[1].trim();if(n.startsWith("secrets.")){let c=n.slice(8);return Object.prototype.hasOwnProperty.call(o.secrets,c)?o.secrets[c]:t}if(n.startsWith("auth.")){let c=n.slice(5);return Object.prototype.hasOwnProperty.call(o.auth,c)?o.auth[c]:t}return I(n,e)}return H(t,e,o)}if(Array.isArray(t))return t.map(r=>T(r,e,o));if(typeof t=="object"){let r={};for(let n in t)r[n]=T(t[n],e,o);return r}return t},ft=(t,e)=>t?e?/^https?:\/\//i.test(e)?e:t.endsWith("/")&&e.startsWith("/")?t+e.slice(1):!t.endsWith("/")&&!e.startsWith("/")?`${t}/${e}`:t+e:t:e||"",pt=(t,e)=>{if(!e)return t;let o=new URL(t);for(let r in e){let n=e[r];n!==void 0&&(Array.isArray(n)?o.searchParams.set(r,n.join(",")):o.searchParams.set(r,String(n)))}return o.toString()},K=t=>{if(!t)return{};let e={};for(let o in t)t[o]!==void 0&&(e[o]=t[o]);return e},yt=t=>{let e={};for(let o in t){let r=t[o];r!=null&&(e[o]=typeof r=="string"?r:String(r))}return e},gt=(t,e,o)=>{if(!(!t||t.type==="none"||!t.value)){if(t.type==="bearer"){e.Authorization=`Bearer ${t.value}`;return}if(t.type==="apiKey"){let r=t.in||"header",n=t.param||t.header||"X-API-Key";r==="query"?o[n]=t.value:e[n]=t.value}}},mt=(t,e)=>{let o=new TextEncoder().encode(t);if(o.byteLength<=e)return{text:t,truncated:!1};let r=o.slice(0,e);return{text:new TextDecoder("utf-8",{fatal:!1}).decode(r),truncated:!0}};function ht(t,e,o,r){var Z;if(t.kind!=="http")throw new Error(`customHttpTool: unsupported kind '${t.kind}' for tool '${t.name}'`);let n=t.execution||{},a=n.actions&&typeof n.actions=="object"?Object.keys(n.actions):[],c=((Z=n.router)==null?void 0:Z.field)||"action",f=t.inputSchema&&typeof t.inputSchema=="object"&&Object.keys(t.inputSchema).length>0?j(t.inputSchema):M.object({});if(a.length>0&&f instanceof M.ZodObject){let m=M.enum(a);f=f.extend({[c]:m})}let G=t.description||t.label||t.name,y=t.output||{},Q=Number.isFinite(y.maxBytes)&&y.maxBytes>0?y.maxBytes:st;return ot({description:G,inputSchema:f,execute:async m=>{var z;let h={secrets:e.secrets??{},auth:e.userAuth??{}},b={input:m??{},...o.context||{}},u=n,i;if(n.actions&&typeof n.actions=="object"){let s=((z=n.router)==null?void 0:z.field)||"action";if(i=m==null?void 0:m[s],!i||!n.actions[i])return{type:"error",error:`unknown action '${i}' for tool '${t.name}'`,natural:`Tool ${t.name} could not run: missing or unknown action.`};u=n.actions[i]}let C=u.url||ft(n.baseUrl,u.path);if(!C)return{type:"error",error:"missing url",natural:`Tool ${t.name} has no URL configured.`};let V=E(C),F=H(C,b,h),X={...n.headers||{},...u.headers||{}},g=yt(K(T(X,b,h))),Y={...n.query||{},...u.query||{}},P=K(T(Y,b,h)),$=(u.method||n.method||"GET").toUpperCase(),k,v=u.body!==void 0||n.body!==void 0;if($!=="GET"&&$!=="HEAD"&&v){let s=u.body!==void 0?u.body:n.body,d=typeof s=="string"?H(s,b,h):T(s,b,h);k=typeof d=="string"?d:JSON.stringify(d),!g["Content-Type"]&&!g["content-type"]&&(g["Content-Type"]="application/json")}let R=u.auth||n.auth,A=R?{...R,value:R.value?H(String(R.value),b,h):R.value}:void 0;gt(A,g,P);let S=pt(F,P),tt=V?w(S):S,U=lt(F,g,P,k,A==null?void 0:A.value);if(U.length>0){let s=U.map(d=>`{{ ${d} }}`).join(", ");return r==null||r({type:`error:tool:${t.name}:credentials`,content:{tool:t.name,action:i,missing:U}}),{type:"error",error:`unresolved credentials: ${s}`,natural:`Tool ${t.name} could not run because ${s} has no value in this execution. Connect the credential or use a tenant secret so unattended runs can resolve it.`}}let et=Math.min(Number.isFinite(u.timeoutMs)&&u.timeoutMs>0?u.timeoutMs:Number.isFinite(n.timeoutMs)&&n.timeoutMs>0?n.timeoutMs:15e3,it),D={tool:t.name,action:i,stage:"request",url:tt,method:$,headers:ut(g)};JSON.stringify(D),r==null||r({type:`info:tool:${t.name}:request`,content:D});let q=new AbortController,nt=setTimeout(()=>q.abort(),et);try{let s=await fetch(S,{method:$,headers:g,body:k,signal:q.signal}),d=s.headers.get("content-type")||"",O=await s.text(),{text:x,truncated:_}=mt(O,Q),l;if(y.contentType==="text"?l=x:d.includes("application/json")||y.contentType==="json"?(l=J(x),l===null&&x&&(l=x)):l=x,y.jsonPath&&l!==null&&typeof l=="object"&&(l=N(l,y.jsonPath)),!s.ok){let B={tool:t.name,action:i,stage:"http_error",status:s.status};return JSON.stringify(B),r==null||r({type:`error:tool:${t.name}:http`,content:B}),{type:"error",status:s.status,error:`HTTP ${s.status}: ${s.statusText}`,result:l,truncated:_,natural:`${t.name}${i?`:${i}`:""} failed with HTTP ${s.status}.`}}let L={tool:t.name,action:i,stage:"finish",status:s.status,truncated:_};return JSON.stringify(L),r==null||r({type:`info:tool:${t.name}:finish`,content:L}),{type:i||t.name,status:s.status,result:l,truncated:_,natural:`${t.name}${i?`:${i}`:""} completed (HTTP ${s.status}).`}}catch(s){let d=String((s==null?void 0:s.message)??s),O={tool:t.name,action:i,stage:"error",error:d};return JSON.stringify(O),r==null||r({type:`error:tool:${t.name}:execution`,content:O}),{type:"error",error:d,natural:`${t.name}${i?`:${i}`:""} failed: ${d}`}}finally{clearTimeout(nt)}}})}var St=ht;export{xt as a,w as b,j as c,ht as d,St as e};
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as u,b as Q,c as T,d as X,e as z,f as
|
|
1
|
+
import{a as u,b as Q,c as T,d as X,e as z,f as Fe,g as De,h as He}from"./chunk-E7BCWUTG.js";import{a as $,b as L,c as Y,d as k,e as K,f as Se,g as fe,h as Ae,i as Re,j as Me,k as Ee,l as Te,m as Ie,n as Ce,o as he,p as xe,q as we,r as _e,s as be,t as Ne,u as Oe,v as qe,w as Ve}from"./chunk-K4MP63XM.js";import{a as B,b as W,c as Z,d as ee,e as te,f as ne,g as se,h as oe,i as re,j as ae,k as ie,l as ge,m as le,n as pe,o as ce,p as ue,q as de,r as ve,s as ye,t as me}from"./chunk-GRZ6ZRHM.js";import{a as G}from"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";import{useAgent as U}from"agents/react";import{useCallback as d,useEffect as P,useMemo as J,useRef as m}from"react";import{create as F}from"zustand";import{devtools as D}from"zustand/middleware";var H={messages:[],events:[],eventsVisible:!1,status:"connecting",typingMessage:null,reasoningMessage:null,reasoningMessages:[],isReasoning:!1,stepInfo:null,approvals:[],error:null,flowConfig:null,composioAuth:null};function C(n){return F()(D((t,y)=>({...H,initHistory:e=>t({messages:e}),addEvent:e=>t(o=>({events:[...o.events,{...e,ts:Date.now()}]})),clearEvents:()=>t({events:[]}),setMessages:e=>{t({messages:e})},addMessage:e=>{t(o=>({messages:[...o.messages,e]}))},setTyping:e=>t({typingMessage:e}),appendTyping:(e,o)=>{let r=y().typingMessage;r&&r.id===e?t({typingMessage:{id:e,text:r.text+o}}):t({typingMessage:{id:e,text:o}})},clearTyping:()=>t({typingMessage:null}),setReasoning:e=>t({reasoningMessage:e}),appendReasoning:(e,o)=>{let r=y().reasoningMessage;r&&r.id===e?t({reasoningMessage:{id:e,text:r.text+o}}):t({reasoningMessage:{id:e,text:o}})},commitReasoning:e=>{t(o=>{var r;return(r=o.reasoningMessage)!=null&&r.text?{reasoningMessages:[...o.reasoningMessages,{...o.reasoningMessage,ts:e??Date.now()}],reasoningMessage:null,isReasoning:!1}:{reasoningMessage:null,isReasoning:!1}})},clearReasoning:()=>t({reasoningMessage:null,isReasoning:!1}),setReasoningMessages:e=>t({reasoningMessages:e}),setReasoningActive:e=>t({isReasoning:e}),setStep:e=>t({stepInfo:e}),clearStep:()=>t({stepInfo:null}),setStatus:e=>t({status:e}),toggleEvents:()=>t(e=>({eventsVisible:!e.eventsVisible})),clearHistory:()=>t({messages:[],typingMessage:null,reasoningMessage:null,reasoningMessages:[],isReasoning:!1,stepInfo:null}),addApprovalRequest:e=>{let o={id:`approval-${Date.now()}-${Math.random()}`,toolCallId:e.toolCallId,toolName:e.toolName,args:e.args??{},description:e.description,ts:Date.now(),status:"pending"};t(r=>({approvals:[...r.approvals,o]}))},updateApprovalStatus:({toolCallId:e,status:o})=>{t(r=>({approvals:r.approvals.map(v=>v.toolCallId===e?{...v,status:o}:v)}))},removeApproval:e=>{t(o=>({approvals:o.approvals.filter(r=>r.toolCallId!==e)}))},setError:e=>t({error:e}),setFlowConfig:e=>t({flowConfig:e}),setComposioAuth:e=>t({composioAuth:e}),clearComposioAuth:()=>t({composioAuth:null})}),{name:n,enabled:!0}))}var j=C("agent-store"),I=new Map;function h(n){if(!n)return j;let t=I.get(n);return t||(t=C(`agent-store:${n}`),I.set(n,t)),t}function ke(n){let t=J(()=>h(n==null?void 0:n.storeKey),[n==null?void 0:n.storeKey]),y=t(s=>s.typingMessage),e=m(null),o=m(null),r=m(null),v=m(0),S=m(null),f=()=>(v.current=Math.max(Date.now(),v.current+1),v.current);P(()=>{e.current=y},[y]);let A=d(s=>{var g;let i=s.trim().slice(0,T);!i||typeof((g=S.current)==null?void 0:g.send)!="function"||S.current.send(u.USER_IDENTITY+":"+i)},[]),l=U({host:n==null?void 0:n.host,basePath:(n==null?void 0:n.basePath)??"/api/agents/base",agent:n==null?void 0:n.agent,name:n==null?void 0:n.name,query:n==null?void 0:n.query,onMessage:s=>{if(typeof s.data!="string")return;let[i,g]=s.data.split("::");if(!i||!g)return;let a=t.getState(),R={[u.SERVER_HISTORY]:p=>{let c=JSON.parse(p);a.setMessages(c.messages),a.setReasoningMessages([])},[u.SERVER_EVENT]:p=>{var E;let c=JSON.parse(p);if((c==null?void 0:c.type)==="info:composio:auth_required"&&((E=c==null?void 0:c.content)!=null&&E.redirectUrl)){let M=c.content;a.setComposioAuth({toolkit:M.toolkit,redirectUrl:M.redirectUrl,toolRowId:M.toolRowId})}a.addEvent({type:"server",...c})},[u.SERVER_ERROR]:p=>{a.setError(p),a.addEvent({type:"error",content:p})},[u.SERVER_TEXT_STREAM]:p=>{o.current?a.appendTyping(o.current,p):(o.current=String(Date.now()),a.setTyping({id:o.current,text:p}))},[u.SERVER_TEXT_STREAM_COMPLETE]:p=>{if(a.setReasoningActive(!1),o.current&&a.typingMessage){let c=a.typingMessage.text;a.addMessage({role:"assistant",type:"text",content:c,id:o.current,ts:f()}),a.clearTyping(),o.current=null}},[u.SERVER_REASONING_STREAM]:p=>{a.setReasoningActive(!0),r.current?a.appendReasoning(r.current,p):(r.current=String(Date.now()),a.setReasoning({id:r.current,text:p}))},[u.SERVER_REASONING_STREAM_COMPLETE]:()=>{a.commitReasoning(f()),r.current=null},[u.SERVER_CONFIG]:p=>{a.setFlowConfig(JSON.parse(p))}};R[i]&&R[i](g)},onOpen:()=>{let s=t.getState();s.setStatus("connected"),s.clearTyping(),o.current=null,s.clearReasoning(),r.current=null,s.clearStep(),s.addEvent({type:"connection",content:"Connected to Agent Server"}),n!=null&&n.user&&A(n.user)},onClose:()=>{let s=t.getState();s.setStatus("disconnected"),s.setFlowConfig(null),s.addEvent({type:"connection",content:"Connection closed"})}});S.current=l;let x=d((s,i,g)=>{let a=s.trim();if(!a&&(!i||i.length===0)&&(!g||g.length===0))return;let p=((i==null?void 0:i.length)??0)>0||((g==null?void 0:g.length)??0)>0?JSON.stringify({text:a,images:i,documents:g}):a;l.send(u.USER_MESSAGE+":"+p);let c=t.getState();r.current=null,c.clearReasoning(),c.addMessage({id:String(Date.now())+Math.random(),role:"user",type:"text",content:a,images:i,ts:f()})},[l]),w=d(()=>{t.getState().clearHistory(),l.send(u.USER_CLEAR_HISTORY+":1")},[l]),_=d((s,i)=>{let g=s.trim();g&&l.send(u.USER_AUTH+":"+JSON.stringify({name:g,value:i}))},[l]),b=d(s=>{A(s)},[A]),N=d(()=>t.getState().toggleEvents(),[]),O=d(()=>t.getState().clearEvents(),[]),q=d(s=>{let i=t.getState();i.updateApprovalStatus({toolCallId:s,status:"approved"});let g=JSON.stringify({type:"tool_approval",toolCallId:s,approved:!0});typeof(l==null?void 0:l.send)=="function"&&l.send(g),i.addEvent({type:"approval",content:`Approved tool call ${s}`,ts:Date.now()})},[l]),V=d(s=>{let i=t.getState();i.updateApprovalStatus({toolCallId:s,status:"rejected"});let g=JSON.stringify({type:"tool_approval",toolCallId:s,approved:!1});typeof(l==null?void 0:l.send)=="function"&&l.send(g),i.addEvent({type:"approval",content:`Rejected tool call ${s}`,ts:Date.now()})},[l]);return{connection:l,store:t,send:x,clearHistory:w,sendAuth:_,setIdentity:b,toggleEventsVisible:N,clearEvents:O,approve:q,reject:V}}export{L as FLOW_INPUT_NAME_RE,B as GENERATION_PARAM_KEYS,Z as GENERATION_PRESETS,T as MAX_USER_IDENTITY_LENGTH,De as MODEL_REGISTRY_SNAPSHOT,$ as NodeType,Se as OUT_VAR_NAME_RE,W as PRESET_PARAM_KEYS,ce as REASONING_EFFORT_LEVELS,Fe as TOOL_REGISTRY_SNAPSHOT,xe as VariableResolutionError,ne as applyPresetToOverrides,me as buildReasoningProviderOptions,Te as buildScope,K as buildTriggerMessageText,ee as deriveParamSupport,Oe as extractTemplateReferences,Ie as findScopedSourceNode,h as getAgentStore,Me as getAncestorNodeIds,fe as getDefaultOutVars,Re as getEffectiveOutVars,Y as getFlowInputDefs,He as getModelEntry,Ce as getRefTail,Ee as getUpstreamOutVars,he as isBinaryOutVar,G as logc,u as messageTypes,oe as normalizeEffectiveParams,k as normalizeFlowInputs,ue as normalizeReasoning,ie as openAiReasoningParamSupport,ae as openAiStandardParamSupport,Ne as parseTemplateExpression,z as parseUserAuth,Q as parseUserMessage,se as pickNodeOverrides,de as reasoningEffortLevels,ve as reasoningExposable,be as resolveOutVarRef,te as resolvePreset,ye as resolveReasoningEffort,_e as resolveReference,Ve as resolveTemplate,qe as rewriteTemplateNodeRefs,X as sanitizeUserIdentity,pe as stripUnsupportedFromNodeData,re as toStreamTextSettings,ke as useAgent,j as useAgentStore,Ae as validateOutVars,we as walkPath,le as workersAiParamSupport,ge as xaiParamSupport};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export interface FlowNode {
|
|
2
|
+
id: string;
|
|
3
|
+
type?: string;
|
|
4
|
+
data?: any;
|
|
5
|
+
}
|
|
6
|
+
export interface FlowEdge {
|
|
7
|
+
source: string;
|
|
8
|
+
target: string;
|
|
9
|
+
sourceHandle?: string | null;
|
|
10
|
+
}
|
|
11
|
+
export type OutVarType = 'string' | 'number' | 'boolean' | 'object' | 'array' | 'image' | 'file';
|
|
12
|
+
/** A named, public value exposed by a node result. */
|
|
13
|
+
export interface OutVar {
|
|
14
|
+
name: string;
|
|
15
|
+
path?: string;
|
|
16
|
+
type?: OutVarType;
|
|
17
|
+
description?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface EffectiveOutVar extends OutVar {
|
|
20
|
+
source: 'default' | 'user';
|
|
21
|
+
}
|
|
22
|
+
/** Only Answer nodes use this: it maps runtime values into persisted JSON output. */
|
|
23
|
+
export interface OutputMapping {
|
|
24
|
+
key: string;
|
|
25
|
+
from: string;
|
|
26
|
+
default?: string;
|
|
27
|
+
}
|
|
28
|
+
export interface ResolveInput {
|
|
29
|
+
context: Record<string, any>;
|
|
30
|
+
results: Record<string, any>;
|
|
31
|
+
nodes: FlowNode[];
|
|
32
|
+
edges: FlowEdge[];
|
|
33
|
+
currentNodeId: string;
|
|
34
|
+
secrets?: Record<string, string>;
|
|
35
|
+
/** Design-time values keyed by complete canonical refs. Never supplied in production. */
|
|
36
|
+
refOverrides?: Record<string, unknown>;
|
|
37
|
+
}
|
|
38
|
+
export interface ResolveOptions {
|
|
39
|
+
callerTag?: string;
|
|
40
|
+
serializeNonStrings?: boolean;
|
|
41
|
+
onError?: (msg: string) => void;
|
|
42
|
+
}
|
|
43
|
+
export declare const OUT_VAR_NAME_RE: RegExp;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { EffectiveOutVar, FlowEdge, FlowNode, OutVar } from '../types/var-scope';
|
|
2
|
+
export interface ScopedVar extends EffectiveOutVar {
|
|
3
|
+
ref: string;
|
|
4
|
+
nodeId: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function getAncestorNodeIds(edges: FlowEdge[], nodeId: string): Set<string>;
|
|
7
|
+
export declare function getUpstreamOutVars(nodes: FlowNode[], edges: FlowEdge[], nodeId: string): ScopedVar[];
|
|
8
|
+
export declare function buildScope(nodes: FlowNode[], edges: FlowEdge[], nodeId: string): Set<string>;
|
|
9
|
+
/** Finds the longest real ancestor ID that prefixes a qualified ref. */
|
|
10
|
+
export declare function findScopedSourceNode(ref: string, input: {
|
|
11
|
+
nodes: FlowNode[];
|
|
12
|
+
edges: FlowEdge[];
|
|
13
|
+
currentNodeId: string;
|
|
14
|
+
}): FlowNode | undefined;
|
|
15
|
+
export declare function getRefTail(ref: string, nodeId: string): string;
|
|
16
|
+
export declare function isBinaryOutVar(outVar: Pick<OutVar, 'type'>): boolean;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { NodeType } from '../types/node-types';
|
|
2
|
+
import type { EffectiveOutVar, FlowNode, OutVar } from '../types/var-scope';
|
|
3
|
+
export declare function getDefaultOutVars(nodeType: NodeType): OutVar[];
|
|
4
|
+
/** Validates every public output name, including collisions with built-ins and Start inputs. */
|
|
5
|
+
export declare function validateOutVars(node: FlowNode): string[];
|
|
6
|
+
export declare function getEffectiveOutVars(node: FlowNode): EffectiveOutVar[];
|
|
@@ -1,7 +1,25 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import type { FlowNode, ResolveInput, ResolveOptions } from '../types/var-scope';
|
|
2
|
+
export { getDefaultOutVars, getEffectiveOutVars, validateOutVars } from './outVars';
|
|
3
|
+
export type VariableResolutionCode = 'OUT_OF_SCOPE' | 'UNKNOWN_OUTPUT' | 'UNKNOWN_CONTEXT_REF' | 'ANCESTOR_NOT_EXECUTED' | 'PATH_NOT_FOUND' | 'UNSAFE_PATH' | 'INVALID_EXPRESSION' | 'MISSING_SECRET';
|
|
4
|
+
export declare class VariableResolutionError extends Error {
|
|
5
|
+
readonly code: VariableResolutionCode;
|
|
6
|
+
constructor(code: VariableResolutionCode, message: string);
|
|
7
|
+
}
|
|
8
|
+
export interface RefResolution {
|
|
9
|
+
value: unknown;
|
|
10
|
+
missing?: 'ancestor_not_executed' | 'path_not_found';
|
|
11
|
+
}
|
|
12
|
+
export interface ParsedTemplateExpression {
|
|
13
|
+
ref: string;
|
|
14
|
+
defaultValue?: string;
|
|
15
|
+
}
|
|
3
16
|
export declare function walkPath(obj: any, path: string): any;
|
|
4
|
-
|
|
5
|
-
export declare function
|
|
17
|
+
/** Resolves one canonical direct reference. Structural errors throw; absent values return missing metadata. */
|
|
18
|
+
export declare function resolveReference(ref: string, input: ResolveInput): RefResolution;
|
|
19
|
+
/** Kept as a concise public helper for callers that do not need missing diagnostics. */
|
|
6
20
|
export declare function resolveOutVarRef(ref: string, input: ResolveInput): unknown | undefined;
|
|
21
|
+
export declare function parseTemplateExpression(expression: string): ParsedTemplateExpression;
|
|
22
|
+
export declare function extractTemplateReferences(template: string): string[];
|
|
23
|
+
/** Rewrites only the source-node segment at the beginning of a template expression. */
|
|
24
|
+
export declare function rewriteTemplateNodeRefs(template: string, oldNodeId: string, newNodeId: string): string;
|
|
7
25
|
export declare function resolveTemplate(template: string, node: FlowNode, input: ResolveInput, options?: ResolveOptions): string;
|
package/dist/common.d.ts
CHANGED
|
@@ -8,7 +8,9 @@ export * from './common/utils/reasoning';
|
|
|
8
8
|
export * from './common/constants/tools-registry';
|
|
9
9
|
export * from './common/constants/ai-models';
|
|
10
10
|
export * from './common/utils/logc';
|
|
11
|
-
export * from './common/types/var-
|
|
11
|
+
export * from './common/types/var-scope';
|
|
12
12
|
export * from './common/types/trigger-types';
|
|
13
13
|
export * from './common/utils/flowInputs';
|
|
14
14
|
export * from './common/utils/templateUtils';
|
|
15
|
+
export * from './common/utils/flowScope';
|
|
16
|
+
export * from './common/utils/outVars';
|
package/dist/common.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as b,b as h,c as i,d as j,e as k,f as
|
|
1
|
+
import{a as b,b as h,c as i,d as j,e as k,f as X,g as Y,h as Z}from"./chunk-E7BCWUTG.js";import{a as c,b as d,c as e,d as f,e as g,f as F,g as G,h as H,i as I,j as J,k as K,l as L,m as M,n as N,o as O,p as P,q as Q,r as R,s as S,t as T,u as U,v as V,w as W}from"./chunk-K4MP63XM.js";import{a as l,b as m,c as n,d as o,e as p,f as q,g as r,h as s,i as t,j as u,k as v,l as w,m as x,n as y,o as z,p as A,q as B,r as C,s as D,t as E}from"./chunk-GRZ6ZRHM.js";import{a}from"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{d as FLOW_INPUT_NAME_RE,l as GENERATION_PARAM_KEYS,n as GENERATION_PRESETS,i as MAX_USER_IDENTITY_LENGTH,Y as MODEL_REGISTRY_SNAPSHOT,c as NodeType,F as OUT_VAR_NAME_RE,m as PRESET_PARAM_KEYS,z as REASONING_EFFORT_LEVELS,X as TOOL_REGISTRY_SNAPSHOT,P as VariableResolutionError,q as applyPresetToOverrides,E as buildReasoningProviderOptions,L as buildScope,g as buildTriggerMessageText,o as deriveParamSupport,U as extractTemplateReferences,M as findScopedSourceNode,J as getAncestorNodeIds,G as getDefaultOutVars,I as getEffectiveOutVars,e as getFlowInputDefs,Z as getModelEntry,N as getRefTail,K as getUpstreamOutVars,O as isBinaryOutVar,a as logc,b as messageTypes,s as normalizeEffectiveParams,f as normalizeFlowInputs,A as normalizeReasoning,v as openAiReasoningParamSupport,u as openAiStandardParamSupport,T as parseTemplateExpression,k as parseUserAuth,h as parseUserMessage,r as pickNodeOverrides,B as reasoningEffortLevels,C as reasoningExposable,S as resolveOutVarRef,p as resolvePreset,D as resolveReasoningEffort,R as resolveReference,W as resolveTemplate,V as rewriteTemplateNodeRefs,j as sanitizeUserIdentity,y as stripUnsupportedFromNodeData,t as toStreamTextSettings,H as validateOutVars,Q as walkPath,x as workersAiParamSupport,w as xaiParamSupport};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as a,e as b}from"./chunk-UBNZUUTD.js";import"./chunk-K4MP63XM.js";import"./chunk-V6JSMX5A.js";import"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{a as customHttpTool,b as default};
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as ue}from"./chunk-ELMOSEQ7.js";import{a as B,b as st,c as pe,d as yt}from"./chunk-UBNZUUTD.js";import{a as me}from"./chunk-OF6G42DM.js";import"./chunk-MOYYZBTC.js";import{a as ge,b as ye}from"./chunk-W6DBEVOO.js";import{a as Pn,b as ut,c as Dn,d as pt,e as _t,f as oe,g as ne,h as se,i as re,j as ie,k as $t,l as ae}from"./chunk-57TCP6J4.js";import{a as E,b as dt,c as gn,d as nt,e as Bt,f as fe,g as Kn,h as Jn}from"./chunk-E7BCWUTG.js";import{a as v,b as mn,c as tt,d as Wt,e as Yt,f as Un,g as Mn,h as ce,i as ft,j as bn,k as et,l as En,m as jn,n as Ln,o as Hn,p as V,q as mt,r as K,s as Vn,t as qn,u as Sn,v as Xn,w as le}from"./chunk-K4MP63XM.js";import{a as yn,b as wn,c as hn,d as Rn,e as xn,f as In,g as Qt,h as Tn,i as Zt,j as Nn,k as An,l as Cn,m as On,n as _n,o as $n,p as kn,q as Fn,r as vt,s as te,t as ee}from"./chunk-GRZ6ZRHM.js";import{a as an}from"./chunk-RYHQGPX5.js";import{a as cn}from"./chunk-R6EKV3WR.js";import{a as un}from"./chunk-6HY7QUMP.js";import{a as ln,b as dn}from"./chunk-V6JSMX5A.js";import{a as W,b as Z,c as pn,d as Gt,e as fn}from"./chunk-G3SGJ7XJ.js";import{a as ot}from"./chunk-U56YWPSI.js";import{a as gt,b as de}from"./chunk-A2IRPAD4.js";import{a as lt}from"./chunk-3TXHFKDN.js";import{Agent as Jo}from"agents";import{nanoid as zo}from"nanoid";var H=(o,t,n)=>{o.send(t+"::"+n)};async function io(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 we(o,t){o.sql`INSERT INTO messages (id, role, type, content, ts) VALUES (${t.id}, ${t.role}, ${t.type}, ${t.content}, ${t.ts})`}async function z(o){return o.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function wt(o){o.sql`DELETE FROM messages`}async function ao(o){o.sql`CREATE TABLE IF NOT EXISTS context (
|
|
2
2
|
ref TEXT PRIMARY KEY,
|
|
3
3
|
domain TEXT NOT NULL,
|
|
4
4
|
description TEXT NOT NULL,
|
|
@@ -6,7 +6,7 @@ import{a as ce}from"./chunk-ELMOSEQ7.js";import{a as Y,b as nt,c as le,d as mt}f
|
|
|
6
6
|
cycle INTEGER NOT NULL,
|
|
7
7
|
meta TEXT,
|
|
8
8
|
ts INTEGER NOT NULL
|
|
9
|
-
)`}async function
|
|
9
|
+
)`}async function he(o,t){let n=t.data??null,e=n!=null?se(n):{data:null,truncated:!1},s=e.truncated?ae(t.meta,{truncated:!0}):t.meta??null,r=t.ts??Date.now();o.sql`INSERT INTO context (ref, domain, description, data, cycle, meta, ts)
|
|
10
10
|
VALUES (${t.ref}, ${t.domain}, ${t.description}, ${e.data}, ${t.cycle}, ${s}, ${r})
|
|
11
11
|
ON CONFLICT(ref) DO UPDATE SET
|
|
12
12
|
domain = excluded.domain,
|
|
@@ -14,29 +14,29 @@ import{a as ce}from"./chunk-ELMOSEQ7.js";import{a as Y,b as nt,c as le,d as mt}f
|
|
|
14
14
|
data = excluded.data,
|
|
15
15
|
cycle = excluded.cycle,
|
|
16
16
|
meta = excluded.meta,
|
|
17
|
-
ts = excluded.ts`}async function yt(o){return o.sql`SELECT ref, domain, description, cycle, meta, ts FROM context ORDER BY ts ASC`}async function ye(o){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context ORDER BY ts ASC`}async function wt(o,t){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${t} LIMIT 1`[0]??null}async function we(o,t){var e;return((e=o.sql`SELECT data FROM context WHERE ref = ${t} LIMIT 1`[0])==null?void 0:e.data)??null}async function he(o,t){let n=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${t} LIMIT 1`;if(n[0])return n[0];let e=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref LIKE ${t+"%"} LIMIT 2`;return e.length===1?e[0]:null}async function Re(o,t){o.sql`DELETE FROM context WHERE domain = 'tool' AND cycle <= ${t}`}async function xe(o){var n;return((n=o.sql`SELECT COALESCE(MAX(cycle), 0) AS maxCycle FROM context`[0])==null?void 0:n.maxCycle)??0}async function ht(o){o.sql`DELETE FROM context`}async function Ie(o){await oo(o),await no(o)}function _t(o){return{"Content-Type":"application/json",Authorization:o.HX_API_KEY}}function Rt(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function kt(o,t){if(!Rt(o))return null;let n=await fetch(`${o.HX_ORA_URL}/internal/runs`,{method:"POST",headers:_t(o),body:JSON.stringify(t)});return n.ok?await n.json():(console.error("[oraTriggers] createRun failed",n.status,await n.text().catch(()=>"")),null)}async function st(o,t){if(!Rt(o))return{claimed:!0};let n=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(t)}/claim`,{method:"POST",headers:_t(o)});if(!n.ok){let e=await n.text().catch(()=>"");throw new Error(`claimRun ${t} failed with ${n.status}: ${e}`)}return await n.json()}async function xt(o,t,n,e=3){if(!Rt(o))return!0;for(let s=1;s<=e;s++){try{let r=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(t)}/complete`,{method:"POST",headers:_t(o),body:JSON.stringify(n)});if(r.ok||r.status===409)return!0;if(r.status===404)return console.error(`[oraTriggers] completeRun ${t} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${t} attempt ${s} failed with ${r.status}`)}catch(r){console.warn(`[oraTriggers] completeRun ${t} attempt ${s} threw`,r)}s<e&&await new Promise(r=>setTimeout(r,250*s))}return console.error(`[oraTriggers] completeRun ${t} exhausted ${e} attempts; hx-ora will time the run out`),!1}async function Te(o,t){if(!Rt(o))return Promise.resolve();try{return await kt(o,t)}catch(n){return console.error("[oraTriggers] recordRun failed",n),null}}var $t=Object.freeze({}),so="__SYSTEM_";function Ne(o){return o.startsWith(so)}function ro(o){let t={};for(let[n,e]of Object.entries(o))Ne(n)||(t[n]=e);return Object.freeze(t)}async function It(o,t){if(!t)return $t;if(o.HX_ORA_URL&&o.HX_API_KEY)try{let s=await fetch(`${o.HX_ORA_URL}/internal/secrets`,{headers:{Authorization:o.HX_API_KEY}});if(s.ok){let r=await s.json();if(r.secrets)return ro(r.secrets)}else console.warn(`[secrets] API failed with status ${s.status}, falling back to KV`)}catch(s){console.error("[secrets] API request failed, falling back to KV",s)}let n=o.ORA_SECRETS;if(!n)return $t;let e=`${t}:`;try{let s=await n.list({prefix:e,limit:1e3});s.list_complete===!1&&console.warn(`[secrets] tenant=${t} exceeded list page; truncating to first 1000 keys`);let r=s.keys.filter(d=>!Ne(d.name.slice(e.length))),i=await Promise.all(r.map(async d=>{let u=await n.get(d.name);return u!==null?[d.name.slice(e.length),u]:null})),c={};for(let d of i){if(!d)continue;let[u,p]=d;u&&(c[u]=p)}return Object.freeze(c)}catch(s){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:t,err:s}),$t}}import{nanoid as jn}from"nanoid";function rt(o){var s,r;let t=(s=o==null?void 0:o.flowData)==null?void 0:s.state,e=((t==null?void 0:t.nodes)??((r=o==null?void 0:o.flowData)==null?void 0:r.nodes)??[]).find(i=>i.type==="startNode");return e==null?void 0:e.data}async function Ce(o,t){return typeof t.cycle=="number"&&Number.isFinite(t.cycle)?t.cycle+1:await xe(o)+1}function Ae(o,t,n,e,s){let r=ut(rt(n));return{...t,memoryConfig:r,cycle:e,setContext:async c=>{await ge(o,c),await(s==null?void 0:s(c.ref))},getContextIndex:async()=>yt(o),getContextData:async c=>we(o,c),getContext:async c=>wt(o,c),resolveContext:async c=>he(o,c),pruneContext:async c=>Re(o,c)}}import{nanoid as jo}from"nanoid";async function Oe(o,t){return o.length?!t||!t.HX_ORA_URL||!t.HX_API_KEY?(console.error("extractDocuments: missing HX_ORA_URL or HX_API_KEY"),o.map(e=>({name:e.name,text:""}))):await Promise.all(o.map(async e=>{try{let s=await fetch(`${t.HX_ORA_URL}/internal/files/extract`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t.HX_API_KEY},body:JSON.stringify(e)});if(!s.ok)return console.error(`extractDocuments: ${e.name} failed ${s.status}`),{name:e.name,text:""};let r=await s.json();return{name:e.name,text:r.text||""}}catch(s){return console.error(`extractDocuments: ${e.name} threw`,s),{name:e.name,text:""}}})):[]}function io(o,t){if(o==="images"||o==="files"||o==="file_content")return!0;let n=o.indexOf(".");if(n===-1)return!1;let e=t.find(i=>i.id===o.slice(0,n));if(!e)return!1;let s=o.slice(n+1).split(".")[0],r=X(e).find(i=>i.name===s);return(r==null?void 0:r.type)==="image"||(r==null?void 0:r.type)==="file"}function ao(o,t){var i,c,d,u,p;let n=Array.isArray((i=o.data)==null?void 0:i.varMapping)?o.data.varMapping:[];if(n.length===0)return null;let e=((d=(c=t.flowData)==null?void 0:c.state)==null?void 0:d.nodes)||[],s={},r=new Set;for(let f of n){let l=(u=f.var)==null?void 0:u.trim(),m=(p=f.from)==null?void 0:p.trim();if(!l||!m)throw new Error(`Answer node ${o.id} has an incomplete variable mapping`);if(r.has(l))throw new Error(`Answer node ${o.id} has duplicate output key "${l}"`);if(io(m,e))throw new Error(`Answer node ${o.id} cannot persist binary source "${m}"`);let a=tt(m,{context:t.context||{},results:t.results||{},nodes:e});(a==null||a==="")&&(a=f.default??""),s[l]=a,r.add(l)}try{JSON.stringify(s)}catch{throw new Error(`Answer node ${o.id} produced a value that is not JSON serializable`)}return s}async function Ft(o,t,n,e,s,r,i){var d,u,p;e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c;try{c=ao(t,n)}catch(f){throw e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(f)}}),f}c&&o.outputCollector&&o.outputCollector.add(t.id,c);try{let f=await((d=o.getMessages)==null?void 0:d.call(o))??[],l=((u=f[f.length-1])==null?void 0:u.type)==="text"?f[f.length-1].content:"NO-TEXT";i==null||i({type:"answer_node",payload:{userMessage:(p=n==null?void 0:n.context)==null?void 0:p.user_input,answer:l}})}catch(f){console.error("answerNodeRunner: failed to emit answer telemetry:",f),e==null||e({type:"debug",content:"Warning: failed to emit answer telemetry"})}s==null||s(t.id,{type:"answerNode",message:"Answer response for: "+t.data.response,saved:!0,persistenceRequested:!!c&&!!o.outputCollector,persisted:!1,...o.runId?{runId:o.runId}:{}}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"success"}})}function z(o,t,n,e,s){var c,d,u;let r=(s==null?void 0:s.callerTag)??"llmNodeRunner",i=(s==null?void 0:s.serializeNonStrings)??!1;try{return ie(o,t,{context:n.context??{},results:n.results??{},nodes:((d=(c=n.flowData)==null?void 0:c.state)==null?void 0:d.nodes)??[],secrets:(u=s==null?void 0:s.sessionEnv)==null?void 0:u.secrets},{callerTag:r,serializeNonStrings:i,onError:p=>{e==null||e({type:`error:${r}`,content:p})}})}catch(p){return console.error(p),"error"}}var Pt="[redacted]",_e=8*1024;function co(o){if(o==null)return{value:o,truncated:!1};let t=typeof o=="string"?o:JSON.stringify(o),n=new TextEncoder().encode(t);if(n.byteLength<=_e){if(typeof o=="string")return{value:o,truncated:!1};try{return{value:JSON.parse(t),truncated:!1}}catch{return{value:t,truncated:!1}}}let e=n.slice(0,_e);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(e),truncated:!0}}function lo(o,t){let n={};for(let e of X(o))n[e.name]=pt(t,e.path??"");return n}var Dt=(o,t,n,e,s)=>z(o,t,n,s,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:e});async function Mt(o,t,n,e,s,r,i){var u,p,f,l,m,a;`${t.id}`,e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c=null,d=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(n.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(n.results||{}));let g=((u=t.data)==null?void 0:u.url)||"",y=Dt(g,t,n,o,e);if(console.log("[apiNodeRunner] resolved url:",Y(g)?nt(y):y),!y){e==null||e({type:"error:apiNodeRunner",content:"Missing url"}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:"Missing url"}}),s==null||s(t.id,c);return}let h=(((p=t.data)==null?void 0:p.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",h);let w=((f=t.data)==null?void 0:f.headers)||{},x={},R={};for(let U in w)if(Object.prototype.hasOwnProperty.call(w,U)){let K=String(w[U]??"");R[U]=Y(K),x[U]=Dt(K,t,n,o,e)}let T,_=!1;if(h!=="GET"&&h!=="HEAD"&&((l=t.data)==null?void 0:l.body)!==void 0){let U=typeof t.data.body=="string"?t.data.body:JSON.stringify(t.data.body);_=Y(U),T=Dt(U,t,n,o,e),!x["Content-Type"]&&!x["content-type"]&&(x["Content-Type"]="application/json")}let A={};for(let U in x)A[U]=R[U]?Pt:x[U];console.log("[apiNodeRunner] headers:",JSON.stringify(A)),console.log("[apiNodeRunner] body:",_?Pt:T),e==null||e({type:"info:apiNodeRunner:request",content:{nodeId:t.id,method:h,url:Y(g)?nt(y):y,headers:A,body:_?Pt:T}});let P=Number((m=t.data)==null?void 0:m.timeoutMs),E=new AbortController,D=Number.isFinite(P)&&P>0?setTimeout(()=>E.abort(),P):null,F;try{console.log("[apiNodeRunner] fetching..."),F=await fetch(y,{method:h,headers:x,body:T,signal:E.signal}),console.log("[apiNodeRunner] fetch returned status:",F.status)}finally{D&&clearTimeout(D)}let H=F.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",H);let I;H.includes("application/json")?I=await F.json():I=await F.text(),console.log("[apiNodeRunner] payload preview:",typeof I=="string"?I.slice(0,200):JSON.stringify(I).slice(0,200)),c={ok:F.ok,status:F.status,data:I};let C=Date.now()-d;i==null||i({type:"api_call",payload:{nodeId:t.id,url:y,method:h,status:F.status,latencyMs:C}});let{value:k,truncated:j}=co(I);e==null||e({type:"info:apiNodeRunner:response",content:{nodeId:t.id,ok:F.ok,status:F.status,latencyMs:C,data:k,truncated:j,outVars:lo(t,c)}}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"success"}})}catch(g){console.error("Error processing ApiNode:",g),e==null||e({type:"error:apiNodeRunner",content:`API node execution failed: ${g}`}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(g)}})}finally{console.log("[apiNodeRunner] final result:",(a=JSON.stringify(c))==null?void 0:a.slice(0,300)),s==null||s(t.id,c)}}var uo="[redacted]",ke=8*1024;function bt(o,t){if(typeof o=="string")return Y(o)?typeof t=="string"&&/^https?:\/\//i.test(t)?nt(t):uo:t;if(o&&typeof o=="object"&&!Array.isArray(o)){let n={},e=t&&typeof t=="object"&&!Array.isArray(t)?t:{};for(let[s,r]of Object.entries(o))n[s]=bt(r,e[s]);return n}if(Array.isArray(o)){let n=Array.isArray(t)?t:[];return o.map((e,s)=>bt(e,n[s]))}return t}function po(o){if(o==null)return{value:o,truncated:!1};let t=typeof o=="string"?o:JSON.stringify(o),n=new TextEncoder().encode(t);if(n.byteLength<=ke){if(typeof o=="string")return{value:o,truncated:!1};try{return{value:JSON.parse(t),truncated:!1}}catch{return{value:t,truncated:!1}}}let e=n.slice(0,ke);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(e),truncated:!0}}function fo(o,t){let n={};for(let e of X(o))n[e.name]=pt(t,e.path??"");return n}var mo=(o,t,n,e,s)=>z(o,t,n,s,{callerTag:"toolNodeRunner",serializeNonStrings:!0,sessionEnv:e});function Tt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:{}}function go(o){let t=Tt(o);if(Array.isArray(t.enum)&&t.enum.length>0)return t.enum.every(s=>typeof s=="string"||typeof s=="number")?"enum":"unsupported";switch(Array.isArray(t.type)?t.type.find(e=>typeof e=="string"&&e!=="null"):t.type){case"string":return"string";case"number":return"number";case"integer":return"integer";case"boolean":return"boolean";case"object":return"object";case"array":return"array";default:return"unsupported"}}function yo(o,t){var i,c;let n={},e={},s=((i=o.data)==null?void 0:i.inputSchema)??t;if(s&&typeof s=="object"&&!Array.isArray(s)){e=Tt(Tt(s).properties);for(let[d,u]of Object.entries(e))n[d]=go(u);return{types:n,properties:e}}let r=(c=o.data)==null?void 0:c.argTypes;if(r&&typeof r=="object"&&!Array.isArray(r))for(let[d,u]of Object.entries(r))typeof u=="string"&&(n[d]=u);return{types:n,properties:e}}function wo(o,t,n){if(o.trim()!==""){if(o==="null"&&t&&t!=="string"&&t!=="enum")return null;switch(t){case"string":return o;case"enum":{let e=Tt(n).enum;if(Array.isArray(e)){let s=e.find(r=>String(r)===o);if(s!==void 0)return s}return o}case"number":{let e=Number(o);return Number.isFinite(e)?e:o}case"integer":{let e=Number.parseInt(o,10);return Number.isFinite(e)?e:o}case"boolean":return o==="true"?!0:o==="false"?!1:o;case"object":case"array":case"unsupported":try{return JSON.parse(o)}catch{return o}default:return o}}}function ho(o){return o===void 0||typeof o=="string"&&o.trim()===""}function Ut(o,t,n,e,s,r,i){if(typeof o=="string"){let c=o.includes("{{")?mo(o,t,n,e,s):o;return wo(c,r,i)}if(o&&typeof o=="object"&&!Array.isArray(o)){let c={};for(let[d,u]of Object.entries(o))c[d]=Ut(u,t,n,e,s);return c}return Array.isArray(o)?o.map(c=>Ut(c,t,n,e,s)):o}function Ro(o,t,n,e,s,r){let i={};for(let[c,d]of Object.entries(o)){let u=Ut(d,t,n,e,s,r.types[c],r.properties[c]);ho(u)||(i[c]=u)}return i}async function xo(o){if(o.toolCatalog)return o.toolCatalog;if(!o.env)return o.toolCatalog={},o.toolCatalog;let t=await ae(o.env),n={};for(let e of t)e!=null&&e.id&&(n[e.id]=e);return o.toolCatalog=n,n}async function Io(o){if(o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs={},o.toolDefs;let t=await ft(o.env),n={};for(let e of t)e!=null&&e.id&&(n[e.id]=e);return o.toolDefs=n,n}async function jt(o,t,n,e,s,r,i){var p,f,l,m,a,g,y,h,w,x,R,T;`${t.id}`,e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c={ok:!1,data:null,error:null},d=Date.now(),u=((p=t.data)==null?void 0:p.source)==="http"?"http":"catalog";try{let _=(f=t.data)!=null&&f.args&&typeof t.data.args=="object"&&!Array.isArray(t.data.args)?t.data.args:{},A,P;if(u==="http"){let C=typeof((l=t.data)==null?void 0:l.toolId)=="string"?t.data.toolId.trim():"";if(!C)throw new Error("HTTP tool nodes require toolId");if(P=(await Io(o))[C],!P)throw new Error(`Tool ${C} not found`);A=P.inputSchema}let E=yo(t,A),D=Ro(_,t,n,o,e,E);if(e==null||e({type:"info:toolNodeRunner:request",content:{nodeId:t.id,source:u,catalogId:(m=t.data)==null?void 0:m.catalogId,toolSlug:(a=t.data)==null?void 0:a.toolSlug,toolId:(g=t.data)==null?void 0:g.toolId,args:bt(_,D)}}),u==="catalog"){let C=typeof((y=t.data)==null?void 0:y.catalogId)=="string"?t.data.catalogId.trim():"",k=typeof((h=t.data)==null?void 0:h.toolSlug)=="string"?t.data.toolSlug.trim():"";if(!C||!k)throw new Error("Catalog tool nodes require catalogId and toolSlug");let U=(await xo(o))[C];if(!U)throw new Error(`Tool catalog entry ${C} not found or disabled`);let K=typeof((w=t.data)==null?void 0:w.toolVersion)=="string"?t.data.toolVersion.trim():"",M=await ce(o,{toolSlug:k,connectionScope:U.connectionScope,toolVersion:K||null,toolkitVersion:U.toolkitVersion,arguments:D});c={ok:M.ok,data:M.ok?M.data:null,error:M.ok?null:M.error??"Tool execution failed"}}else{let C=mt(P,o,n,e);if(!C.execute)throw new Error(`Tool ${(x=t.data)==null?void 0:x.toolId} is missing an execute handler`);let k=await C.execute(D,{}),j=k&&typeof k=="object"&&"error"in k&&k.error?String(k.error):null;c={ok:!j,data:k,error:j}}let F=Date.now()-d;i==null||i({type:"tool_call",payload:{nodeId:t.id,url:u==="catalog"?`composio:${((R=t.data)==null?void 0:R.toolSlug)??""}`:`tool:${((T=t.data)==null?void 0:T.toolId)??""}`,method:"EXECUTE",status:c.ok?200:502,latencyMs:F}});let{value:H,truncated:I}=po(c.data);e==null||e({type:"info:toolNodeRunner:response",content:{nodeId:t.id,ok:c.ok,latencyMs:F,data:H,truncated:I,error:c.error,outVars:fo(t,c)}}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:c.ok?"success":"error",error:c.error??void 0}})}catch(_){let A=_ instanceof Error?_.message:String(_);c={ok:!1,data:null,error:A},e==null||e({type:"error:toolNodeRunner",content:`Tool node execution failed: ${A}`}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:A}})}finally{s==null||s(t.id,c)}}import{generateObject as To}from"ai";import{z as $e}from"zod";async function Et(o,t,n,e,s,r,i){var g,y,h;e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c=(n==null?void 0:n.context)??{},d=String(((g=t==null?void 0:t.data)==null?void 0:g.input_variable)||"user_input").trim(),u=(c==null?void 0:c[d])??"",p=Array.isArray((y=t==null?void 0:t.data)==null?void 0:y.items)?t.data.items:[];if(p.length===0){e==null||e({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let f=String((h=p[p.length-1])==null?void 0:h.id);if(!u||String(u).trim().length===0){e==null||e({type:"warning:classifier",content:"No input for classification \u2014 falling back to last item."}),s==null||s(t.id,{classification:f}),n.context=n.context||{},n.context.classified_id=f,r==null||r(n);return}let m=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
|
|
17
|
+
ts = excluded.ts`}async function ht(o){return o.sql`SELECT ref, domain, description, cycle, meta, ts FROM context ORDER BY ts ASC`}async function Re(o){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context ORDER BY ts ASC`}async function Rt(o,t){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${t} LIMIT 1`[0]??null}async function xe(o,t){var e;return((e=o.sql`SELECT data FROM context WHERE ref = ${t} LIMIT 1`[0])==null?void 0:e.data)??null}async function Ie(o,t){let n=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${t} LIMIT 1`;if(n[0])return n[0];let e=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref LIKE ${t+"%"} LIMIT 2`;return e.length===1?e[0]:null}async function Te(o,t){o.sql`DELETE FROM context WHERE domain = 'tool' AND cycle <= ${t}`}async function Ne(o){var n;return((n=o.sql`SELECT COALESCE(MAX(cycle), 0) AS maxCycle FROM context`[0])==null?void 0:n.maxCycle)??0}async function xt(o){o.sql`DELETE FROM context`}async function Ae(o){await io(o),await ao(o)}function kt(o){return{"Content-Type":"application/json",Authorization:o.HX_API_KEY}}function It(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}var co="anonymous:";function Ce(o,t){return(o==null?void 0:o.trim())||`${co}${t}`}async function Ft(o,t){if(!It(o))return null;let n=await fetch(`${o.HX_ORA_URL}/internal/runs`,{method:"POST",headers:kt(o),body:JSON.stringify(t)});return n.ok?await n.json():(console.error("[oraTriggers] createRun failed",n.status,await n.text().catch(()=>"")),null)}async function rt(o,t){if(!It(o))return{claimed:!0};let n=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(t)}/claim`,{method:"POST",headers:kt(o)});if(!n.ok){let e=await n.text().catch(()=>"");throw new Error(`claimRun ${t} failed with ${n.status}: ${e}`)}return await n.json()}async function Tt(o,t,n,e=3){if(!It(o))return!0;for(let s=1;s<=e;s++){try{let r=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(t)}/complete`,{method:"POST",headers:kt(o),body:JSON.stringify(n)});if(r.ok||r.status===409)return!0;if(r.status===404)return console.error(`[oraTriggers] completeRun ${t} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${t} attempt ${s} failed with ${r.status}`)}catch(r){console.warn(`[oraTriggers] completeRun ${t} attempt ${s} threw`,r)}s<e&&await new Promise(r=>setTimeout(r,250*s))}return console.error(`[oraTriggers] completeRun ${t} exhausted ${e} attempts; hx-ora will time the run out`),!1}async function Oe(o,t){if(!It(o))return Promise.resolve();try{return await Ft(o,t)}catch(n){return console.error("[oraTriggers] recordRun failed",n),null}}var Pt=Object.freeze({}),lo="__SYSTEM_";function _e(o){return o.startsWith(lo)}function uo(o){let t={};for(let[n,e]of Object.entries(o))_e(n)||(t[n]=e);return Object.freeze(t)}async function Nt(o,t){if(!t)return Pt;if(o.HX_ORA_URL&&o.HX_API_KEY)try{let s=await fetch(`${o.HX_ORA_URL}/internal/secrets`,{headers:{Authorization:o.HX_API_KEY}});if(s.ok){let r=await s.json();if(r.secrets)return uo(r.secrets)}else console.warn(`[secrets] API failed with status ${s.status}, falling back to KV`)}catch(s){console.error("[secrets] API request failed, falling back to KV",s)}let n=o.ORA_SECRETS;if(!n)return Pt;let e=`${t}:`;try{let s=await n.list({prefix:e,limit:1e3});s.list_complete===!1&&console.warn(`[secrets] tenant=${t} exceeded list page; truncating to first 1000 keys`);let r=s.keys.filter(d=>!_e(d.name.slice(e.length))),i=await Promise.all(r.map(async d=>{let u=await n.get(d.name);return u!==null?[d.name.slice(e.length),u]:null})),c={};for(let d of i){if(!d)continue;let[u,p]=d;u&&(c[u]=p)}return Object.freeze(c)}catch(s){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:t,err:s}),Pt}}import{nanoid as Zn}from"nanoid";function it(o){var s,r;let t=(s=o==null?void 0:o.flowData)==null?void 0:s.state,e=((t==null?void 0:t.nodes)??((r=o==null?void 0:o.flowData)==null?void 0:r.nodes)??[]).find(i=>i.type==="startNode");return e==null?void 0:e.data}async function $e(o,t){return typeof t.cycle=="number"&&Number.isFinite(t.cycle)?t.cycle+1:await Ne(o)+1}function ke(o,t,n,e,s){let r=pt(it(n));return{...t,memoryConfig:r,cycle:e,setContext:async c=>{await he(o,c),await(s==null?void 0:s(c.ref))},getContextIndex:async()=>ht(o),getContextData:async c=>xe(o,c),getContext:async c=>Rt(o,c),resolveContext:async c=>Ie(o,c),pruneContext:async c=>Te(o,c)}}import{nanoid as So}from"nanoid";async function Fe(o,t){return o.length?!t||!t.HX_ORA_URL||!t.HX_API_KEY?(console.error("extractDocuments: missing HX_ORA_URL or HX_API_KEY"),o.map(e=>({name:e.name,text:""}))):await Promise.all(o.map(async e=>{try{let s=await fetch(`${t.HX_ORA_URL}/internal/files/extract`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t.HX_API_KEY},body:JSON.stringify(e)});if(!s.ok)return console.error(`extractDocuments: ${e.name} failed ${s.status}`),{name:e.name,text:""};let r=await s.json();return{name:e.name,text:r.text||""}}catch(s){return console.error(`extractDocuments: ${e.name} threw`,s),{name:e.name,text:""}}})):[]}function po(o,t,n){var e,s,r,i;return et(((s=(e=n.flowData)==null?void 0:e.state)==null?void 0:s.nodes)??[],((i=(r=n.flowData)==null?void 0:r.state)==null?void 0:i.edges)??[],t.id).some(c=>c.ref===o&&(c.type==="image"||c.type==="file"))}function fo(o,t){var i,c,d,u,p,g,l;let n=Array.isArray((i=o.data)==null?void 0:i.outputMapping)?o.data.outputMapping:[];if(n.length===0)return null;let e=((d=(c=t.flowData)==null?void 0:c.state)==null?void 0:d.nodes)||[],s={},r=new Set;for(let f of n){let a=(u=f.key)==null?void 0:u.trim(),m=(p=f.from)==null?void 0:p.trim();if(!a||!m)throw new Error(`Answer node ${o.id} has an incomplete variable mapping`);if(r.has(a))throw new Error(`Answer node ${o.id} has duplicate output key "${a}"`);if(po(m,o,t))throw new Error(`Answer node ${o.id} cannot persist binary source "${m}"`);let y=K(m,{context:t.context||{},results:t.results||{},nodes:e,edges:((l=(g=t.flowData)==null?void 0:g.state)==null?void 0:l.edges)??[],currentNodeId:o.id}),w=y.value;if(y.missing||w===void 0||w===null){if(f.default===void 0)throw new V(y.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Answer node ${o.id} could not resolve output "${m}"`);w=f.default}s[a]=w,r.add(a)}try{JSON.stringify(s)}catch{throw new Error(`Answer node ${o.id} produced a value that is not JSON serializable`)}return s}async function Dt(o,t,n,e,s,r,i){var d,u,p;e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c;try{c=fo(t,n)}catch(g){throw e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(g)}}),g}c&&o.outputCollector&&o.outputCollector.add(t.id,c);try{let g=await((d=o.getMessages)==null?void 0:d.call(o))??[],l=((u=g[g.length-1])==null?void 0:u.type)==="text"?g[g.length-1].content:"NO-TEXT";i==null||i({type:"answer_node",payload:{userMessage:(p=n==null?void 0:n.context)==null?void 0:p.user_input,answer:l}})}catch(g){console.error("answerNodeRunner: failed to emit answer telemetry:",g),e==null||e({type:"debug",content:"Warning: failed to emit answer telemetry"})}s==null||s(t.id,{type:"answerNode",message:"Answer response for: "+t.data.response,saved:!0,persistenceRequested:!!c&&!!o.outputCollector,persisted:!1,...o.runId?{runId:o.runId}:{}}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"success"}})}function G(o,t,n,e,s){var c,d,u,p,g;let r=(s==null?void 0:s.callerTag)??"llmNodeRunner",i=(s==null?void 0:s.serializeNonStrings)??!1;return le(o,t,{context:n.context??{},results:n.results??{},nodes:((d=(c=n.flowData)==null?void 0:c.state)==null?void 0:d.nodes)??[],edges:((p=(u=n.flowData)==null?void 0:u.state)==null?void 0:p.edges)??[],currentNodeId:t.id,secrets:(g=s==null?void 0:s.sessionEnv)==null?void 0:g.secrets},{callerTag:r,serializeNonStrings:i,onError:l=>{e==null||e({type:`error:${r}`,content:l})}})}var Ut="[redacted]",Pe=8*1024;function mo(o){if(o==null)return{value:o,truncated:!1};let t=typeof o=="string"?o:JSON.stringify(o),n=new TextEncoder().encode(t);if(n.byteLength<=Pe){if(typeof o=="string")return{value:o,truncated:!1};try{return{value:JSON.parse(t),truncated:!1}}catch{return{value:t,truncated:!1}}}let e=n.slice(0,Pe);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(e),truncated:!0}}function go(o,t){let n={};for(let e of ft(o))n[e.name]=mt(t,e.path??"");return n}var Mt=(o,t,n,e,s)=>G(o,t,n,s,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:e});async function bt(o,t,n,e,s,r,i){var u,p,g,l,f,a;`${t.id}`,e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c=null,d=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(n.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(n.results||{}));let m=((u=t.data)==null?void 0:u.url)||"",y=Mt(m,t,n,o,e);if(console.log("[apiNodeRunner] resolved url:",B(m)?st(y):y),!y){e==null||e({type:"error:apiNodeRunner",content:"Missing url"}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:"Missing url"}}),s==null||s(t.id,c);return}let w=(((p=t.data)==null?void 0:p.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",w);let h=((g=t.data)==null?void 0:g.headers)||{},I={},R={};for(let M in h)if(Object.prototype.hasOwnProperty.call(h,M)){let X=String(h[M]??"");R[M]=B(X),I[M]=Mt(X,t,n,o,e)}let x,O=!1;if(w!=="GET"&&w!=="HEAD"&&((l=t.data)==null?void 0:l.body)!==void 0){let M=typeof t.data.body=="string"?t.data.body:JSON.stringify(t.data.body);O=B(M),x=Mt(M,t,n,o,e),!I["Content-Type"]&&!I["content-type"]&&(I["Content-Type"]="application/json")}let C={};for(let M in I)C[M]=R[M]?Ut:I[M];console.log("[apiNodeRunner] headers:",JSON.stringify(C)),console.log("[apiNodeRunner] body:",O?Ut:x),e==null||e({type:"info:apiNodeRunner:request",content:{nodeId:t.id,method:w,url:B(m)?st(y):y,headers:C,body:O?Ut:x}});let D=Number((f=t.data)==null?void 0:f.timeoutMs),j=new AbortController,k=Number.isFinite(D)&&D>0?setTimeout(()=>j.abort(),D):null,_;try{console.log("[apiNodeRunner] fetching..."),_=await fetch(y,{method:w,headers:I,body:x,signal:j.signal}),console.log("[apiNodeRunner] fetch returned status:",_.status)}finally{k&&clearTimeout(k)}let L=_.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",L);let N;L.includes("application/json")?N=await _.json():N=await _.text(),console.log("[apiNodeRunner] payload preview:",typeof N=="string"?N.slice(0,200):JSON.stringify(N).slice(0,200)),c={ok:_.ok,status:_.status,data:N};let T=Date.now()-d;i==null||i({type:"api_call",payload:{nodeId:t.id,url:y,method:w,status:_.status,latencyMs:T}});let{value:F,truncated:U}=mo(N);e==null||e({type:"info:apiNodeRunner:response",content:{nodeId:t.id,ok:_.ok,status:_.status,latencyMs:T,data:F,truncated:U,outVars:go(t,c)}}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"success"}})}catch(m){console.error("Error processing ApiNode:",m),e==null||e({type:"error:apiNodeRunner",content:`API node execution failed: ${m}`}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(m)}})}finally{console.log("[apiNodeRunner] final result:",(a=JSON.stringify(c))==null?void 0:a.slice(0,300)),s==null||s(t.id,c)}}var yo="[redacted]",De=8*1024;function Et(o,t){if(typeof o=="string")return B(o)?typeof t=="string"&&/^https?:\/\//i.test(t)?st(t):yo:t;if(o&&typeof o=="object"&&!Array.isArray(o)){let n={},e=t&&typeof t=="object"&&!Array.isArray(t)?t:{};for(let[s,r]of Object.entries(o))n[s]=Et(r,e[s]);return n}if(Array.isArray(o)){let n=Array.isArray(t)?t:[];return o.map((e,s)=>Et(e,n[s]))}return t}function wo(o){if(o==null)return{value:o,truncated:!1};let t=typeof o=="string"?o:JSON.stringify(o),n=new TextEncoder().encode(t);if(n.byteLength<=De){if(typeof o=="string")return{value:o,truncated:!1};try{return{value:JSON.parse(t),truncated:!1}}catch{return{value:t,truncated:!1}}}let e=n.slice(0,De);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(e),truncated:!0}}function ho(o,t){let n={};for(let e of ft(o))n[e.name]=mt(t,e.path??"");return n}var Ro=(o,t,n,e,s)=>G(o,t,n,s,{callerTag:"toolNodeRunner",serializeNonStrings:!0,sessionEnv:e});function At(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:{}}function xo(o){let t=At(o);if(Array.isArray(t.enum)&&t.enum.length>0)return t.enum.every(s=>typeof s=="string"||typeof s=="number")?"enum":"unsupported";switch(Array.isArray(t.type)?t.type.find(e=>typeof e=="string"&&e!=="null"):t.type){case"string":return"string";case"number":return"number";case"integer":return"integer";case"boolean":return"boolean";case"object":return"object";case"array":return"array";default:return"unsupported"}}function Io(o,t){var i,c;let n={},e={},s=((i=o.data)==null?void 0:i.inputSchema)??t;if(s&&typeof s=="object"&&!Array.isArray(s)){e=At(At(s).properties);for(let[d,u]of Object.entries(e))n[d]=xo(u);return{types:n,properties:e}}let r=(c=o.data)==null?void 0:c.argTypes;if(r&&typeof r=="object"&&!Array.isArray(r))for(let[d,u]of Object.entries(r))typeof u=="string"&&(n[d]=u);return{types:n,properties:e}}function To(o,t,n){if(o.trim()!==""){if(o==="null"&&t&&t!=="string"&&t!=="enum")return null;switch(t){case"string":return o;case"enum":{let e=At(n).enum;if(Array.isArray(e)){let s=e.find(r=>String(r)===o);if(s!==void 0)return s}return o}case"number":{let e=Number(o);return Number.isFinite(e)?e:o}case"integer":{let e=Number.parseInt(o,10);return Number.isFinite(e)?e:o}case"boolean":return o==="true"?!0:o==="false"?!1:o;case"object":case"array":case"unsupported":try{return JSON.parse(o)}catch{return o}default:return o}}}function No(o){return o===void 0||typeof o=="string"&&o.trim()===""}function jt(o,t,n,e,s,r,i){if(typeof o=="string"){let c=o.includes("{{")?Ro(o,t,n,e,s):o;return To(c,r,i)}if(o&&typeof o=="object"&&!Array.isArray(o)){let c={};for(let[d,u]of Object.entries(o))c[d]=jt(u,t,n,e,s);return c}return Array.isArray(o)?o.map(c=>jt(c,t,n,e,s)):o}function Ao(o,t,n,e,s,r){let i={};for(let[c,d]of Object.entries(o)){let u=jt(d,t,n,e,s,r.types[c],r.properties[c]);No(u)||(i[c]=u)}return i}async function Co(o){if(o.toolCatalog)return o.toolCatalog;if(!o.env)return o.toolCatalog={},o.toolCatalog;let t=await de(o.env),n={};for(let e of t)e!=null&&e.id&&(n[e.id]=e);return o.toolCatalog=n,n}async function Oo(o){if(o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs={},o.toolDefs;let t=await gt(o.env),n={};for(let e of t)e!=null&&e.id&&(n[e.id]=e);return o.toolDefs=n,n}async function Lt(o,t,n,e,s,r,i){var p,g,l,f,a,m,y,w,h,I,R,x;`${t.id}`,e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c={ok:!1,data:null,error:null},d=Date.now(),u=((p=t.data)==null?void 0:p.source)==="http"?"http":"catalog";try{let O=(g=t.data)!=null&&g.args&&typeof t.data.args=="object"&&!Array.isArray(t.data.args)?t.data.args:{},C,D;if(u==="http"){let T=typeof((l=t.data)==null?void 0:l.toolId)=="string"?t.data.toolId.trim():"";if(!T)throw new Error("HTTP tool nodes require toolId");if(D=(await Oo(o))[T],!D)throw new Error(`Tool ${T} not found`);C=D.inputSchema}let j=Io(t,C),k=Ao(O,t,n,o,e,j);if(e==null||e({type:"info:toolNodeRunner:request",content:{nodeId:t.id,source:u,catalogId:(f=t.data)==null?void 0:f.catalogId,toolSlug:(a=t.data)==null?void 0:a.toolSlug,toolId:(m=t.data)==null?void 0:m.toolId,args:Et(O,k)}}),u==="catalog"){let T=typeof((y=t.data)==null?void 0:y.catalogId)=="string"?t.data.catalogId.trim():"",F=typeof((w=t.data)==null?void 0:w.toolSlug)=="string"?t.data.toolSlug.trim():"";if(!T||!F)throw new Error("Catalog tool nodes require catalogId and toolSlug");let M=(await Co(o))[T];if(!M)throw new Error(`Tool catalog entry ${T} not found or disabled`);let X=typeof((h=t.data)==null?void 0:h.toolVersion)=="string"?t.data.toolVersion.trim():"",b=await ue(o,{toolSlug:F,connectionScope:M.connectionScope,toolVersion:X||null,toolkitVersion:M.toolkitVersion,arguments:k});c={ok:b.ok,data:b.ok?b.data:null,error:b.ok?null:b.error??"Tool execution failed"}}else{let T=yt(D,o,n,e);if(!T.execute)throw new Error(`Tool ${(I=t.data)==null?void 0:I.toolId} is missing an execute handler`);let F=await T.execute(k,{}),U=F&&typeof F=="object"&&"error"in F&&F.error?String(F.error):null;c={ok:!U,data:F,error:U}}let _=Date.now()-d;i==null||i({type:"tool_call",payload:{nodeId:t.id,url:u==="catalog"?`composio:${((R=t.data)==null?void 0:R.toolSlug)??""}`:`tool:${((x=t.data)==null?void 0:x.toolId)??""}`,method:"EXECUTE",status:c.ok?200:502,latencyMs:_}});let{value:L,truncated:N}=wo(c.data);e==null||e({type:"info:toolNodeRunner:response",content:{nodeId:t.id,ok:c.ok,latencyMs:_,data:L,truncated:N,error:c.error,outVars:ho(t,c)}}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:c.ok?"success":"error",error:c.error??void 0}})}catch(O){let C=O instanceof Error?O.message:String(O);c={ok:!1,data:null,error:C},e==null||e({type:"error:toolNodeRunner",content:`Tool node execution failed: ${C}`}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:C}})}finally{s==null||s(t.id,c)}}import{generateObject as _o}from"ai";import{z as Ue}from"zod";async function Ht(o,t,n,e,s,r,i){var a,m,y,w,h,I,R;e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c=String(((a=t==null?void 0:t.data)==null?void 0:a.input_variable)||"user_input").trim(),d;try{let x=K(c,{context:n.context??{},results:n.results??{},nodes:((y=(m=n.flowData)==null?void 0:m.state)==null?void 0:y.nodes)??[],edges:((h=(w=n.flowData)==null?void 0:w.state)==null?void 0:h.edges)??[],currentNodeId:t.id});if(x.missing)throw new Error(`Classifier input "${c}" did not produce a value`);d=x.value}catch(x){throw e==null||e({type:"error:classifier",content:String(x)}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(x)}}),x}let u=Array.isArray((I=t==null?void 0:t.data)==null?void 0:I.items)?t.data.items:[];if(u.length===0){e==null||e({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let p=String((R=u[u.length-1])==null?void 0:R.id);if(!d||String(d).trim().length===0){e==null||e({type:"warning:classifier",content:"No input for classification \u2014 falling back to last item."}),s==null||s(t.id,{classification:p}),n.context=n.context||{},n.context.classified_id=p,r==null||r(n);return}let l=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
|
|
18
18
|
If the message is ambiguous or none clearly matches, choose the LAST category in the list.
|
|
19
19
|
|
|
20
20
|
Categories:
|
|
21
|
-
${
|
|
22
|
-
label: ${
|
|
23
|
-
keywords/topics: ${
|
|
21
|
+
${u.map(x=>{let O=x.keywords??x["keywords/topics"]??"",C=Array.isArray(O)?O.join(", "):String(O||"");return`- id: ${x.id}
|
|
22
|
+
label: ${x.label}
|
|
23
|
+
keywords/topics: ${C}`}).join(`
|
|
24
24
|
`)}
|
|
25
|
-
`,
|
|
26
|
-
"""${String(
|
|
25
|
+
`,f=`User message:
|
|
26
|
+
"""${String(d).trim()}"""
|
|
27
27
|
|
|
28
|
-
Select the best matching category id.`;try{let
|
|
28
|
+
Select the best matching category id.`;try{let x=Date.now(),O=u.map(T=>String(T.id)),C="gpt_4_1_mini",D=await ut(C,o);if(!D)throw new Error(`Model '${C}' not found in registry`);let{modelHandle:j,effectiveParams:k}=D,_=await _o({model:j,messages:[{role:"system",content:l},{role:"user",content:f}],schema:Ue.object({classification:Ue.enum(O).describe("The id of the best matching category")}),temperature:k.temperature??0}),L=Date.now()-x,N=_.object.classification;i==null||i({type:"class_telemetry",payload:{nodeId:t.id,totalLatency:L,model:_.response.modelId,usage:_.usage,options:O}}),i==null||i({type:"class_result",payload:{result:_}}),s==null||s(t.id,{classification:N}),n.context=n.context||{},n.context.classified_id=N,r==null||r(n),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"success"}})}catch(x){throw e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(x)}}),x}}import{stepCountIs as Po,streamText as Do}from"ai";import{nanoid as Uo}from"nanoid";import"zod";function Me(o,t){var c,d,u,p,g;let n=((c=o.data)==null?void 0:c.attachments)??[];if(!Array.isArray(n))throw new V("INVALID_EXPRESSION",`Node ${o.id} attachments must be an array`);let e=((u=(d=t.flowData)==null?void 0:d.state)==null?void 0:u.nodes)??[],s=((g=(p=t.flowData)==null?void 0:p.state)==null?void 0:g.edges)??[],r=et(e,s,o.id),i="";for(let l of n){if(typeof l!="string")throw new V("INVALID_EXPRESSION",`Node ${o.id} has an invalid attachment reference`);let f=r.find(m=>m.ref===l);if(!f)throw new V("OUT_OF_SCOPE",`Attachment "${l}" is not in this node's connection scope`);if(f.type!=="file"&&f.type!=="image")throw new V("UNKNOWN_OUTPUT",`Attachment "${l}" is not an image or file output`);if(f.type!=="file")continue;let a=K(l,{context:t.context??{},results:t.results??{},nodes:e,edges:s,currentNodeId:o.id});if(a.missing)throw new V(a.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${l}" did not produce a value`);if(typeof a.value!="string")throw new V("PATH_NOT_FOUND",`Attachment "${l}" must resolve to file text`);a.value.trim()&&(i+=(i?`
|
|
29
29
|
|
|
30
|
-
`:"")+l)}}return n}function Pe(o,t){var e,s,r,i,c,d;let n=[];if((e=o.data)!=null&&e.varMapping&&Array.isArray(o.data.varMapping))for(let u of o.data.varMapping){let p=u.from;if(!p)continue;let f=!1;if(p==="images")f=!0;else{let l=p.indexOf(".");if(l!==-1){let m=p.substring(0,l),a=p.substring(l+1).split(".")[0],g=(i=(r=(s=t.flowData)==null?void 0:s.state)==null?void 0:r.nodes)==null?void 0:i.find(y=>y.id===m);if(g){let h=X(g).find(w=>w.name===a);(h==null?void 0:h.type)==="image"&&(f=!0)}}}if(f){let l=tt(p,{context:t.context||{},results:t.results||{},nodes:((d=(c=t.flowData)==null?void 0:c.state)==null?void 0:d.nodes)||[]});Array.isArray(l)&&n.push(...l)}}return n}var No=ct({"../tools/composioDirectTool.ts":()=>import("./composioDirectTool-H3GSCIPY.js"),"../tools/composioTool.ts":()=>import("./composioTool-5LFWUQ7F.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-F3UYG6WX.js"),"../tools/recall.ts":()=>import("./recall-IABRCSHY.js"),"../tools/skillTool.ts":()=>import("./skillTool-PLHCAODG.js"),"../tools/tempTool.ts":()=>import("./tempTool-2RXAF56M.js"),"../tools/twitter.ts":()=>import("./twitter-OMDEG7T2.js"),"../tools/vectorize.ts":()=>import("./vectorize-UJXIDL2E.js")});var Co=ct({});function Lt(o,t,n,e,s){var i;if(!((i=e.memoryConfig)!=null&&i.enabled)||!e.memoryConfig.toolCache||!n.cacheable||!t||typeof t.execute!="function")return t;let r=t.execute.bind(t);return t.execute=async(c,...d)=>{var l;if(!e.getContextIndex)return r(c,...d);let u=await At(c),f=(await e.getContextIndex()).find(m=>{if(m.domain!=="tool")return!1;let a=Ot(m.meta);return a.toolName===o&&a.paramsHash===u});if(f){let m=await((l=e.getContext)==null?void 0:l.call(e,f.ref));if((m==null?void 0:m.data)!=null&&Ot(m.meta).truncated!==!0){s==null||s({type:"info:memory:cacheHit",content:{ref:m.ref,toolName:o}});try{return JSON.parse(m.data)}catch{return m.data}}}return r(c,...d)},t}async function ko(o,t,n,e){var p,f;if(!((p=n.memoryConfig)!=null&&p.enabled)||!n.setContext||n.cycle==null)return;let s=o.toolCalls??[],r=o.toolResults??[];if(!s.length||!r.length)return;let i=new Map;for(let l of r)l!=null&&l.toolCallId&&i.set(l.toolCallId,l);let c=Array.isArray((f=t==null?void 0:t.data)==null?void 0:f.tools)?t.data.tools:[],d=new Map;for(let l of c)l&&typeof l.id=="string"&&d.set(l.id,l);let u=new Map;for(let l of Object.values(n.toolDefs??{}))l&&l.name&&u.set(l.name,l);for(let l of s){let m=l.toolCallId,a=l.toolName,g=i.get(m);if(!a||!g||a==="readSkillRef")continue;let y=l.args??l.input,h=g.result??g.output,w=!1,x="",R="tool",T="",_=u.get(a);_&&_.kind==="skill"&&(w=!0,x=`skill:${a}`,R="skill",T=`Skill instructions for ${a}`),x||(x=await ee(a,y),T=te(y,h));let A=d.get(a)??c.find(D=>D.id===a),P=await At(y),E=typeof h=="string"?h:JSON.stringify(h??null);await n.setContext({ref:x,domain:R,description:T,data:E,cycle:n.cycle,meta:JSON.stringify({toolName:a,paramsHash:P,cacheable:(A==null?void 0:A.cacheable)===!0})}),e==null||e({type:"info:memory:updated",content:{ref:x}})}}async function $o(o,t,n,e){var f;let s=Array.isArray((f=n==null?void 0:n.data)==null?void 0:f.tools)?n.data.tools:[];if(s.length===0)return{};let r={},i=l=>{var x,R;let m=typeof(l==null?void 0:l.description)=="string"?l.description:"",a=l==null?void 0:l.inputSchema,g;try{let T=(a==null?void 0:a.shape)??(typeof((x=a==null?void 0:a._def)==null?void 0:x.shape)=="function"?a._def.shape():(R=a==null?void 0:a._def)==null?void 0:R.shape);T&&typeof T=="object"&&(g=T)}catch{}let y=g?Object.keys(g):[],h=m?`description="${m.length>120?m.slice(0,120)+"\u2026":m}"`:"description=(none)",w=y.length?`inputSchema={${y.join(", ")}}`:"inputSchema=(none)";return`${h} ${w}`},c=(()=>{let l=[],m=[],a=[],g=[];for(let h=0;h<s.length;h++){let w=s[h];!w||typeof w!="object"||typeof w.id!="string"?g.push(h):w.kind==="builtin"?l.push(w.id):w.kind==="skill"?a.push(w.id):w.kind==="http"||w.kind==="mcp"||w.kind==="composio"?m.push(w.id):g.push(h)}let y=[];return l.length&&y.push(`builtin[${l.join(", ")}]`),m.length&&y.push(`custom[${m.join(", ")}]`),a.length&&y.push(`skill[${a.join(", ")}]`),g.length&&y.push(`invalid@[${g.join(", ")}]`),y.join(" ")||"(none)"})();console.log(`[tools] node ${n.id} requested (${s.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 l=await ft(o.env),m={};for(let a of l)a&&a.id&&(m[a.id]=a);o.toolDefs=m}catch(l){e==null||e({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(l)}`}),o.toolDefs=o.toolDefs||{}}return d=!0,o.toolDefs},p=[];for(let l=0;l<s.length;l++){let m=s[l];if(!m||typeof m!="object"||typeof m.id!="string"||m.kind!=="builtin"&&m.kind!=="http"&&m.kind!=="mcp"&&m.kind!=="composio"&&m.kind!=="skill"){e==null||e({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${l}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let a=m;if(a.kind!=="builtin"){let y=(await u())[a.id];if(!y){console.error(`[tools] \u2717 custom '${a.id}': not found for tenant`),e==null||e({type:"error:llmNodeRunner",content:`custom tool '${a.id}' not found for this tenant`});continue}if(a.kind==="composio"){try{let w=await ue(y,o,t,e),x=Object.keys(w);for(let[R,T]of Object.entries(w))r[R]=Lt(R,T,a,o,e);console.log(`[tools] \u2713 composio '${a.id}' \u2192 ${x.length} tool(s)`)}catch(w){console.error(`[tools] \u2717 composio '${a.id}': ${String(w)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading composio tool '${a.id}': ${String(w)}`})}continue}if(a.kind==="skill"){if(y.kind!=="skill"){console.error(`[tools] \u2717 skill '${a.id}': row is of kind '${y.kind}', not 'skill'`),e==null||e({type:"error:llmNodeRunner",content:`tool '${a.id}' is not a skill`});continue}let w=y.name;if(r[w]){e==null||e({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin/other already registered, skipping skill '${a.id}'`});continue}try{r[w]=pe(y,o,t,e),p.push(y);let x=typeof y.execution=="string"?JSON.parse(y.execution):y.execution||{},R=Array.isArray(x.references)?x.references.map(T=>T==null?void 0:T.name):[];console.log(`[tools] \u2713 skill '${a.id}' \u2192 '${w}' (refs: ${R.join(", ")||"none"})`),e==null||e({type:"info:skill:registered",content:{skill:w,refCount:R.length,refs:R}})}catch(x){console.error(`[tools] \u2717 skill '${a.id}': ${String(x)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading skill tool '${a.id}': ${String(x)}`})}continue}let h=y.name;if(r[h]){e==null||e({type:"warn:llmNodeRunner",content:`tool name collision on '${h}' \u2014 builtin already registered, skipping custom tool '${a.id}'`});continue}try{let w=mt(y,o,t,e);r[h]=Lt(h,w,a,o,e),console.log(`[tools] \u2713 custom '${a.id}' \u2192 '${h}'`),console.log(`[tools] ${i(r[h])}`)}catch(w){console.error(`[tools] \u2717 custom '${a.id}': ${String(w)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading custom tool '${a.id}': ${String(w)}`})}continue}if(!de[a.id]){console.error(`[tools] \u2717 builtin '${a.id}': not in registry`),e==null||e({type:"error:llmNodeRunner",content:`Tool '${a.id}' not found in registry`});continue}try{let g;try{g=await No(`../tools/${a.id}.ts`)}catch{g=await Co(`../tools/${a.id}.js`)}let y;if(g[a.id])y=g[a.id];else if(g.default)y=g.default;else if(g.create)y=g.create;else{let A=Object.values(g);A.length>0&&(y=A[0])}if(!y){e==null||e({type:"error:llmNodeRunner",content:`No factory export found for tool '${a.id}'`});continue}let h,w,x={};if(a.params&&typeof a.params=="object"){if(typeof a.params.description=="string"?h=a.params.description:a.params.description!==void 0&&(e==null||e({type:"error:llmNodeRunner",content:`Invalid description for tool '${a.id}' \u2014 must be a string`})),a.params.inputSchema!==void 0){let A=a.params.inputSchema;typeof A=="object"&&(typeof A.safeParse=="function"||A._def)?w=A:typeof A=="object"&&A!==null&&A.type==="object"&&A.properties?(w=le(A),w||e==null||e({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${a.id}' \u2014 must be a Zod schema or JSON Schema object`})):e==null||e({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${a.id}' \u2014 must be a Zod schema or JSON Schema object`})}a.params.defaults!==void 0?typeof a.params.defaults=="object"&&a.params.defaults!==null&&!Array.isArray(a.params.defaults)?x=a.params.defaults:(e==null||e({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${a.id}' \u2014 must be an object`}),x={}):a.params.source!==void 0||a.params.target!==void 0?(e==null||e({type:"error:llmNodeRunner",content:`Invalid params for tool '${a.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),x={}):x={}}let R=y(o,t,x,e);h&&R&&typeof R=="object"&&(R.description=h),w&&R&&typeof R=="object"&&(R.inputSchema=w),r[a.id]=Lt(a.id,R,a,o,e);let T=[];h&&T.push("description"),w&&T.push("inputSchema"),Object.keys(x).length&&T.push(`defaults(${Object.keys(x).join(",")})`);let _=T.length?` [overrides: ${T.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${a.id}'${_}`),console.log(`[tools] ${i(R)}`)}catch(g){console.error(`[tools] \u2717 builtin '${a.id}': ${String(g)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading tool '${a.id}': ${String(g)}`});continue}}if(p.length>0)if(r.readSkillRef)e==null||e({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{r.readSkillRef=fe(o,p,t,e),console.log(`[tools] \u2713 registered readSkillRef tool for ${p.length} skill(s)`),e==null||e({type:"info:skill:readSkillRefRegistered",content:{skills:p.map(l=>l.name)}})}catch(l){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(l)}`)}return r}async function Ht(o,t,n,e,s,r,i){var P,E,D,F,H;`${t.id}`,e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c=!1;try{let I=(P=n.flowData)==null?void 0:P.state;if(I&&I.edges&&I.nodes){let C=I.edges.filter(k=>k.source===t.id);if(C.length>0){let k=I.nodes.find(j=>j.id===C[0].target);k&&k.type==="answerNode"&&(c=!0)}}}catch(I){console.error("Error determining next node for streaming:",I)}let d=z(t.data.template,t,n,e,{sessionEnv:o});(!d||!d.trim())&&(d="Answer straight forward to the user, dont offer any other option to continue");let u=d,p="";if((E=o.memoryConfig)!=null&&E.enabled){let I=await((D=o.getContextIndex)==null?void 0:D.call(o))??[];p=ne(I),d+=p}let f=z(t.data.user_template||"",t,n,e,{sessionEnv:o}),l=I=>I&&Object.fromEntries(Object.keys(I).map(C=>[C,"[redacted]"])),m=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:l(o.secrets),userAuth:l(o.userAuth)}:o,a=z(t.data.template,t,n,void 0,{sessionEnv:m})||u;a+=p;let g=z(t.data.user_template||"",t,n,void 0,{sessionEnv:m});e==null||e({type:`info:llmNodeRunner:${t.id}`,content:a}),e==null||e({type:`info:llmNodeRunner:${t.id}`,content:g});let y=(F=t==null?void 0:t.data)==null?void 0:F.window_size,h=Number(y);(!Number.isInteger(h)||h<=0)&&(h=5);let w=Pe(t,n),x=Fe(t,n),T=(await((H=o.getMessages)==null?void 0:H.call(o))??[]).slice(-h),_=T.filter(I=>I&&typeof I.role=="string"&&typeof I.content=="string");_.length!==T.length&&console.warn(`Filtered ${T.length-_.length} invalid messages from history`);let A=Po(_,f,w,x);await Fo(d,A,o.conn,e,t,c,s,n,r,o,i)}async function Fo(o,t,n,e,s,r,i,c,d,u,p){var l;let f=Date.now();if(!((l=u.env)!=null&&l.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(m,a)=>{var H,I,C,k,j,U,K;let g,y={},h,w="none",x=!1,R,T=!1,_=!1,A=0,P=0,E=(H=s==null?void 0:s.data)==null?void 0:H.sendReasoning,D=E!==!1;try{let M=(I=s==null?void 0:s.data)==null?void 0:I.model,B=Array.isArray(M)?M[0]:M||"gpt_5_nano",N=Yt(s==null?void 0:s.data),$=await dt(B,u,N);if(!$)throw new Error(`Model '${B}' not found in registry`);g=$.modelHandle,y=$.effectiveParams||{},w=$.reasoning.kind;let O=Zt($.reasoning,(C=s==null?void 0:s.data)==null?void 0:C.reasoningEffort);x=D&&Qt($.reasoning);let q=typeof((k=s==null?void 0:s.data)==null?void 0:k.reasoningMaxTokens)=="number"?s.data.reasoningMaxTokens:void 0;h=vt($.provider,{effort:O,exposeReasoning:x,maxTokens:q}),O&&(e==null||e({type:"info:llmNodeRunner:reasoningEffort",content:O})),console.log(`[reasoning] ${JSON.stringify({model:B,provider:$.provider,capability:$.reasoning,requestedEffort:((j=s==null?void 0:s.data)==null?void 0:j.reasoningEffort)??null,resolvedEffort:O??null,sendReasoning:D,exposeReasoning:x,providerOptions:h??null},null,2)}`);for(let V of $.paramAdjustments??[])e==null||e({type:"warn:llmNodeRunner",content:V});e==null||e({type:"info:llmNodeRunner:model",content:B}),e==null||e({type:"info:llmNodeRunner:generationParams",content:{...(U=s==null?void 0:s.data)!=null&&U.generationPreset?{preset:s.data.generationPreset}:{},...y,...w!=="none"?{reasoning:w,configuredSendReasoning:E,sendReasoning:D,exposeReasoning:x,...O?{effort:O}:{}}:{}}})}catch(M){throw e==null||e({type:"error:llmNodeRunner",content:`Model error: ${String(M)}`}),M}let F=await $o(u,c,s,e);if((K=u.memoryConfig)!=null&&K.enabled){let{recall:M}=await import("./recall-IABRCSHY.js");F.recall=M(u,c,void 0,e)}console.log(`[tools] node ${s.id} loaded ${Object.keys(F).length}: ${Object.keys(F).join(", ")||"(none)"}`),e==null||e({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:s.id,tools:Object.keys(F)}});try{let M=Oo({model:g,system:o,messages:t,stopWhen:(()=>{var V;let $=!!F.readSkillRef?10:5,O=Number(((V=s.data)==null?void 0:V.max_steps)??$),q=Number.isFinite(O)?Math.max(1,Math.min(30,O)):$;return Ao(q)})(),...Bt(y),...h?{providerOptions:h}:{},tools:F,onFinish:async N=>{var Xt,St;let $=N.text||"",O=N.reasoningText??((Xt=N.reasoning)==null?void 0:Xt.text)??"";if(console.log(`[reasoning] done: deltas=${A} chars=${P} result.reasoningText=${O.length} finishReason=${N.finishReason??"n/a"} reasoningTokens=${((St=N.usage)==null?void 0:St.reasoningTokens)??"n/a"}`),D&&x&&!T&&O&&n){T=!0;try{L(n,b.SERVER_REASONING_STREAM,O)}catch(eo){console.warn("Failed to send finished reasoning over connection",eo)}}let q={id:_o(),role:"assistant",type:"text",content:$,ts:Date.now()};r&&(u.setMessages?await u.setMessages(q):e==null||e({type:"error:llmNodeRunner",content:"setMessages callback missing"})),n&&D&&T&&!_&&(_=!0,L(n,b.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),r&&n&&L(n,b.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),i==null||i((s==null?void 0:s.id)||"llm_result",$),e==null||e({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(N)});let V=Date.now()-f,to=R?R-f:void 0;p==null||p({type:"llm_telemetry",payload:{nodeId:s.id,totalLatency:V,timeToFirstToken:to,model:N.response.modelId,usage:N.usage}}),p==null||p({type:"llm_result",payload:{result:N}})},onStepFinish:async N=>{let $=(O,q=200)=>{let V=typeof O=="string"?O:JSON.stringify(O);return V?V.length>q?`${V.slice(0,q)}\u2026(+${V.length-q})`:V:""};if(N.toolCalls&&N.toolCalls.length>0){for(let O of N.toolCalls)console.log(`[tools] \u2192 ${O.toolName}(${$(O.args??O.input)})`);e==null||e({type:`info:llmNodeRunner:toolCalls:${s.id}`,content:JSON.stringify(N.toolCalls)})}if(N.toolResults&&N.toolResults.length>0){for(let O of N.toolResults)console.log(`[tools] \u2190 ${O.toolName} \u2192 ${$(O.result??O.output)}`);e==null||e({type:`info:llmNodeRunner:toolResults:${s.id}`,content:JSON.stringify(N.toolResults)})}await ko(N,s,u,e)},experimental_onToolCallStart:N=>{var $;e==null||e({type:"tool:execution",content:{nodeId:s.id,toolName:($=N==null?void 0:N.toolCall)==null?void 0:$.toolName,status:"start"}})},experimental_onToolCallFinish:N=>{var $,O;e==null||e({type:"tool:execution",content:{nodeId:s.id,toolName:($=N==null?void 0:N.toolCall)==null?void 0:$.toolName,status:((O=N==null?void 0:N.toolOutput)==null?void 0:O.type)==="tool-error"?"error":"success"}})},onError:N=>{e==null||e({type:"error:llmNodeRunner",content:"Execution error"}),a(N)},onChunk:N=>{if(N.chunk.type==="reasoning-delta"){let O=N.chunk.text??N.chunk.delta??"";if(O&&(T=!0,A+=1,P+=O.length,A===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),D&&n&&O)try{L(n,b.SERVER_REASONING_STREAM,O)}catch(q){console.warn("Failed to send reasoning chunk over connection",q)}return}if(N.chunk.type==="text-delta"){if(R||(R=Date.now()),n&&D&&T&&!_){_=!0;try{L(n,b.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to send reasoning complete over connection",O)}}return}p==null||p({type:N.chunk.type,payload:{nodeId:s.id,chunk:N.chunk}});let $=`llm_chunk:${N.chunk.type}`;e==null||e({type:$,content:{...N}})}}),B=async()=>{let N="";for await(let $ of M.fullStream)if($.type==="text-delta"){if(N+=$.text,r&&n)try{L(n,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(r&&n&&N.trim())try{L(n,b.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to flush text segment over connection",O)}N=""}};await Promise.all([M,B()]),m(),e==null||e({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"success"}})}catch(M){e==null||e({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"error",error:String(M)}}),a(M)}})}function Po(o,t,n,e){let s=!!(n&&n.length>0),r=!!e,i=s||r,d=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,u=p=>{let f=[],l="";if(r&&(l+=`[Attached files]
|
|
30
|
+
`:"")+a.value)}return i}function $o(o,t){var s,r,i,c,d;let n=((s=o.data)==null?void 0:s.attachments)??[];if(!Array.isArray(n))throw new V("INVALID_EXPRESSION",`Node ${o.id} attachments must be an array`);let e=et(((i=(r=t.flowData)==null?void 0:r.state)==null?void 0:i.nodes)??[],((d=(c=t.flowData)==null?void 0:c.state)==null?void 0:d.edges)??[],o.id);return n.map(u=>{if(typeof u!="string")throw new V("INVALID_EXPRESSION",`Node ${o.id} has an invalid attachment reference`);let p=e.find(g=>g.ref===u);if(!p)throw new V("OUT_OF_SCOPE",`Attachment "${u}" is not in this node's connection scope`);if(p.type!=="image"&&p.type!=="file")throw new V("UNKNOWN_OUTPUT",`Attachment "${u}" is not a binary output`);return p.type==="image"?u:null}).filter(u=>u!==null)}function be(o,t){var s,r,i,c;let n=[],e={context:t.context??{},results:t.results??{},nodes:((r=(s=t.flowData)==null?void 0:s.state)==null?void 0:r.nodes)??[],edges:((c=(i=t.flowData)==null?void 0:i.state)==null?void 0:c.edges)??[],currentNodeId:o.id};for(let d of $o(o,t)){let u=K(d,e);if(u.missing)throw new V(u.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${d}" did not produce a value`);if(!Array.isArray(u.value))throw new V("PATH_NOT_FOUND",`Attachment "${d}" must resolve to an image array`);n.push(...u.value)}return n}var ko=lt({"../tools/composioDirectTool.ts":()=>import("./composioDirectTool-H3GSCIPY.js"),"../tools/composioTool.ts":()=>import("./composioTool-5LFWUQ7F.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-LSNJKMPR.js"),"../tools/recall.ts":()=>import("./recall-IABRCSHY.js"),"../tools/skillTool.ts":()=>import("./skillTool-PLHCAODG.js"),"../tools/tempTool.ts":()=>import("./tempTool-2RXAF56M.js"),"../tools/twitter.ts":()=>import("./twitter-OMDEG7T2.js"),"../tools/vectorize.ts":()=>import("./vectorize-UJXIDL2E.js")});var Fo=lt({});function Vt(o,t,n,e,s){var i;if(!((i=e.memoryConfig)!=null&&i.enabled)||!e.memoryConfig.toolCache||!n.cacheable||!t||typeof t.execute!="function")return t;let r=t.execute.bind(t);return t.execute=async(c,...d)=>{var l;if(!e.getContextIndex)return r(c,...d);let u=await _t(c),g=(await e.getContextIndex()).find(f=>{if(f.domain!=="tool")return!1;let a=$t(f.meta);return a.toolName===o&&a.paramsHash===u});if(g){let f=await((l=e.getContext)==null?void 0:l.call(e,g.ref));if((f==null?void 0:f.data)!=null&&$t(f.meta).truncated!==!0){s==null||s({type:"info:memory:cacheHit",content:{ref:f.ref,toolName:o}});try{return JSON.parse(f.data)}catch{return f.data}}}return r(c,...d)},t}async function Mo(o,t,n,e){var p,g;if(!((p=n.memoryConfig)!=null&&p.enabled)||!n.setContext||n.cycle==null)return;let s=o.toolCalls??[],r=o.toolResults??[];if(!s.length||!r.length)return;let i=new Map;for(let l of r)l!=null&&l.toolCallId&&i.set(l.toolCallId,l);let c=Array.isArray((g=t==null?void 0:t.data)==null?void 0:g.tools)?t.data.tools:[],d=new Map;for(let l of c)l&&typeof l.id=="string"&&d.set(l.id,l);let u=new Map;for(let l of Object.values(n.toolDefs??{}))l&&l.name&&u.set(l.name,l);for(let l of s){let f=l.toolCallId,a=l.toolName,m=i.get(f);if(!a||!m||a==="readSkillRef")continue;let y=l.args??l.input,w=m.result??m.output,h=!1,I="",R="tool",x="",O=u.get(a);O&&O.kind==="skill"&&(h=!0,I=`skill:${a}`,R="skill",x=`Skill instructions for ${a}`),I||(I=await ne(a,y),x=oe(y,w));let C=d.get(a)??c.find(k=>k.id===a),D=await _t(y),j=typeof w=="string"?w:JSON.stringify(w??null);await n.setContext({ref:I,domain:R,description:x,data:j,cycle:n.cycle,meta:JSON.stringify({toolName:a,paramsHash:D,cacheable:(C==null?void 0:C.cacheable)===!0})}),e==null||e({type:"info:memory:updated",content:{ref:I}})}}async function bo(o,t,n,e){var g;let s=Array.isArray((g=n==null?void 0:n.data)==null?void 0:g.tools)?n.data.tools:[];if(s.length===0)return{};let r={},i=l=>{var I,R;let f=typeof(l==null?void 0:l.description)=="string"?l.description:"",a=l==null?void 0:l.inputSchema,m;try{let x=(a==null?void 0:a.shape)??(typeof((I=a==null?void 0:a._def)==null?void 0:I.shape)=="function"?a._def.shape():(R=a==null?void 0:a._def)==null?void 0:R.shape);x&&typeof x=="object"&&(m=x)}catch{}let y=m?Object.keys(m):[],w=f?`description="${f.length>120?f.slice(0,120)+"\u2026":f}"`:"description=(none)",h=y.length?`inputSchema={${y.join(", ")}}`:"inputSchema=(none)";return`${w} ${h}`},c=(()=>{let l=[],f=[],a=[],m=[];for(let w=0;w<s.length;w++){let h=s[w];!h||typeof h!="object"||typeof h.id!="string"?m.push(w):h.kind==="builtin"?l.push(h.id):h.kind==="skill"?a.push(h.id):h.kind==="http"||h.kind==="mcp"||h.kind==="composio"?f.push(h.id):m.push(w)}let y=[];return l.length&&y.push(`builtin[${l.join(", ")}]`),f.length&&y.push(`custom[${f.join(", ")}]`),a.length&&y.push(`skill[${a.join(", ")}]`),m.length&&y.push(`invalid@[${m.join(", ")}]`),y.join(" ")||"(none)"})();console.log(`[tools] node ${n.id} requested (${s.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 l=await gt(o.env),f={};for(let a of l)a&&a.id&&(f[a.id]=a);o.toolDefs=f}catch(l){e==null||e({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(l)}`}),o.toolDefs=o.toolDefs||{}}return d=!0,o.toolDefs},p=[];for(let l=0;l<s.length;l++){let f=s[l];if(!f||typeof f!="object"||typeof f.id!="string"||f.kind!=="builtin"&&f.kind!=="http"&&f.kind!=="mcp"&&f.kind!=="composio"&&f.kind!=="skill"){e==null||e({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${l}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let a=f;if(a.kind!=="builtin"){let y=(await u())[a.id];if(!y){console.error(`[tools] \u2717 custom '${a.id}': not found for tenant`),e==null||e({type:"error:llmNodeRunner",content:`custom tool '${a.id}' not found for this tenant`});continue}if(a.kind==="composio"){try{let h=await me(y,o,t,e),I=Object.keys(h);for(let[R,x]of Object.entries(h))r[R]=Vt(R,x,a,o,e);console.log(`[tools] \u2713 composio '${a.id}' \u2192 ${I.length} tool(s)`)}catch(h){console.error(`[tools] \u2717 composio '${a.id}': ${String(h)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading composio tool '${a.id}': ${String(h)}`})}continue}if(a.kind==="skill"){if(y.kind!=="skill"){console.error(`[tools] \u2717 skill '${a.id}': row is of kind '${y.kind}', not 'skill'`),e==null||e({type:"error:llmNodeRunner",content:`tool '${a.id}' is not a skill`});continue}let h=y.name;if(r[h]){e==null||e({type:"warn:llmNodeRunner",content:`tool name collision on '${h}' \u2014 builtin/other already registered, skipping skill '${a.id}'`});continue}try{r[h]=ge(y,o,t,e),p.push(y);let I=typeof y.execution=="string"?JSON.parse(y.execution):y.execution||{},R=Array.isArray(I.references)?I.references.map(x=>x==null?void 0:x.name):[];console.log(`[tools] \u2713 skill '${a.id}' \u2192 '${h}' (refs: ${R.join(", ")||"none"})`),e==null||e({type:"info:skill:registered",content:{skill:h,refCount:R.length,refs:R}})}catch(I){console.error(`[tools] \u2717 skill '${a.id}': ${String(I)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading skill tool '${a.id}': ${String(I)}`})}continue}let w=y.name;if(r[w]){e==null||e({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin already registered, skipping custom tool '${a.id}'`});continue}try{let h=yt(y,o,t,e);r[w]=Vt(w,h,a,o,e),console.log(`[tools] \u2713 custom '${a.id}' \u2192 '${w}'`),console.log(`[tools] ${i(r[w])}`)}catch(h){console.error(`[tools] \u2717 custom '${a.id}': ${String(h)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading custom tool '${a.id}': ${String(h)}`})}continue}if(!fe[a.id]){console.error(`[tools] \u2717 builtin '${a.id}': not in registry`),e==null||e({type:"error:llmNodeRunner",content:`Tool '${a.id}' not found in registry`});continue}try{let m;try{m=await ko(`../tools/${a.id}.ts`)}catch{m=await Fo(`../tools/${a.id}.js`)}let y;if(m[a.id])y=m[a.id];else if(m.default)y=m.default;else if(m.create)y=m.create;else{let C=Object.values(m);C.length>0&&(y=C[0])}if(!y){e==null||e({type:"error:llmNodeRunner",content:`No factory export found for tool '${a.id}'`});continue}let w,h,I={};if(a.params&&typeof a.params=="object"){if(typeof a.params.description=="string"?w=a.params.description:a.params.description!==void 0&&(e==null||e({type:"error:llmNodeRunner",content:`Invalid description for tool '${a.id}' \u2014 must be a string`})),a.params.inputSchema!==void 0){let C=a.params.inputSchema;typeof C=="object"&&(typeof C.safeParse=="function"||C._def)?h=C:typeof C=="object"&&C!==null&&C.type==="object"&&C.properties?(h=pe(C),h||e==null||e({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${a.id}' \u2014 must be a Zod schema or JSON Schema object`})):e==null||e({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${a.id}' \u2014 must be a Zod schema or JSON Schema object`})}a.params.defaults!==void 0?typeof a.params.defaults=="object"&&a.params.defaults!==null&&!Array.isArray(a.params.defaults)?I=a.params.defaults:(e==null||e({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${a.id}' \u2014 must be an object`}),I={}):a.params.source!==void 0||a.params.target!==void 0?(e==null||e({type:"error:llmNodeRunner",content:`Invalid params for tool '${a.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),I={}):I={}}let R=y(o,t,I,e);w&&R&&typeof R=="object"&&(R.description=w),h&&R&&typeof R=="object"&&(R.inputSchema=h),r[a.id]=Vt(a.id,R,a,o,e);let x=[];w&&x.push("description"),h&&x.push("inputSchema"),Object.keys(I).length&&x.push(`defaults(${Object.keys(I).join(",")})`);let O=x.length?` [overrides: ${x.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${a.id}'${O}`),console.log(`[tools] ${i(R)}`)}catch(m){console.error(`[tools] \u2717 builtin '${a.id}': ${String(m)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading tool '${a.id}': ${String(m)}`});continue}}if(p.length>0)if(r.readSkillRef)e==null||e({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{r.readSkillRef=ye(o,p,t,e),console.log(`[tools] \u2713 registered readSkillRef tool for ${p.length} skill(s)`),e==null||e({type:"info:skill:readSkillRefRegistered",content:{skills:p.map(l=>l.name)}})}catch(l){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(l)}`)}return r}async function qt(o,t,n,e,s,r,i){var D,j,k,_,L,N;`${t.id}`,e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c=!1;try{let T=(D=n.flowData)==null?void 0:D.state;if(T&&T.edges&&T.nodes){let F=T.edges.filter(U=>U.source===t.id);if(F.length>0){let U=T.nodes.find(M=>M.id===F[0].target);U&&U.type==="answerNode"&&(c=!0)}}}catch(T){console.error("Error determining next node for streaming:",T)}let d=G(t.data.template,t,n,e,{sessionEnv:o});(!d||!d.trim())&&(d="Answer straight forward to the user, dont offer any other option to continue");let u=d,p="";if((j=o.memoryConfig)!=null&&j.enabled){let T=await((k=o.getContextIndex)==null?void 0:k.call(o))??[];p=re(T),d+=p}let g=G(t.data.user_template||"",t,n,e,{sessionEnv:o}),l=T=>T&&Object.fromEntries(Object.keys(T).map(F=>[F,"[redacted]"])),f=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:l(o.secrets),userAuth:l(o.userAuth)}:o,a=G(t.data.template,t,n,void 0,{sessionEnv:f})||u;a+=p;let m=G(t.data.user_template||"",t,n,void 0,{sessionEnv:f});e==null||e({type:`info:llmNodeRunner:${t.id}`,content:a}),e==null||e({type:`info:llmNodeRunner:${t.id}`,content:m});let y=(_=t==null?void 0:t.data)==null?void 0:_.window_size,w=Number(y);(!Number.isInteger(w)||w<=0)&&(w=5);let h=be(t,n),I=Me(t,n);e==null||e({type:"info:llmNodeRunner:attachments",content:{nodeId:t.id,refs:Array.isArray((L=t.data)==null?void 0:L.attachments)?t.data.attachments:[],images:h.length,documents:I?1:0}});let x=(await((N=o.getMessages)==null?void 0:N.call(o))??[]).slice(-w),O=x.filter(T=>T&&typeof T.role=="string"&&typeof T.content=="string");O.length!==x.length&&console.warn(`Filtered ${x.length-O.length} invalid messages from history`);let C=jo(O,g,h,I);await Eo(d,C,o.conn,e,t,c,s,n,r,o,i)}async function Eo(o,t,n,e,s,r,i,c,d,u,p){var l;let g=Date.now();if(!((l=u.env)!=null&&l.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(f,a)=>{var L,N,T,F,U,M,X;let m,y={},w,h="none",I=!1,R,x=!1,O=!1,C=0,D=0,j=(L=s==null?void 0:s.data)==null?void 0:L.sendReasoning,k=j!==!1;try{let b=(N=s==null?void 0:s.data)==null?void 0:N.model,Q=Array.isArray(b)?b[0]:b||"gpt_5_nano",A=Qt(s==null?void 0:s.data),P=await ut(Q,u,A);if(!P)throw new Error(`Model '${Q}' not found in registry`);m=P.modelHandle,y=P.effectiveParams||{},h=P.reasoning.kind;let $=te(P.reasoning,(T=s==null?void 0:s.data)==null?void 0:T.reasoningEffort);I=k&&vt(P.reasoning);let S=typeof((F=s==null?void 0:s.data)==null?void 0:F.reasoningMaxTokens)=="number"?s.data.reasoningMaxTokens:void 0;w=ee(P.provider,{effort:$,exposeReasoning:I,maxTokens:S}),$&&(e==null||e({type:"info:llmNodeRunner:reasoningEffort",content:$})),console.log(`[reasoning] ${JSON.stringify({model:Q,provider:P.provider,capability:P.reasoning,requestedEffort:((U=s==null?void 0:s.data)==null?void 0:U.reasoningEffort)??null,resolvedEffort:$??null,sendReasoning:k,exposeReasoning:I,providerOptions:w??null},null,2)}`);for(let q of P.paramAdjustments??[])e==null||e({type:"warn:llmNodeRunner",content:q});e==null||e({type:"info:llmNodeRunner:model",content:Q}),e==null||e({type:"info:llmNodeRunner:generationParams",content:{...(M=s==null?void 0:s.data)!=null&&M.generationPreset?{preset:s.data.generationPreset}:{},...y,...h!=="none"?{reasoning:h,configuredSendReasoning:j,sendReasoning:k,exposeReasoning:I,...$?{effort:$}:{}}:{}}})}catch(b){throw e==null||e({type:"error:llmNodeRunner",content:`Model error: ${String(b)}`}),b}let _=await bo(u,c,s,e);if((X=u.memoryConfig)!=null&&X.enabled){let{recall:b}=await import("./recall-IABRCSHY.js");_.recall=b(u,c,void 0,e)}console.log(`[tools] node ${s.id} loaded ${Object.keys(_).length}: ${Object.keys(_).join(", ")||"(none)"}`),e==null||e({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:s.id,tools:Object.keys(_)}});try{let b=Do({model:m,system:o,messages:t,stopWhen:(()=>{var q;let P=!!_.readSkillRef?10:5,$=Number(((q=s.data)==null?void 0:q.max_steps)??P),S=Number.isFinite($)?Math.max(1,Math.min(30,$)):P;return Po(S)})(),...Zt(y),...w?{providerOptions:w}:{},tools:_,onFinish:async A=>{var Jt,zt;let P=A.text||"",$=A.reasoningText??((Jt=A.reasoning)==null?void 0:Jt.text)??"";if(console.log(`[reasoning] done: deltas=${C} chars=${D} result.reasoningText=${$.length} finishReason=${A.finishReason??"n/a"} reasoningTokens=${((zt=A.usage)==null?void 0:zt.reasoningTokens)??"n/a"}`),k&&I&&!x&&$&&n){x=!0;try{H(n,E.SERVER_REASONING_STREAM,$)}catch(ro){console.warn("Failed to send finished reasoning over connection",ro)}}let S={id:Uo(),role:"assistant",type:"text",content:P,ts:Date.now()};r&&(u.setMessages?await u.setMessages(S):e==null||e({type:"error:llmNodeRunner",content:"setMessages callback missing"})),n&&k&&x&&!O&&(O=!0,H(n,E.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),r&&n&&H(n,E.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),i==null||i((s==null?void 0:s.id)||"llm_result",P),e==null||e({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(A)});let q=Date.now()-g,so=R?R-g:void 0;p==null||p({type:"llm_telemetry",payload:{nodeId:s.id,totalLatency:q,timeToFirstToken:so,model:A.response.modelId,usage:A.usage}}),p==null||p({type:"llm_result",payload:{result:A}})},onStepFinish:async A=>{let P=($,S=200)=>{let q=typeof $=="string"?$:JSON.stringify($);return q?q.length>S?`${q.slice(0,S)}\u2026(+${q.length-S})`:q:""};if(A.toolCalls&&A.toolCalls.length>0){for(let $ of A.toolCalls)console.log(`[tools] \u2192 ${$.toolName}(${P($.args??$.input)})`);e==null||e({type:`info:llmNodeRunner:toolCalls:${s.id}`,content:JSON.stringify(A.toolCalls)})}if(A.toolResults&&A.toolResults.length>0){for(let $ of A.toolResults)console.log(`[tools] \u2190 ${$.toolName} \u2192 ${P($.result??$.output)}`);e==null||e({type:`info:llmNodeRunner:toolResults:${s.id}`,content:JSON.stringify(A.toolResults)})}await Mo(A,s,u,e)},experimental_onToolCallStart:A=>{var P;e==null||e({type:"tool:execution",content:{nodeId:s.id,toolName:(P=A==null?void 0:A.toolCall)==null?void 0:P.toolName,status:"start"}})},experimental_onToolCallFinish:A=>{var P,$;e==null||e({type:"tool:execution",content:{nodeId:s.id,toolName:(P=A==null?void 0:A.toolCall)==null?void 0:P.toolName,status:(($=A==null?void 0:A.toolOutput)==null?void 0:$.type)==="tool-error"?"error":"success"}})},onError:A=>{e==null||e({type:"error:llmNodeRunner",content:"Execution error"}),a(A)},onChunk:A=>{if(A.chunk.type==="reasoning-delta"){let $=A.chunk.text??A.chunk.delta??"";if($&&(x=!0,C+=1,D+=$.length,C===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),k&&n&&$)try{H(n,E.SERVER_REASONING_STREAM,$)}catch(S){console.warn("Failed to send reasoning chunk over connection",S)}return}if(A.chunk.type==="text-delta"){if(R||(R=Date.now()),n&&k&&x&&!O){O=!0;try{H(n,E.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch($){console.warn("Failed to send reasoning complete over connection",$)}}return}p==null||p({type:A.chunk.type,payload:{nodeId:s.id,chunk:A.chunk}});let P=`llm_chunk:${A.chunk.type}`;e==null||e({type:P,content:{...A}})}}),Q=async()=>{let A="";for await(let P of b.fullStream)if(P.type==="text-delta"){if(A+=P.text,r&&n)try{H(n,E.SERVER_TEXT_STREAM,P.text)}catch($){console.warn("Failed to send chunk over connection",$)}}else if(P.type==="finish-step"&&P.finishReason==="tool-calls"){if(r&&n&&A.trim())try{H(n,E.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch($){console.warn("Failed to flush text segment over connection",$)}A=""}};await Promise.all([b,Q()]),f(),e==null||e({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"success"}})}catch(b){e==null||e({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"error",error:String(b)}}),a(b)}})}function jo(o,t,n,e){let s=!!(n&&n.length>0),r=!!e,i=s||r,d=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,u=p=>{let g=[],l="";if(r&&(l+=`[Attached files]
|
|
31
31
|
${e}
|
|
32
32
|
[End of attached files]
|
|
33
33
|
|
|
34
|
-
`),p&&(l+=p),l&&
|
|
34
|
+
`),p&&(l+=p),l&&g.push({type:"text",text:l}),s)for(let f of n)g.push({type:"image",image:f.data,mimeType:f.mimeType});return g};return t&&d&&d.content===t?[...o.slice(0,-1).map(g=>({role:g.role,content:g.content})),{role:"user",content:u(t)}]:t?[...o.map(p=>({role:p.role,content:p.content})),{role:"user",content:u(t)}]:i&&d?[...o.slice(0,-1).map(g=>({role:g.role,content:g.content})),{role:"user",content:u(d.content)}]:o.map(p=>({role:p.role,content:p.content}))}async function St(o,t,n,e,s,r,i){var p,g,l,f,a,m,y;console.log(`**** MEMO Node id: ${t.id} ****`),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c="",d=!1,u=Date.now();try{e==null||e({type:"info:memoNodeRunner",content:"Starting memo node execution"});let w=String(((p=t.data)==null?void 0:p.query_key)||"user_input"),h=K(w,{context:n.context??{},results:n.results??{},nodes:((l=(g=n.flowData)==null?void 0:g.state)==null?void 0:l.nodes)??[],edges:((a=(f=n.flowData)==null?void 0:f.state)==null?void 0:a.edges)??[],currentNodeId:t.id});if(h.missing)throw new Error(`Memo query "${w}" did not produce a value`);if(!o.env||!o.ctx){e==null||e({type:"error:memoNodeRunner",content:"Missing env or ctx"}),s==null||s(t.id,c);return}if(!t.data.rag_id){e==null||e({type:"error:memoNodeRunner",content:"Missing rag_id"}),s==null||s(t.id,c);return}let I=String(h.value??"");e==null||e({type:"info:memoNodeRunner",content:`Query text: ${I}`}),e==null||e({type:"info:memoNodeRunner",content:"Generating embedding for query"});let R=await Gt(o,I,!0);e==null||e({type:"info:memoNodeRunner",content:`Embedding generated successfully, length: ${R.data[0].length}`});let x=Array.isArray(t.data.rag_id)?t.data.rag_id:[t.data.rag_id],O=[];for(let k of x){e==null||e({type:"info:memoNodeRunner",content:`Executing RAG query with namespace: ${k}`});let _=await o.env[`VDB_${(m=n.flowData)==null?void 0:m.tenant}_1024`].query(R.data[0],{namespace:k,topK:t.data.topk,returnMetadata:"all"});e==null||e({type:"info:memoNodeRunner",content:`RAG query completed for namespace ${k}, matches: ${((y=_.matches)==null?void 0:y.length)||0}`}),Array.isArray(_.matches)&&O.push(..._.matches)}let C=Date.now()-u;c=O.map(k=>{var _;return(_=k.metadata)==null?void 0:_.value}).filter(k=>typeof k=="string").join(`
|
|
35
35
|
|
|
36
|
-
`),i==null||i({type:"memo_search",payload:{nodeId:t.id,searchLatencyMs:
|
|
37
|
-
${
|
|
36
|
+
`),i==null||i({type:"memo_search",payload:{nodeId:t.id,searchLatencyMs:C,retrievedContext:c}}),e==null||e({type:"info:memoNodeRunner",content:`Context retrieval complete, length: ${c.length}, preview: ${c.substring(0,200)}...`}),e==null||e({type:"info:memoNodeRunner",content:"Memo node execution completed successfully"}),d=!0}catch(w){throw console.error("Error processing MemoNode:",w),e==null||e({type:"error:memoNodeRunner",content:`Memo node execution failed: ${w}`}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(w)}}),w}finally{d&&(s==null||s(t.id,c),e==null||e({type:"info:memoNodeRunner",content:`onResult called with context length: ${c.length}`}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"success"}}))}}async function Xt(o,t,n,e,s,r,i){var p,g,l,f,a,m,y;console.log(`**** START Node ${t.id} ****`),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}}),e==null||e({type:"info:flow",content:n}),i==null||i({type:"start_node",payload:{userMessage:(p=n==null?void 0:n.context)==null?void 0:p.user_input}});let c=((g=t.data)==null?void 0:g.allow_images)!==!1,d=((l=t.data)==null?void 0:l.allow_documents)!==!1;!c&&(n!=null&&n.context)&&(n.context.user_images=[],r==null||r({...n})),!d&&(n!=null&&n.context)&&(n.context.files="",r==null||r({...n}));let u={};for(let w of tt(t.data))u[w.name]=(f=n==null?void 0:n.context)==null?void 0:f[w.name];s==null||s(t.id,{...u,user_input:(a=n==null?void 0:n.context)==null?void 0:a.user_input,images:c?(m=n==null?void 0:n.context)==null?void 0:m.user_images:[],files:d?(y=n==null?void 0:n.context)==null?void 0:y.files:""}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"success"}})}function je(o,t,n){let e=t;async function s(){var u;if(await((u=n==null?void 0:n.shouldStop)==null?void 0:u.call(n)))throw new Ct}async function r(u){let p=u;for(e.executedNodes=e.executedNodes||[],e.context=e.context||{},e.results=e.results||{};p&&p.id;)await s(),await i(p),await s(),p=Vo(p,e.flowData,e)}async function i(u){var a;let p=d[u.type];if(!p){(a=n==null?void 0:n.onError)==null||a.call(n,`Unknown node type: ${u.type}`);return}let g=m=>{var y;return(y=n==null?void 0:n.onServerEvent)==null?void 0:y.call(n,{...m,ts:Date.now()})},l=m=>{var y,w;if((y=n==null?void 0:n.onTelemetry)==null||y.call(n,m),m.type==="llm_telemetry"||m.type==="class_telemetry"){let h=(w=m.payload)==null?void 0:w.usage;h&&(e.tokenUsage=e.tokenUsage||{promptTokens:0,completionTokens:0,totalTokens:0},e.tokenUsage.promptTokens+=h.promptTokens||0,e.tokenUsage.completionTokens+=h.completionTokens||0,e.tokenUsage.totalTokens+=h.totalTokens||0)}};return await p(o,u,e,g,(m,y)=>{e.results[m]=y},n==null?void 0:n.onChangeState,l)}let c=async u=>{var f,a,m,y,w,h,I;let p=Date.now(),g="completed",l;try{await s();let R=typeof u=="string"?dt(u):u,x=(R==null?void 0:R.text)||"",O=(R==null?void 0:R.images)||[],C=(R==null?void 0:R.documents)||[],D=await Fe(C,o.env),j=D.length>0?D.map(L=>`--- file: ${L.name} ---
|
|
37
|
+
${L.text}`).join(`
|
|
38
38
|
|
|
39
|
-
`):"";e.context={user_input:T,user_images:_,files:E},e.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},(m=n==null?void 0:n.onServerEvent)==null||m.call(n,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:D,error:F}=Do(e.flowData);if(!D)f="failed",l=F||"Flow Format Error",(a=n==null?void 0:n.onError)==null||a.call(n,l);else{let H=v(D.data),{values:I,errors:C}=zt(H,R==null?void 0:R.inputs);if(C.length>0)return f="failed",l=`Invalid flow inputs: ${C.join("; ")}`,(g=n==null?void 0:n.onError)==null||g.call(n,l),{status:f,error:l};e.context={...e.context,inputs:I,...I},e.context.user_input||(e.context.user_input=T),await r(D),(y=n==null?void 0:n.onServerEvent)==null||y.call(n,{type:"agent:telemetry",content:{durationMs:Date.now()-p,tokenUsage:e.tokenUsage},timestamp:Date.now()})}}catch(R){R instanceof Nt?(f="stopped",l=R.message,(h=n==null?void 0:n.onServerEvent)==null||h.call(n,{type:"agent:stopped",content:l,timestamp:Date.now()})):(f="failed",l=R instanceof Error?R.message:"Agent execution failed",(w=n==null?void 0:n.onError)==null||w.call(n,l))}finally{(x=n==null?void 0:n.onServerEvent)==null||x.call(n,{type:"agent:complete",content:{status:f,durationMs:Date.now()-p},timestamp:Date.now()})}return{status:f,error:l}},d={startNode:qt,classifierNode:Et,llmNode:Ht,memoNode:Vt,answerNode:Ft,apiNode:Mt,toolNode:jt};return c}var Nt=class extends Error{constructor(){super("Stopped by user"),this.name="FlowExecutionStoppedError"}};function Do(o){var p;let t=(o==null?void 0:o.state)??o;if(!t||!t.nodes||!t.edges||t.edges.length===0)return{error:"Flow is missing state, nodes, or edges."};let n=t.nodes.filter(f=>f.type==="startNode");if(n.length!==1)return{error:`Flow must include exactly one START node, found ${n.length}.`};let e=n[0],s=t.nodes.filter(f=>f.type==="answerNode");if(s.length===0)return{error:"Flow must include at least one ANSWER node."};let r=new Map;for(let f of t.edges)r.has(f.source)||r.set(f.source,[]),r.get(f.source).push(f.target);let i=new Map;for(let f of t.edges)i.has(f.target)||i.set(f.target,[]),i.get(f.target).push(f.source);let c=De(e.id,r),d=new Set;for(let f of s){let l=De(f.id,i);for(let m of l)d.add(m)}let u=[];for(let f of c)if(!d.has(f)){let l=t.nodes.find(m=>m.id===f);if(l){let m=((p=l.data)==null?void 0:p.label)||"";u.push(`${f}(${m},${l.type})`)}}return u.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${u.join(", ")}`}:{startNode:e}}function De(o,t){let n=new Set,e=[o];for(n.add(o);e.length>0;){let s=e.shift(),r=t.get(s)||[];for(let i of r)n.has(i)||(n.add(i),e.push(i))}return n}function Mo(o,t){var n;return((n=o.state)==null?void 0:n.nodes.find(e=>e.id===t))||null}function bo(o,t,n){var c;let e=t==null?void 0:t.state;if(!e)return null;let s=e.edges.filter(d=>d.source===o.id);if(s.length===0)return null;let r=s[0].target;if(o.type==="classifierNode"&&((c=n==null?void 0:n.context)!=null&&c.classified_id)){let d=n.context.classified_id,u=s.find(p=>p.sourceHandle===`source-${d}`);u?r=u.target:console.log(`No matching edge, falling back to first: ${r}`)}return Mo(t,r)}async function be(o,t){var e,s;let n=(e=t==null?void 0:t.flowData)==null?void 0:e.flowId;if(!(o!=null&&o.HX_CORE_URL)||!n)return{engineState:t,refreshed:!1};try{let r=await Q(n,o),i={...t,flowData:{...r,tenant:t.flowData.tenant,flowId:n,chatId:t.flowData.chatId}},c=r==null?void 0:r.stateVersion,d=typeof c=="number"&&c!==((s=t.flowData)==null?void 0:s.stateVersion);return{engineState:i,refreshed:d}}catch(r){return console.error(`[flowRefresh] fetch failed for flow ${n}:`,r),{engineState:t,refreshed:!1}}}function Ue(o,t){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(t)}).catch(n=>{console.error("[sessionIndex] failed to index session",n)})}function je(){let o={};return{add(t,n){o[t]=n},hasOutputs(){return Object.keys(o).length>0},answerNodeIds(){return Object.keys(o)},snapshotData(){let t=Object.entries(o);return t.length===1?t[0][1]:Object.fromEntries(t)}}}function Uo(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function Ee(o,t){if(!Uo(o))throw new Error("Structured outputs require HX_ORA_URL and HX_API_KEY");let n=await fetch(`${o.HX_ORA_URL}/internal/outputs/${encodeURIComponent(t.flowId)}/${encodeURIComponent(t.sessionId)}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:o.HX_API_KEY},body:JSON.stringify({runId:t.runId,createdAt:t.createdAt,data:t.data,answerNodeIds:t.answerNodeIds})});if(!n.ok){let e=await n.text().catch(()=>"");throw new Error(`Structured output persistence failed with ${n.status}${e?`: ${e}`:""}`)}}var Le=async(o,t)=>{fetch(`${t.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),`${JSON.stringify(o)}`};async function it(o,t){var r,i;let n=o.id||o.name||"",[e,s]=String(n).split("::");if(!e||!s)return null;try{let d=(r=(await G(e,t)).metadata)==null?void 0:r.tenant,u=await Q(e,t),p=(i=o.state)==null?void 0:i.user,f={flowData:{...u,tenant:d,flowId:e,chatId:s},executedNodes:[],context:p?{user:p}:{}};return o.setState({...o.state,engineState:f}),f}catch(c){return console.error("Failed to initialize engine state:",c),null}}async function at(o){var P,E,D,F,H;let{agent:t,env:n,ctx:e,payload:s,connection:r}=o,i=Date.now(),c=[],d=o.runId?je():void 0,u=async()=>await J(t),p=async I=>{await me(t,I)},f=async I=>{if(t.state.modelsCache&&t.state.modelsCache[I])return t.state.modelsCache[I];try{let{fetchOraModel:C}=await import("./oraApi-4O3W5LXD.js"),k=await C(I,n);return t.setState({...t.state,modelsCache:{...t.state.modelsCache||{},[I]:k}}),k}catch(C){throw console.error(`Error fetching model ${I}:`,C),C}},l={id:jo(),role:"user",type:"text",content:s.text,images:s.images,ts:Date.now()};await p(l);let m={onChangeState:I=>{t.setState({...t.state,engineState:I})},onServerEvent:async I=>{var C;await((C=o.onServerEvent)==null?void 0:C.call(o,I)),c.push(I)},onTelemetry:async I=>{var C,k,j,U,K,M;await Le({...I,userId:o.resolveUserId(),tenant:((k=(C=t.state.engineState)==null?void 0:C.flowData)==null?void 0:k.tenant)||"",flowId:((U=(j=t.state.engineState)==null?void 0:j.flowData)==null?void 0:U.flowId)||"",sessionId:((M=(K=t.state.engineState)==null?void 0:K.flowData)==null?void 0:M.chatId)||""},n)},onError:I=>{var C;(C=o.onError)==null||C.call(o,I),t.setState({...t.state,error:I})},shouldStop:o.shouldStop},a=t.state.engineState?{...t.state.engineState}:null;if(a){let{engineState:I,refreshed:C}=await be(n,a);a=I,C&&t.setState({...t.state,engineState:a,modelsCache:{}})}else if(a=await it(t,n),!a){let I="Failed to initialize agent";return m.onError(I),{status:"failed",error:I}}let g=o.secrets;if(!g||Object.keys(g).length===0){let I=(P=a.flowData)==null?void 0:P.tenant;g=I?await It(n,I):{},(E=o.onSecretsLoaded)==null||E.call(o,g)}let y=o.user??t.state.user??void 0;y&&!((D=a.context)!=null&&D.user)&&(a.context={...a.context||{},user:y});let h=ut(rt(a)),w=typeof a.cycle=="number"?a.cycle:0;h.enabled&&(w=await Ce(t,a),a.cycle=w,t.setState({...t.state,engineState:a}));let x=Ae(t,{env:n,ctx:e,conn:r,getMessages:u,setMessages:p,getOraModel:f,secrets:g,userAuth:o.userAuth,user:y,composioSessions:o.composioSessions,publicOrigin:o.publicOrigin,skillRefCache:o.skillRefCache,runId:o.runId,outputCollector:d},a,w,o.onMemoryRef),R=await Me(x,a,m)(s);if(R.status==="completed"&&o.runId&&(d!=null&&d.hasOutputs())){let{flowId:I,chatId:C}=a.flowData??{};if(!I||!C)R={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await Ee(n,{flowId:I,sessionId:C,runId:o.runId,createdAt:new Date(i).toISOString(),data:d.snapshotData(),answerNodeIds:d.answerNodeIds()});let k={...a.results||{}};for(let j of d.answerNodeIds())k[j]={...k[j]||{},persisted:!0,runId:o.runId};a={...a,results:k},t.setState({...t.state,engineState:a})}catch(k){let j=k instanceof Error?k.message:"Structured output persistence failed";m.onError(j),await m.onServerEvent({type:"error:answer-output",content:{runId:o.runId,error:j},timestamp:Date.now()}),R={status:"failed",error:j}}}let{tenant:T,flowId:_,chatId:A}=a.flowData??{};return T&&_&&A&&e.waitUntil(Ue(n,{id:`${_}::${A}`,tenant:T,flowId:_,sessionId:A,userId:o.resolveUserId(),title:(F=s.text)==null?void 0:F.slice(0,120),turnTs:i,events:c})),R.status==="completed"&&((H=x.memoryConfig)!=null&&H.enabled)&&x.memoryConfig.mode==="summarize"&&e&&e.waitUntil(se(t,x,w)),t.setState({...t.state,lastUpdated:new Date}),{status:R.status,error:R.error,engineState:a}}import{nanoid as Eo}from"nanoid";function Lo(o){let t=o.headers.get("X-User-Payload");if(!t)return null;try{let n=JSON.parse(t),e=typeof(n==null?void 0:n.email)=="string"?ot(n.email):null;return e?{...n,email:e}:null}catch{return null}}async function He(o,t,n,e){var s;try{let r=await t.json(),i=r.message;if(!i||typeof i!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let c=typeof r.userId=="string"?ot(r.userId):null,d=Lo(t),u=d==null?void 0:d.email;d?o.setState({...o.state,user:d,injectedUserId:u}):c&&!((s=o.state.user)!=null&&s.email)&&o.setState({...o.state,injectedUserId:c});let p=()=>u??c??o.state.injectedUserId??void 0;o.skillRefCache||(o.skillRefCache=new Map);let f=r.inputs&&typeof r.inputs=="object"?r.inputs:void 0;if(!o.state.engineState&&!await it(o,n))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let l=u?`run-${Eo(12)}`:null;l&&(await o.registerManualRun(l,i,u),await st(n,l).catch(y=>{console.warn(`[AgentHTTP] could not mark manual run ${l} as running`,y)}));let m;try{m=await at({agent:o,env:n,ctx:e,payload:{text:i,inputs:f},skillRefCache:o.skillRefCache,user:d??void 0,resolveUserId:p,runId:l??void 0,shouldStop:l?()=>o.isRunStopRequested(l):void 0}),l&&e.waitUntil(o.completeManualRun(l,m.status==="completed"?"succeeded":m.status==="stopped"?"skipped":"failed",m.error))}finally{l&&await o.clearRunStopRequest(l)}if(m.status==="failed")return new Response(JSON.stringify({error:m.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});if(m.status==="stopped")return new Response(JSON.stringify({error:m.error||"Stopped by user"}),{status:409,headers:{"content-type":"application/json"}});let g=(await J(o)).reverse().find(y=>y.role==="assistant");return new Response(JSON.stringify({answer:(g==null?void 0:g.content)||""}),{headers:{"content-type":"application/json"}})}catch(r){return new Response(JSON.stringify({error:r.message}),{status:500,headers:{"content-type":"application/json"}})}}async function Ve(o){try{return await gt(o),await ht(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(t){return new Response(JSON.stringify({error:t.message}),{status:500,headers:{"content-type":"application/json"}})}}var qe="trigger:nonce:",qo=900*1e3,Kt="run:stop:",Ke=class extends Ho{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{}};resolveSessionUserId(){var t;return((t=this.state.user)==null?void 0:t.email)??this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async inspectPersistedSession(t){return t==="state"?{state:this.state}:t==="messages"?{messages:await J(this)}:{context:await ye(this)}}async requestRunStop(t){return t!=null&&t.trim()?(await this.ctx.storage.put(`${Kt}${t}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(t){return!!await this.ctx.storage.get(`${Kt}${t}`)}async clearRunStopRequest(t){await this.ctx.storage.delete(`${Kt}${t}`)}async onRequest(t){let n=new URL(t.url);if(n.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(n.pathname.endsWith("/history")){let e=await J(this);return new Response(JSON.stringify(e),{headers:{"content-type":"application/json"}})}if(n.pathname.endsWith("/context")){let e={"content-type":"application/json","access-control-allow-origin":"*"};if(!t.headers.get("X-User-Payload"))return new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:e});let s=n.searchParams.get("ref");if(s){let i=await wt(this,s);return i?new Response(JSON.stringify({entry:i}),{headers:e}):new Response(JSON.stringify({error:"Not found"}),{status:404,headers:e})}let r=await yt(this);return new Response(JSON.stringify({entries:r}),{headers:e})}return t.method==="POST"&&n.pathname.endsWith("/message")?He(this,t,this.env,this.ctx):t.method==="DELETE"&&n.pathname.endsWith("/clear")?Ve(this):new Response("Ready to assist.")}async onConnect(t,n){var l,m,a,g,y;let[e,s]=t.server.split("::"),i=(l=(await G(e,this.env)).metadata)==null?void 0:l.tenant;this.secrets=await It(this.env,i),this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let c=null;if(n.request){try{this.publicOrigin=new URL(n.request.url).origin}catch{}let h=n.request.headers.get("X-User-Payload");if(h)try{c=JSON.parse(h)}catch(w){console.warn("Failed to parse X-User-Payload",w)}}let d=await Q(e,this.env);this.setState({...this.state,user:c||null,sessionId:s,engineState:{flowData:{...d,tenant:i,flowId:e,chatId:s},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 J(this);L(t,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(h=>h.type==="startNode");if(f){let h={allow_images:((a=f.data)==null?void 0:a.allow_images)??!1,allow_documents:((g=f.data)==null?void 0:g.allow_documents)??!1,greeting:(y=f.data)==null?void 0:y.greeting};L(t,b.SERVER_CONFIG,JSON.stringify(h))}}async onMessage(t,n){if(typeof n!="string")return;let e=n.indexOf(":");if(e===-1)return;let s=n.substring(0,e),r=n.substring(e+1);if(!s||!r)return;let c={[b.USER_MESSAGE]:d=>this.onUserMessage(t,d),[b.USER_CLEAR_HISTORY]:()=>this.onClearHistory(t),[b.USER_AUTH]:d=>this.onUserAuth(t,d),[b.USER_IDENTITY]:d=>this.onUserIdentity(t,d)}[s];c&&await c(r)}async onUserMessage(t,n){let e=lt(n),s=this.hasAuditableUser()?`run-${Vo(12)}`:null;s&&(await this.registerManualRun(s,e.text),await st(this.env,s).catch(r=>{console.warn(`[AgentDO] could not mark manual run ${s} as running`,r)}));try{let r=await at({agent:this,env:this.env,ctx:this.ctx,payload:e,connection:t,secrets:this.secrets,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:this.state.user,resolveUserId:()=>this.resolveSessionUserId(),runId:s??void 0,shouldStop:s?()=>this.isRunStopRequested(s):void 0,onServerEvent:i=>{L(t,b.SERVER_EVENT,JSON.stringify(i))},onError:i=>{L(t,b.SERVER_ERROR,i)},onMemoryRef:i=>{L(t,b.SERVER_EVENT,JSON.stringify({type:"info:memory:updated",content:{ref:i}}))},onSecretsLoaded:i=>{this.secrets=i}});s&&this.ctx.waitUntil(this.completeManualRun(s,r.status==="completed"?"succeeded":r.status==="stopped"?"skipped":"failed",r.error))}finally{s&&await this.clearRunStopRequest(s)}}hasAuditableUser(t){var n;return!!(t||(n=this.state.user)!=null&&n.email)}registerManualRun(t,n,e){var d,u;let{tenant:s,flowId:r,chatId:i}=((d=this.state.engineState)==null?void 0:d.flowData)??{},c=e||((u=this.state.user)==null?void 0:u.email);return!s||!r||!i||!c?Promise.resolve():Te(this.env,{id:t,tenant:s,flowId:r,userId:c,sessionId:i,label:n==null?void 0:n.slice(0,120)})}completeManualRun(t,n,e){return xt(this.env,t,{status:n,error:e})}async enqueueTrigger(t){var s;if(!(t!=null&&t.runId)||!(t!=null&&t.flowId))return{queued:!1};if(t.nonce&&!await this.claimTriggerNonce(t.nonce))return console.warn(`[AgentDO] rejected replayed trigger nonce ${t.nonce}`),{queued:!1,duplicate:!0};let n=t.runAsUserId;return n&&!((s=this.state.user)!=null&&s.email)&&this.state.injectedUserId!==n&&this.setState({...this.state,injectedUserId:n}),{queued:!0,taskId:await this.queue("processTrigger",t)}}async claimTriggerNonce(t){let n=`${qe}${t}`;if(await this.ctx.storage.get(n))return!1;let e=Date.now();await this.ctx.storage.put(n,e);let r=[...(await this.ctx.storage.list({prefix:qe})).entries()].filter(([,i])=>e-i>qo).map(([i])=>i);return r.length>0&&await this.ctx.storage.delete(r),!0}async processTrigger(t){if(!(await st(this.env,t.runId)).claimed){console.warn(`[AgentDO] activation ${t.activationId} skipped \u2014 run ${t.runId} already claimed`);return}try{this.state.engineState||await it(this,this.env);let e=v(rt(this.state.engineState)),s=Gt(e,t.inputs||{},t.label),r=await at({agent:this,env:this.env,ctx:this.ctx,payload:{text:s,inputs:t.inputs||{}},secrets:this.secrets,composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>t.runAsUserId||this.resolveSessionUserId(),runId:t.runId,shouldStop:()=>this.isRunStopRequested(t.runId),onSecretsLoaded:i=>{this.secrets=i}});await xt(this.env,t.runId,{status:r.status==="completed"?"succeeded":r.status==="stopped"?"skipped":"failed",error:r.error})}catch(e){let s=e instanceof Error?e.message:"Trigger execution failed";throw await xt(this.env,t.runId,{status:"failed",error:s}),e}finally{await this.clearRunStopRequest(t.runId)}}async onUserIdentity(t,n){let e=ot(n);if(!e){L(t,b.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:e}),L(t,b.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(t,n){let e=Wt(n);if(!e){L(t,b.SERVER_ERROR,"Invalid auth payload");return}let s=e.value.trim();s===""?delete this.userAuth[e.name]:this.userAuth[e.name]=e.value,L(t,b.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:e.name,set:s!==""}}))}async onClearHistory(t){await gt(this),await ht(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear();let n=this.state.engineState?{...this.state.engineState,cycle:void 0}:void 0;this.setState({...this.state,error:"",engineState:n,modelsCache:{},lastUpdated:new Date}),t&&L(t,b.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await Ie(this);let t=await J(this);`${JSON.stringify(t)}`}async onClose(t,n,e,s){console.log(`Session closed: ${this.state.sessionId} ${n} - ${e}`)}async onError(t){console.error("AgentDO encountered an error:",t)}};function Jr(o){let t=o.state;if(!t)return null;let n=["startNode","answerNode"];for(let e of n)if(!t.nodes.some(r=>r.type===e))return!1;return t.nodes.find(e=>e.type==="startNode")}import{importSPKI as Ko,jwtVerify as Xo}from"jose";function Xe(o){let t={};if(!o)return t;let n=o.split(";");for(let e of n){let s=e.indexOf("=");if(s>-1){let r=e.slice(0,s).trim(),i=e.slice(s+1).trim();r&&(t[r]=decodeURIComponent(i))}}return t}function So(o){return(typeof o.email=="string"?o.email.trim():"")||null}async function W(o,t,n){let e=Xe(o.headers.get("cookie")),s=new URL(o.url),r=e.access_token||s.searchParams.get("access_token"),i=await Jo(t,r);if(i.ok){let c=i.payload,d=So(c);return d?{id:c.sub,email:d,name:c.name,first_name:c.given_name,last_name:c.family_name,tenant:c.tenant,roles:c["ora-roles"],db_name:c.db_name||null,user_id:c.user_id||null}:null}return null}async function Jo(o,t){if(!t||typeof t!="string")return{ok:!1,payload:null,protectedHeader:null};if(!o.KC_RS256_PK)throw new Error("PK is not defined");let n=`-----BEGIN PUBLIC KEY-----
|
|
39
|
+
`):"";e.context={user_input:x,user_images:O,files:j},e.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},(f=n==null?void 0:n.onServerEvent)==null||f.call(n,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:k,error:_}=Lo(e.flowData);if(!k)g="failed",l=_||"Flow Format Error",(a=n==null?void 0:n.onError)==null||a.call(n,l);else{let L=tt(k.data),{values:N,errors:T}=Wt(L,R==null?void 0:R.inputs);if(T.length>0)return g="failed",l=`Invalid flow inputs: ${T.join("; ")}`,(m=n==null?void 0:n.onError)==null||m.call(n,l),{status:g,error:l};e.context={...e.context,inputs:N,...N},e.context.user_input||(e.context.user_input=x),await r(k),(y=n==null?void 0:n.onServerEvent)==null||y.call(n,{type:"agent:telemetry",content:{durationMs:Date.now()-p,tokenUsage:e.tokenUsage},timestamp:Date.now()})}}catch(R){R instanceof Ct?(g="stopped",l=R.message,(w=n==null?void 0:n.onServerEvent)==null||w.call(n,{type:"agent:stopped",content:l,timestamp:Date.now()})):(g="failed",l=R instanceof Error?R.message:"Agent execution failed",(h=n==null?void 0:n.onError)==null||h.call(n,l))}finally{(I=n==null?void 0:n.onServerEvent)==null||I.call(n,{type:"agent:complete",content:{status:g,durationMs:Date.now()-p},timestamp:Date.now()})}return{status:g,error:l}},d={startNode:Xt,classifierNode:Ht,llmNode:qt,memoNode:St,answerNode:Dt,apiNode:bt,toolNode:Lt};return c}var Ct=class extends Error{constructor(){super("Stopped by user"),this.name="FlowExecutionStoppedError"}};function Lo(o){var p,g;let t=(o==null?void 0:o.state)??o;if(!t||!t.nodes||!t.edges||t.edges.length===0)return{error:"Flow is missing state, nodes, or edges."};if(t.schemaVersion!==3)return{error:"Flow uses an unsupported variable schema. Recreate it in Agent Design 3.0."};for(let l of t.nodes){if(((p=l.data)==null?void 0:p.varMapping)!==void 0)return{error:`Flow uses removed varMapping on node ${l.id}.`};let f=ce(l);if(f.length>0)return{error:f[0]}}let n=t.nodes.filter(l=>l.type==="startNode");if(n.length!==1)return{error:`Flow must include exactly one START node, found ${n.length}.`};let e=n[0],s=t.nodes.filter(l=>l.type==="answerNode");if(s.length===0)return{error:"Flow must include at least one ANSWER node."};let r=new Map;for(let l of t.edges)r.has(l.source)||r.set(l.source,[]),r.get(l.source).push(l.target);let i=new Map;for(let l of t.edges)i.has(l.target)||i.set(l.target,[]),i.get(l.target).push(l.source);let c=Ee(e.id,r),d=new Set;for(let l of s){let f=Ee(l.id,i);for(let a of f)d.add(a)}let u=[];for(let l of c)if(!d.has(l)){let f=t.nodes.find(a=>a.id===l);if(f){let a=((g=f.data)==null?void 0:g.label)||"";u.push(`${l}(${a},${f.type})`)}}return u.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${u.join(", ")}`}:{startNode:e}}function Ee(o,t){let n=new Set,e=[o];for(n.add(o);e.length>0;){let s=e.shift(),r=t.get(s)||[];for(let i of r)n.has(i)||(n.add(i),e.push(i))}return n}function Ho(o,t){var n;return((n=o.state)==null?void 0:n.nodes.find(e=>e.id===t))||null}function Vo(o,t,n){var c;let e=t==null?void 0:t.state;if(!e)return null;let s=e.edges.filter(d=>d.source===o.id);if(s.length===0)return null;let r=s[0].target;if(o.type==="classifierNode"&&((c=n==null?void 0:n.context)!=null&&c.classified_id)){let d=n.context.classified_id,u=s.find(p=>p.sourceHandle===`source-${d}`);u?r=u.target:console.log(`No matching edge, falling back to first: ${r}`)}return Ho(t,r)}async function Le(o,t){var e,s;let n=(e=t==null?void 0:t.flowData)==null?void 0:e.flowId;if(!(o!=null&&o.HX_CORE_URL)||!n)return{engineState:t,refreshed:!1};try{let r=await Z(n,o),i={...t,flowData:{...r,tenant:t.flowData.tenant,flowId:n,chatId:t.flowData.chatId}},c=r==null?void 0:r.stateVersion,d=typeof c=="number"&&c!==((s=t.flowData)==null?void 0:s.stateVersion);return{engineState:i,refreshed:d}}catch(r){return console.error(`[flowRefresh] fetch failed for flow ${n}:`,r),{engineState:t,refreshed:!1}}}function He(o,t){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(t)}).catch(n=>{console.error("[sessionIndex] failed to index session",n)})}function Ve(){let o={};return{add(t,n){o[t]=n},hasOutputs(){return Object.keys(o).length>0},answerNodeIds(){return Object.keys(o)},snapshotData(){let t=Object.entries(o);return t.length===1?t[0][1]:Object.fromEntries(t)}}}function qo(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function qe(o,t){if(!qo(o))throw new Error("Structured outputs require HX_ORA_URL and HX_API_KEY");let n=await fetch(`${o.HX_ORA_URL}/internal/outputs/${encodeURIComponent(t.flowId)}/${encodeURIComponent(t.sessionId)}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:o.HX_API_KEY},body:JSON.stringify({runId:t.runId,createdAt:t.createdAt,data:t.data,answerNodeIds:t.answerNodeIds})});if(!n.ok){let e=await n.text().catch(()=>"");throw new Error(`Structured output persistence failed with ${n.status}${e?`: ${e}`:""}`)}}var Se=async(o,t)=>{fetch(`${t.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),`${JSON.stringify(o)}`};async function at(o,t){var r,i;let n=o.id||o.name||"",[e,s]=String(n).split("::");if(!e||!s)return null;try{let d=(r=(await W(e,t)).metadata)==null?void 0:r.tenant,u=await Z(e,t),p=(i=o.state)==null?void 0:i.user,g={flowData:{...u,tenant:d,flowId:e,chatId:s},executedNodes:[],context:p?{user:p}:{}};return o.setState({...o.state,engineState:g}),g}catch(c){return console.error("Failed to initialize engine state:",c),null}}async function ct(o){var D,j,k,_,L;let{agent:t,env:n,ctx:e,payload:s,connection:r}=o,i=Date.now(),c=[],d=o.runId?Ve():void 0,u=async()=>await z(t),p=async N=>{await we(t,N)},g=async N=>{if(t.state.modelsCache&&t.state.modelsCache[N])return t.state.modelsCache[N];try{let{fetchOraModel:T}=await import("./oraApi-4O3W5LXD.js"),F=await T(N,n);return t.setState({...t.state,modelsCache:{...t.state.modelsCache||{},[N]:F}}),F}catch(T){throw console.error(`Error fetching model ${N}:`,T),T}},l={id:So(),role:"user",type:"text",content:s.text,images:s.images,ts:Date.now()};await p(l);let f={onChangeState:N=>{t.setState({...t.state,engineState:N})},onServerEvent:async N=>{var T;await((T=o.onServerEvent)==null?void 0:T.call(o,N)),c.push(N)},onTelemetry:async N=>{var T,F,U,M,X,b;await Se({...N,userId:o.resolveUserId(),tenant:((F=(T=t.state.engineState)==null?void 0:T.flowData)==null?void 0:F.tenant)||"",flowId:((M=(U=t.state.engineState)==null?void 0:U.flowData)==null?void 0:M.flowId)||"",sessionId:((b=(X=t.state.engineState)==null?void 0:X.flowData)==null?void 0:b.chatId)||""},n)},onError:N=>{var T;(T=o.onError)==null||T.call(o,N),t.setState({...t.state,error:N})},shouldStop:o.shouldStop},a=t.state.engineState?{...t.state.engineState}:null;if(a){let{engineState:N,refreshed:T}=await Le(n,a);a=N,T&&t.setState({...t.state,engineState:a,modelsCache:{}})}else if(a=await at(t,n),!a){let N="Failed to initialize agent";return f.onError(N),{status:"failed",error:N}}let m=o.secrets;if(!m||Object.keys(m).length===0){let N=(D=a.flowData)==null?void 0:D.tenant;m=N?await Nt(n,N):{},(j=o.onSecretsLoaded)==null||j.call(o,m)}let y=o.user??t.state.user??void 0;y&&!((k=a.context)!=null&&k.user)&&(a.context={...a.context||{},user:y});let w=pt(it(a)),h=typeof a.cycle=="number"?a.cycle:0;w.enabled&&(h=await $e(t,a),a.cycle=h,t.setState({...t.state,engineState:a}));let I=ke(t,{env:n,ctx:e,conn:r,getMessages:u,setMessages:p,getOraModel:g,secrets:m,userAuth:o.userAuth,user:y,composioSessions:o.composioSessions,publicOrigin:o.publicOrigin,skillRefCache:o.skillRefCache,runId:o.runId,outputCollector:d},a,h,o.onMemoryRef),R=await je(I,a,f)(s);if(R.status==="completed"&&o.runId&&(d!=null&&d.hasOutputs())){let{flowId:N,chatId:T}=a.flowData??{};if(!N||!T)R={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await qe(n,{flowId:N,sessionId:T,runId:o.runId,createdAt:new Date(i).toISOString(),data:d.snapshotData(),answerNodeIds:d.answerNodeIds()});let F={...a.results||{}};for(let U of d.answerNodeIds())F[U]={...F[U]||{},persisted:!0,runId:o.runId};a={...a,results:F},t.setState({...t.state,engineState:a})}catch(F){let U=F instanceof Error?F.message:"Structured output persistence failed";f.onError(U),await f.onServerEvent({type:"error:answer-output",content:{runId:o.runId,error:U},timestamp:Date.now()}),R={status:"failed",error:U}}}let{tenant:x,flowId:O,chatId:C}=a.flowData??{};return x&&O&&C&&e.waitUntil(He(n,{id:`${O}::${C}`,tenant:x,flowId:O,sessionId:C,userId:o.resolveUserId(),title:(_=s.text)==null?void 0:_.slice(0,120),turnTs:i,events:c})),R.status==="completed"&&((L=I.memoryConfig)!=null&&L.enabled)&&I.memoryConfig.mode==="summarize"&&e&&e.waitUntil(ie(t,I,h)),t.setState({...t.state,lastUpdated:new Date}),{status:R.status,error:R.error,engineState:a}}import{nanoid as Xo}from"nanoid";function Ko(o){let t=o.headers.get("X-User-Payload");if(!t)return null;try{let n=JSON.parse(t),e=typeof(n==null?void 0:n.email)=="string"?nt(n.email):null;return e?{...n,email:e}:null}catch{return null}}async function Xe(o,t,n,e){var s;try{let r=await t.json(),i=r.message;if(!i||typeof i!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let c=typeof r.userId=="string"?nt(r.userId):null,d=Ko(t),u=d==null?void 0:d.email;d?o.setState({...o.state,user:d,injectedUserId:u}):c&&!((s=o.state.user)!=null&&s.email)&&o.setState({...o.state,injectedUserId:c});let p=()=>u??c??o.state.injectedUserId??void 0;o.skillRefCache||(o.skillRefCache=new Map);let g=r.inputs&&typeof r.inputs=="object"?r.inputs:void 0;if(!o.state.engineState&&!await at(o,n))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let l=`run-${Xo(12)}`;await o.registerManualRun(l,i,p()),await rt(n,l).catch(y=>{console.warn(`[AgentHTTP] could not mark manual run ${l} as running`,y)});let f;try{f=await ct({agent:o,env:n,ctx:e,payload:{text:i,inputs:g},skillRefCache:o.skillRefCache,user:d??void 0,resolveUserId:p,runId:l,shouldStop:()=>o.isRunStopRequested(l)}),e.waitUntil(o.completeManualRun(l,f.status==="completed"?"succeeded":f.status==="stopped"?"skipped":"failed",f.error))}finally{await o.clearRunStopRequest(l)}if(f.status==="failed")return new Response(JSON.stringify({error:f.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});if(f.status==="stopped")return new Response(JSON.stringify({error:f.error||"Stopped by user"}),{status:409,headers:{"content-type":"application/json"}});let m=(await z(o)).reverse().find(y=>y.role==="assistant");return new Response(JSON.stringify({answer:(m==null?void 0:m.content)||""}),{headers:{"content-type":"application/json"}})}catch(r){return new Response(JSON.stringify({error:r.message}),{status:500,headers:{"content-type":"application/json"}})}}async function Ke(o){try{return await wt(o),await xt(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(t){return new Response(JSON.stringify({error:t.message}),{status:500,headers:{"content-type":"application/json"}})}}var Je="trigger:nonce:",Go=900*1e3,Kt="run:stop:",ze=class extends Jo{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{}};resolveSessionUserId(){var t;return((t=this.state.user)==null?void 0:t.email)??this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async inspectPersistedSession(t){return t==="state"?{state:this.state}:t==="messages"?{messages:await z(this)}:{context:await Re(this)}}async requestRunStop(t){return t!=null&&t.trim()?(await this.ctx.storage.put(`${Kt}${t}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(t){return!!await this.ctx.storage.get(`${Kt}${t}`)}async clearRunStopRequest(t){await this.ctx.storage.delete(`${Kt}${t}`)}async onRequest(t){let n=new URL(t.url);if(n.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(n.pathname.endsWith("/history")){let e=await z(this);return new Response(JSON.stringify(e),{headers:{"content-type":"application/json"}})}if(n.pathname.endsWith("/context")){let e={"content-type":"application/json","access-control-allow-origin":"*"};if(!t.headers.get("X-User-Payload"))return new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:e});let s=n.searchParams.get("ref");if(s){let i=await Rt(this,s);return i?new Response(JSON.stringify({entry:i}),{headers:e}):new Response(JSON.stringify({error:"Not found"}),{status:404,headers:e})}let r=await ht(this);return new Response(JSON.stringify({entries:r}),{headers:e})}return t.method==="POST"&&n.pathname.endsWith("/message")?Xe(this,t,this.env,this.ctx):t.method==="DELETE"&&n.pathname.endsWith("/clear")?Ke(this):new Response("Ready to assist.")}async onConnect(t,n){var l,f,a,m,y;let[e,s]=t.server.split("::"),i=(l=(await W(e,this.env)).metadata)==null?void 0:l.tenant;this.secrets=await Nt(this.env,i),this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let c=null;if(n.request){try{this.publicOrigin=new URL(n.request.url).origin}catch{}let w=n.request.headers.get("X-User-Payload");if(w)try{c=JSON.parse(w)}catch(h){console.warn("Failed to parse X-User-Payload",h)}}let d=await Z(e,this.env);this.setState({...this.state,user:c||null,sessionId:s,engineState:{flowData:{...d,tenant:i,flowId:e,chatId:s},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 z(this);H(t,E.SERVER_HISTORY,JSON.stringify({messages:u}));let g=(((f=d==null?void 0:d.state)==null?void 0:f.nodes)??(d==null?void 0:d.nodes)??[]).find(w=>w.type==="startNode");if(g){let w={allow_images:((a=g.data)==null?void 0:a.allow_images)??!1,allow_documents:((m=g.data)==null?void 0:m.allow_documents)??!1,greeting:(y=g.data)==null?void 0:y.greeting};H(t,E.SERVER_CONFIG,JSON.stringify(w))}}async onMessage(t,n){if(typeof n!="string")return;let e=n.indexOf(":");if(e===-1)return;let s=n.substring(0,e),r=n.substring(e+1);if(!s||!r)return;let c={[E.USER_MESSAGE]:d=>this.onUserMessage(t,d),[E.USER_CLEAR_HISTORY]:()=>this.onClearHistory(t),[E.USER_AUTH]:d=>this.onUserAuth(t,d),[E.USER_IDENTITY]:d=>this.onUserIdentity(t,d)}[s];c&&await c(r)}async onUserMessage(t,n){let e=dt(n),s=`run-${zo(12)}`;await this.registerManualRun(s,e.text),await rt(this.env,s).catch(r=>{console.warn(`[AgentDO] could not mark manual run ${s} as running`,r)});try{let r=await ct({agent:this,env:this.env,ctx:this.ctx,payload:e,connection:t,secrets:this.secrets,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:this.state.user,resolveUserId:()=>this.resolveSessionUserId(),runId:s,shouldStop:()=>this.isRunStopRequested(s),onServerEvent:i=>{H(t,E.SERVER_EVENT,JSON.stringify(i))},onError:i=>{H(t,E.SERVER_ERROR,i)},onMemoryRef:i=>{H(t,E.SERVER_EVENT,JSON.stringify({type:"info:memory:updated",content:{ref:i}}))},onSecretsLoaded:i=>{this.secrets=i}});this.ctx.waitUntil(this.completeManualRun(s,r.status==="completed"?"succeeded":r.status==="stopped"?"skipped":"failed",r.error))}finally{await this.clearRunStopRequest(s)}}registerManualRun(t,n,e){var d;let{tenant:s,flowId:r,chatId:i}=((d=this.state.engineState)==null?void 0:d.flowData)??{};if(!s||!r||!i)return Promise.resolve();let c=Ce(e||this.resolveSessionUserId(),i);return Oe(this.env,{id:t,tenant:s,flowId:r,userId:c,sessionId:i,label:n==null?void 0:n.slice(0,120)})}completeManualRun(t,n,e){return Tt(this.env,t,{status:n,error:e})}async enqueueTrigger(t){var s;if(!(t!=null&&t.runId)||!(t!=null&&t.flowId))return{queued:!1};if(t.nonce&&!await this.claimTriggerNonce(t.nonce))return console.warn(`[AgentDO] rejected replayed trigger nonce ${t.nonce}`),{queued:!1,duplicate:!0};let n=t.runAsUserId;return n&&!((s=this.state.user)!=null&&s.email)&&this.state.injectedUserId!==n&&this.setState({...this.state,injectedUserId:n}),{queued:!0,taskId:await this.queue("processTrigger",t)}}async claimTriggerNonce(t){let n=`${Je}${t}`;if(await this.ctx.storage.get(n))return!1;let e=Date.now();await this.ctx.storage.put(n,e);let r=[...(await this.ctx.storage.list({prefix:Je})).entries()].filter(([,i])=>e-i>Go).map(([i])=>i);return r.length>0&&await this.ctx.storage.delete(r),!0}async processTrigger(t){if(!(await rt(this.env,t.runId)).claimed){console.warn(`[AgentDO] activation ${t.activationId} skipped \u2014 run ${t.runId} already claimed`);return}try{this.state.engineState||await at(this,this.env);let e=tt(it(this.state.engineState)),s=Yt(e,t.inputs||{},t.label),r=await ct({agent:this,env:this.env,ctx:this.ctx,payload:{text:s,inputs:t.inputs||{}},secrets:this.secrets,composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>t.runAsUserId||this.resolveSessionUserId(),runId:t.runId,shouldStop:()=>this.isRunStopRequested(t.runId),onSecretsLoaded:i=>{this.secrets=i}});await Tt(this.env,t.runId,{status:r.status==="completed"?"succeeded":r.status==="stopped"?"skipped":"failed",error:r.error})}catch(e){let s=e instanceof Error?e.message:"Trigger execution failed";throw await Tt(this.env,t.runId,{status:"failed",error:s}),e}finally{await this.clearRunStopRequest(t.runId)}}async onUserIdentity(t,n){let e=nt(n);if(!e){H(t,E.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:e}),H(t,E.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(t,n){let e=Bt(n);if(!e){H(t,E.SERVER_ERROR,"Invalid auth payload");return}let s=e.value.trim();s===""?delete this.userAuth[e.name]:this.userAuth[e.name]=e.value,H(t,E.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:e.name,set:s!==""}}))}async onClearHistory(t){await wt(this),await xt(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear();let n=this.state.engineState?{...this.state.engineState,cycle:void 0}:void 0;this.setState({...this.state,error:"",engineState:n,modelsCache:{},lastUpdated:new Date}),t&&H(t,E.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await Ae(this);let t=await z(this);`${JSON.stringify(t)}`}async onClose(t,n,e,s){console.log(`Session closed: ${this.state.sessionId} ${n} - ${e}`)}async onError(t){console.error("AgentDO encountered an error:",t)}};function fi(o){let t=o.state;if(!t)return null;let n=["startNode","answerNode"];for(let e of n)if(!t.nodes.some(r=>r.type===e))return!1;return t.nodes.find(e=>e.type==="startNode")}import{importSPKI as Wo,jwtVerify as Yo}from"jose";function Ge(o){let t={};if(!o)return t;let n=o.split(";");for(let e of n){let s=e.indexOf("=");if(s>-1){let r=e.slice(0,s).trim(),i=e.slice(s+1).trim();r&&(t[r]=decodeURIComponent(i))}}return t}function Bo(o){return(typeof o.email=="string"?o.email.trim():"")||null}async function Y(o,t,n){let e=Ge(o.headers.get("cookie")),s=new URL(o.url),r=e.access_token||s.searchParams.get("access_token"),i=await Qo(t,r);if(i.ok){let c=i.payload,d=Bo(c);return d?{id:c.sub,email:d,name:c.name,first_name:c.given_name,last_name:c.family_name,tenant:c.tenant,roles:c["ora-roles"],db_name:c.db_name||null,user_id:c.user_id||null}:null}return null}async function Qo(o,t){if(!t||typeof t!="string")return{ok:!1,payload:null,protectedHeader:null};if(!o.KC_RS256_PK)throw new Error("PK is not defined");let n=`-----BEGIN PUBLIC KEY-----
|
|
40
40
|
${o.KC_RS256_PK}
|
|
41
|
-
-----END PUBLIC KEY-----`,e=await
|
|
42
|
-
`)}async function Qe(o,t){let n=await crypto.subtle.importKey("raw",Je.encode(o),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return Go(await crypto.subtle.sign("HMAC",n,Je.encode(t)))}function Yo(o,t){if(o.length!==t.length)return!1;let n=0;for(let e=0;e<o.length;e++)n|=o.charCodeAt(e)^t.charCodeAt(e);return n===0}async function ni(o){let t=String(o.timestamp??Math.floor(Date.now()/1e3)),n=await Qe(o.secret,Be({timestamp:t,nonce:o.nonce,tenant:o.tenant,destination:o.destination,body:o.body}));return{"content-type":"application/json",[Ye]:o.tenant,[Ge]:t,[We]:o.nonce,[ze]:`v1=${n}`}}async function Ze(o){var u,p,f,l,m;if(!((u=o.secret)!=null&&u.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let t=(p=o.headers.get(Ye))==null?void 0:p.trim(),n=(f=o.headers.get(Ge))==null?void 0:f.trim(),e=(l=o.headers.get(We))==null?void 0:l.trim(),s=(m=o.headers.get(ze))==null?void 0:m.trim();if(!t||!n||!e||!s)return{ok:!1,error:"missing signature headers"};if(!s.startsWith("v1="))return{ok:!1,error:"unsupported signature version"};let r=Number(n);if(!Number.isFinite(r))return{ok:!1,error:"invalid timestamp"};let i=Math.floor((o.now??Date.now())/1e3),c=o.toleranceSeconds??300;if(Math.abs(i-r)>c)return{ok:!1,error:"stale timestamp"};let d=await Qe(o.secret.trim(),Be({timestamp:n,nonce:e,tenant:t,destination:o.url,body:o.body}));return Yo(s.slice(3),d)?{ok:!0,tenant:t,nonce:e,timestamp:r}:{ok:!1,error:"signature mismatch"}}var S=(o,t=200)=>new Response(JSON.stringify(o),{status:t,headers:{"content-type":"application/json"}});async function ve(o,t,n){var u;if(new URL(o.url).pathname!=="/api/triggers/dispatch")return;if(o.method!=="POST")return S({error:"Method not allowed"},405);let s=await o.text(),r=await Ze({secret:t.HX_API_KEY,body:s,url:o.url,headers:o.headers});if(!r.ok)return console.warn(`[triggers] rejected dispatch: ${r.error}`),S({error:"Invalid signature"},401);let i;try{i=JSON.parse(s)}catch{return S({error:"Invalid payload"},400)}if(!(i!=null&&i.runId)||!(i!=null&&i.flowId)||!(i!=null&&i.runAsUserId)||!(i!=null&&i.tenant)||!(i!=null&&i.activationId)||!(i!=null&&i.triggerId)||!(i!=null&&i.triggerKind)||!(i!=null&&i.invocationMode))return S({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(i.tenant!==r.tenant)return S({error:"Tenant mismatch"},403);let c;try{c=await G(i.flowId,t)}catch{return S({error:"Flow not found"},404)}if(!((u=c==null?void 0:c.metadata)!=null&&u.tenant)||c.metadata.tenant!==i.tenant)return console.warn(`[triggers] flow ${i.flowId} does not belong to tenant ${i.tenant}`),S({error:"Tenant mismatch"},403);let d=await Se(t,{...i,sessionId:i.sessionId||i.runAsUserId,nonce:r.nonce});return d.status==="error"?S({error:d.error},502):d.status==="deduped"?S({deduped:!0,runId:d.runId},200):S({accepted:!0,runId:d.runId,taskId:d.taskId},202)}var Bo=/^[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}$/,Qo=new Set(["state","messages","context"]);async function Zo(o,t){let n=new URL(o.url);if(!n.pathname.startsWith("/api/internal/sessions/"))return;let e=n.pathname.split("/");if(e[6]!=="runs"||e[8]!=="stop"||e.length!==9)return;if(o.method!=="POST")return new Response("Method not allowed",{status:405});if(!t.HX_API_KEY||o.headers.get("Authorization")!==t.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=decodeURIComponent(e[4]||""),r=decodeURIComponent(e[5]||""),i=decodeURIComponent(e[7]||"");if(!s||!r||!i)return new Response("Not found",{status:404});try{let c=await Ct(t.AGENT,`${s}::${r}`);return Response.json(await c.requestRunStop(i))}catch(c){return console.error("[agents] failed to request run stop",c),Response.json({error:"Failed to stop run"},{status:502})}}async function vo(o,t){let n=new URL(o.url);if(!n.pathname.startsWith("/api/internal/sessions/"))return;if(o.method!=="GET")return new Response("Method not allowed",{status:405});let e=o.headers.get("Authorization")||"";if(!t.HX_API_KEY||e!==t.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=n.pathname.split("/"),r=decodeURIComponent(s[4]||""),i=decodeURIComponent(s[5]||""),c=s[6];if(!r||!i||!c||!Qo.has(c))return new Response("Not found",{status:404});try{let u=await(await Ct(t.AGENT,`${r}::${i}`)).inspectPersistedSession(c);return Response.json(u)}catch(d){return console.error("[agents] failed to inspect persisted session",d),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function fi(o,t,n){var c,d,u,p;let e=new URL(o.url),s=await ve(o,t,n);if(s instanceof Response)return s;let r=await Zo(o,t);if(r instanceof Response)return r;let i=await vo(o,t);if(i instanceof Response)return i;if(e.pathname.startsWith("/a/")){let f=e.pathname.split("/"),l=f[2],m=f[3];try{if(!l)return Response.redirect(new URL("/",e.origin).toString(),302);let a;try{a=await G(l,t)}catch{return new Response("Flow not found",{status:404})}if(!a.metadata||((c=a.metadata)==null?void 0:c.status)!=="active")return new Response("NO chat",{status:404});if(((d=a.metadata)==null?void 0:d.visibility)==="private"&&!await W(o,t,n)){let y=new URL("/login",e.origin);return y.searchParams.set("nextURL",`${e.pathname}${e.search}`),Response.redirect(y.toString(),302)}if(!m){let g=crypto.randomUUID(),y=new URL(`/a/${l}/${g}`,e.origin);return Response.redirect(y.toString(),302)}if(!Bo.test(m))return new Response("Id del chat no v\xE1lido",{status:400})}catch(a){return console.error("Error accessing flow KV:",a),new Response("Flow error",{status:500})}}if(e.pathname.startsWith("/api/agent/flow")){let f=e.pathname.split("/"),l=f[4],m=f[5],a=`${l}::${m}`;try{let g=await W(o,t,n);if(!g){let R=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${R}) \u2014 Composio connections from tool editor will not apply`)}let y=new Headers(o.headers);y.delete("X-User-Payload"),g&&y.set("X-User-Payload",JSON.stringify(g));let h=new Request(o,{headers:y});return(await Ct(t.AGENT,a)).fetch(h)}catch(g){return console.error("Error accessing agent:",g),new Response("Agent error",{status:500})}}if(e.pathname.startsWith("/api/ora/connect")){let f=e.pathname.split("/"),l=f[4],m=f[5];if(!l||!m)return new Response("Missing flowId or sessionId",{status:400});let a=o.headers.get("Authorization")||e.searchParams.get("authorization");if(!a)return new Response("Missing Authorization header",{status:401});try{let g=`${t.HX_CORE_URL}/p/v1/validation/key/agent/${l}`,h=await(await fetch(g,{method:"GET",headers:{Authorization:a}})).json();if(((u=h.payload)==null?void 0:u.flowId)!==l)return console.error("FlowId mismatch:",(p=h.payload)==null?void 0:p.flowId,"!==",l),new Response("Validation error",{status:403});let w=`${l}::${m}`,x=await W(o,t,n);if(!x){let P=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${P}) \u2014 Composio connections from tool editor will not apply`)}let R=new Headers(o.headers);R.delete("X-User-Payload"),x&&R.set("X-User-Payload",JSON.stringify(x));let T=new Request(o,{headers:R});return(await Ct(t.AGENT,w)).fetch(T)}catch(g){return console.error("Error in /api/ora/connect:",g),new Response("Internal error",{status:500})}}}async function yi(o,t,n){let e=new URL(o.url),s=o.method;if(!e.pathname.startsWith("/api/instances"))return;let r=await W(o,t,n);if(!r)return new Response("Unauthorized",{status:401});let i=t.HX_CORE_URL,c=t.HX_API_KEY;if(!i||!c)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let u=e.pathname.slice("/api/instances".length);u.startsWith("/")&&(u=u.slice(1)),u.endsWith("/")&&(u=u.slice(0,-1));let p="/ora/instances";u&&(p+=`/${u}`);let f=i.endsWith("/")?i.slice(0,-1):i,l=new URL(`${f}${p}`);e.searchParams.forEach((g,y)=>{l.searchParams.set(y,g)}),s==="GET"&&!u&&l.searchParams.set("filter_user_id",r.email);let m=new Headers;m.set("Authorization",c),m.set("Content-Type","application/json"),m.set("X-User-Payload",JSON.stringify(r));let a={method:s,headers:m};if(["POST","PATCH","PUT"].includes(s))try{a.body=await o.text()}catch(g){console.error("Error reading request body:",g)}try{let g=await fetch(l.toString(),a),y=await g.text();return new Response(y,{status:g.status,headers:{"Content-Type":"application/json"}})}catch(g){return console.error("Error proxying to flow instance backend:",g),new Response("Internal Server Error",{status:500})}}async function Ri(o,t,n){let e=new URL(o.url);if(o.method==="POST"&&e.pathname==="/auth/login")try{let s=await o.formData(),r=s.get("username"),i=s.get("password"),c=s.get("nextURL")||"/";if(!r||!i)return new Response("Missing username or password",{status:400});let d=new URLSearchParams;d.append("username",r),d.append("password",i),d.append("grant_type","password"),d.append("client_id",t.KC_CLIENT_ID),d.append("client_secret",t.KC_CLIENT_SECRET);let u=await fetch(`${t.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 p=await u.json(),f=new Response(null,{status:302,headers:{Location:c}}),l=(m,a,g)=>{f.headers.append("Set-Cookie",`${m}=${a}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${g}`)};return p.access_token&&l("access_token",p.access_token,p.expires_in),p.refresh_token&&l("refresh_token",p.refresh_token,p.refresh_expires_in||3600*24*30),p.id_token&&l("id_token",p.id_token,p.expires_in),f}catch(s){return console.error("Auth error:",s),new Response("Internal Server Error",{status:500})}if(e.pathname==="/auth/logout"){let s=new Response(null,{status:302,headers:{Location:"/login"}}),r=i=>{s.headers.append("Set-Cookie",`${i}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return r("access_token"),r("refresh_token"),r("id_token"),s}if(e.pathname.startsWith("/s/")){let s=await W(o,t,n);if(!s){let r=new URL("/login",e.origin);return r.searchParams.set("nextURL",`${e.pathname}${e.search}`),Response.redirect(r.toString(),302)}return{user:s}}}export{Ke as AgentDO,cn as FLOW_INPUT_NAME_RE,Nt as FlowExecutionStoppedError,dn as GENERATION_PARAM_KEYS,pn as GENERATION_PRESETS,ln as MAX_USER_IDENTITY_LENGTH,kn as MODEL_REGISTRY_SNAPSHOT,Z as NodeType,un as PRESET_PARAM_KEYS,Tn as REASONING_EFFORT_LEVELS,de as TOOL_REGISTRY_SNAPSHOT,We as TRIGGER_NONCE_HEADER,ze as TRIGGER_SIGNATURE_HEADER,oi as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,Ye as TRIGGER_TENANT_HEADER,Ge as TRIGGER_TIMESTAMP_HEADER,gn as applyPresetToOverrides,vt as buildReasoningProviderOptions,ni as buildSignedTriggerHeaders,Gt as buildTriggerMessageText,nn as buildUrl,So as canonicalUserEmail,st as claimRun,ht as clearAllContext,gt as clearAllMessages,xt as completeRun,tn as convertTempMessure,kt as createRun,Re as deleteContextToolsUpToCycle,fn as deriveParamSupport,Se as dispatchTrigger,Jt as embedText,Ie as ensureAgentTables,no as ensureContextTable,oo as ensureMessagesTable,ye as getAllContext,J as getAllMessages,wt as getContext,we as getContextData,yt as getContextIndex,_n as getDefaultOutVars,X as getEffectiveOutVars,v as getFlowInputDefs,xe as getMaxContextCycle,$n as getModelEntry,fi as handleAgentsRoutes,Ri as handleAuthRoutes,Qr as handleCommonRoutes,yi as handleIntancesRoutes,vo as handlePersistedSessionInspection,Zo as handleSessionRunControl,ve as handleTriggerRoutes,rn as hashText,it as initializeEngineState,le as jsonSchemaToZod,et as logc,b as messageTypes,Wo as normalizeDestination,yn as normalizeEffectiveParams,zt as normalizeFlowInputs,An as normalizeModelEntry,Nn as normalizeReasoning,hn as openAiReasoningParamSupport,wn as openAiStandardParamSupport,Xe as parseCookies,Wt as parseUserAuth,lt as parseUserMessage,Yt as pickNodeOverrides,Cn as reasoningEffortLevels,Qt as reasoningExposable,Te as recordRun,On as registerProvider,ao as resolveAnswerMappings,he as resolveContextRef,dt as resolveModelById,tt as resolveOutVarRef,mn as resolvePreset,Zt as resolveReasoningEffort,ie as resolveTemplate,at as runAgentTurn,on as safeParseJSON,ot as sanitizeUserIdentity,Le as sendEvent,L as serverSend,ge as setContext,me as setMessage,Qe as signTriggerMaterial,Me as startEngine,In as stripUnsupportedFromNodeData,en as tempTool,Yo as timingSafeEqualHex,Bt as toStreamTextSettings,Be as triggerSignatureMaterial,sn as twitter,Jr as validateFlowStart,an as vectorize,Jo as verifyToken,Ze as verifyTriggerRequest,W as verifyUser,pt as walkPath,xn as workersAiParamSupport,Rn as xaiParamSupport};
|
|
41
|
+
-----END PUBLIC KEY-----`,e=await Wo(n,"RS256");try{let{payload:s,protectedHeader:r}=await Yo(t,e);return{ok:!0,payload:s,protectedHeader:r}}catch(s){return console.error("JWT verification failed:",s),{ok:!1,payload:null,protectedHeader:null}}}async function Ri(o,t,n){let e=new URL(o.url);if(e.pathname==="/favicon.ico")return new Response(null,{status:204});if(e.pathname.startsWith("/.well-known/appspecific"))return new Response(null,{status:204})}import{getAgentByName as Ot}from"agents";import{getAgentByName as Zo}from"agents";async function We(o,t){let n=t.sessionId||t.runAsUserId,e=t.inputs||{},s=t.runId;if(!s){let d=await Ft(o,{tenant:t.tenant,flowId:t.flowId,userId:t.runAsUserId,sessionId:n,triggerId:t.triggerId,triggerKind:t.triggerKind,invocationMode:t.invocationMode,activationId:t.activationId,deliveryId:void 0,externalDeliveryId:t.externalDeliveryId,correlationKey:t.correlationKey,inputs:e,label:t.label});if(!d)return{status:"error",error:"Failed to register run"};if(!d.created&&d.run.status!=="queued")return{status:"deduped",runId:d.run.id};s=d.run.id}let r={...t,sessionId:n,runId:s,inputs:e},c=await(await Zo(o.AGENT,`${t.flowId}::${n}`)).enqueueTrigger(r);return c.duplicate?{status:"deduped",runId:s}:c.queued?{status:"queued",runId:s,activation:r,taskId:c.taskId}:{status:"error",error:"Failed to queue trigger"}}var Be="x-ora-signature",Qe="x-ora-timestamp",Ze="x-ora-nonce",ve="x-ora-tenant",Ai=300,Ye=new TextEncoder;function vo(o){return[...new Uint8Array(o)].map(t=>t.toString(16).padStart(2,"0")).join("")}function tn(o){try{let t=new URL(o);return`${t.origin}${t.pathname.replace(/\/$/,"")}`}catch{return o.replace(/\/$/,"")}}function to(o){return["v1",o.timestamp,o.nonce,o.tenant,tn(o.destination),o.body].join(`
|
|
42
|
+
`)}async function eo(o,t){let n=await crypto.subtle.importKey("raw",Ye.encode(o),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return vo(await crypto.subtle.sign("HMAC",n,Ye.encode(t)))}function en(o,t){if(o.length!==t.length)return!1;let n=0;for(let e=0;e<o.length;e++)n|=o.charCodeAt(e)^t.charCodeAt(e);return n===0}async function Ci(o){let t=String(o.timestamp??Math.floor(Date.now()/1e3)),n=await eo(o.secret,to({timestamp:t,nonce:o.nonce,tenant:o.tenant,destination:o.destination,body:o.body}));return{"content-type":"application/json",[ve]:o.tenant,[Qe]:t,[Ze]:o.nonce,[Be]:`v1=${n}`}}async function oo(o){var u,p,g,l,f;if(!((u=o.secret)!=null&&u.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let t=(p=o.headers.get(ve))==null?void 0:p.trim(),n=(g=o.headers.get(Qe))==null?void 0:g.trim(),e=(l=o.headers.get(Ze))==null?void 0:l.trim(),s=(f=o.headers.get(Be))==null?void 0:f.trim();if(!t||!n||!e||!s)return{ok:!1,error:"missing signature headers"};if(!s.startsWith("v1="))return{ok:!1,error:"unsupported signature version"};let r=Number(n);if(!Number.isFinite(r))return{ok:!1,error:"invalid timestamp"};let i=Math.floor((o.now??Date.now())/1e3),c=o.toleranceSeconds??300;if(Math.abs(i-r)>c)return{ok:!1,error:"stale timestamp"};let d=await eo(o.secret.trim(),to({timestamp:n,nonce:e,tenant:t,destination:o.url,body:o.body}));return en(s.slice(3),d)?{ok:!0,tenant:t,nonce:e,timestamp:r}:{ok:!1,error:"signature mismatch"}}var J=(o,t=200)=>new Response(JSON.stringify(o),{status:t,headers:{"content-type":"application/json"}});async function no(o,t,n){var u;if(new URL(o.url).pathname!=="/api/triggers/dispatch")return;if(o.method!=="POST")return J({error:"Method not allowed"},405);let s=await o.text(),r=await oo({secret:t.HX_API_KEY,body:s,url:o.url,headers:o.headers});if(!r.ok)return console.warn(`[triggers] rejected dispatch: ${r.error}`),J({error:"Invalid signature"},401);let i;try{i=JSON.parse(s)}catch{return J({error:"Invalid payload"},400)}if(!(i!=null&&i.runId)||!(i!=null&&i.flowId)||!(i!=null&&i.runAsUserId)||!(i!=null&&i.tenant)||!(i!=null&&i.activationId)||!(i!=null&&i.triggerId)||!(i!=null&&i.triggerKind)||!(i!=null&&i.invocationMode))return J({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(i.tenant!==r.tenant)return J({error:"Tenant mismatch"},403);let c;try{c=await W(i.flowId,t)}catch{return J({error:"Flow not found"},404)}if(!((u=c==null?void 0:c.metadata)!=null&&u.tenant)||c.metadata.tenant!==i.tenant)return console.warn(`[triggers] flow ${i.flowId} does not belong to tenant ${i.tenant}`),J({error:"Tenant mismatch"},403);let d=await We(t,{...i,sessionId:i.sessionId||i.runAsUserId,nonce:r.nonce});return d.status==="error"?J({error:d.error},502):d.status==="deduped"?J({deduped:!0,runId:d.runId},200):J({accepted:!0,runId:d.runId,taskId:d.taskId},202)}var on=/^[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}$/,nn=new Set(["state","messages","context"]);async function sn(o,t){let n=new URL(o.url);if(!n.pathname.startsWith("/api/internal/sessions/"))return;let e=n.pathname.split("/");if(e[6]!=="runs"||e[8]!=="stop"||e.length!==9)return;if(o.method!=="POST")return new Response("Method not allowed",{status:405});if(!t.HX_API_KEY||o.headers.get("Authorization")!==t.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=decodeURIComponent(e[4]||""),r=decodeURIComponent(e[5]||""),i=decodeURIComponent(e[7]||"");if(!s||!r||!i)return new Response("Not found",{status:404});try{let c=await Ot(t.AGENT,`${s}::${r}`);return Response.json(await c.requestRunStop(i))}catch(c){return console.error("[agents] failed to request run stop",c),Response.json({error:"Failed to stop run"},{status:502})}}async function rn(o,t){let n=new URL(o.url);if(!n.pathname.startsWith("/api/internal/sessions/"))return;if(o.method!=="GET")return new Response("Method not allowed",{status:405});let e=o.headers.get("Authorization")||"";if(!t.HX_API_KEY||e!==t.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=n.pathname.split("/"),r=decodeURIComponent(s[4]||""),i=decodeURIComponent(s[5]||""),c=s[6];if(!r||!i||!c||!nn.has(c))return new Response("Not found",{status:404});try{let u=await(await Ot(t.AGENT,`${r}::${i}`)).inspectPersistedSession(c);return Response.json(u)}catch(d){return console.error("[agents] failed to inspect persisted session",d),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function bi(o,t,n){var c,d,u,p;let e=new URL(o.url),s=await no(o,t,n);if(s instanceof Response)return s;let r=await sn(o,t);if(r instanceof Response)return r;let i=await rn(o,t);if(i instanceof Response)return i;if(e.pathname.startsWith("/a/")){let g=e.pathname.split("/"),l=g[2],f=g[3];try{if(!l)return Response.redirect(new URL("/",e.origin).toString(),302);let a;try{a=await W(l,t)}catch{return new Response("Flow not found",{status:404})}if(!a.metadata||((c=a.metadata)==null?void 0:c.status)!=="active")return new Response("NO chat",{status:404});if(((d=a.metadata)==null?void 0:d.visibility)==="private"&&!await Y(o,t,n)){let y=new URL("/login",e.origin);return y.searchParams.set("nextURL",`${e.pathname}${e.search}`),Response.redirect(y.toString(),302)}if(!f){let m=crypto.randomUUID(),y=new URL(`/a/${l}/${m}`,e.origin);return Response.redirect(y.toString(),302)}if(!on.test(f))return new Response("Id del chat no v\xE1lido",{status:400})}catch(a){return console.error("Error accessing flow KV:",a),new Response("Flow error",{status:500})}}if(e.pathname.startsWith("/api/agent/flow")){let g=e.pathname.split("/"),l=g[4],f=g[5],a=`${l}::${f}`;try{let m=await Y(o,t,n);if(!m){let R=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${R}) \u2014 Composio connections from tool editor will not apply`)}let y=new Headers(o.headers);y.delete("X-User-Payload"),m&&y.set("X-User-Payload",JSON.stringify(m));let w=new Request(o,{headers:y});return(await Ot(t.AGENT,a)).fetch(w)}catch(m){return console.error("Error accessing agent:",m),new Response("Agent error",{status:500})}}if(e.pathname.startsWith("/api/ora/connect")){let g=e.pathname.split("/"),l=g[4],f=g[5];if(!l||!f)return new Response("Missing flowId or sessionId",{status:400});let a=o.headers.get("Authorization")||e.searchParams.get("authorization");if(!a)return new Response("Missing Authorization header",{status:401});try{let m=`${t.HX_CORE_URL}/p/v1/validation/key/agent/${l}`,w=await(await fetch(m,{method:"GET",headers:{Authorization:a}})).json();if(((u=w.payload)==null?void 0:u.flowId)!==l)return console.error("FlowId mismatch:",(p=w.payload)==null?void 0:p.flowId,"!==",l),new Response("Validation error",{status:403});let h=`${l}::${f}`,I=await Y(o,t,n);if(!I){let D=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${D}) \u2014 Composio connections from tool editor will not apply`)}let R=new Headers(o.headers);R.delete("X-User-Payload"),I&&R.set("X-User-Payload",JSON.stringify(I));let x=new Request(o,{headers:R});return(await Ot(t.AGENT,h)).fetch(x)}catch(m){return console.error("Error in /api/ora/connect:",m),new Response("Internal error",{status:500})}}}async function Li(o,t,n){let e=new URL(o.url),s=o.method;if(!e.pathname.startsWith("/api/instances"))return;let r=await Y(o,t,n);if(!r)return new Response("Unauthorized",{status:401});let i=t.HX_CORE_URL,c=t.HX_API_KEY;if(!i||!c)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let u=e.pathname.slice("/api/instances".length);u.startsWith("/")&&(u=u.slice(1)),u.endsWith("/")&&(u=u.slice(0,-1));let p="/ora/instances";u&&(p+=`/${u}`);let g=i.endsWith("/")?i.slice(0,-1):i,l=new URL(`${g}${p}`);e.searchParams.forEach((m,y)=>{l.searchParams.set(y,m)}),s==="GET"&&!u&&l.searchParams.set("filter_user_id",r.email);let f=new Headers;f.set("Authorization",c),f.set("Content-Type","application/json"),f.set("X-User-Payload",JSON.stringify(r));let a={method:s,headers:f};if(["POST","PATCH","PUT"].includes(s))try{a.body=await o.text()}catch(m){console.error("Error reading request body:",m)}try{let m=await fetch(l.toString(),a),y=await m.text();return new Response(y,{status:m.status,headers:{"Content-Type":"application/json"}})}catch(m){return console.error("Error proxying to flow instance backend:",m),new Response("Internal Server Error",{status:500})}}async function qi(o,t,n){let e=new URL(o.url);if(o.method==="POST"&&e.pathname==="/auth/login")try{let s=await o.formData(),r=s.get("username"),i=s.get("password"),c=s.get("nextURL")||"/";if(!r||!i)return new Response("Missing username or password",{status:400});let d=new URLSearchParams;d.append("username",r),d.append("password",i),d.append("grant_type","password"),d.append("client_id",t.KC_CLIENT_ID),d.append("client_secret",t.KC_CLIENT_SECRET);let u=await fetch(`${t.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 p=await u.json(),g=new Response(null,{status:302,headers:{Location:c}}),l=(f,a,m)=>{g.headers.append("Set-Cookie",`${f}=${a}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${m}`)};return p.access_token&&l("access_token",p.access_token,p.expires_in),p.refresh_token&&l("refresh_token",p.refresh_token,p.refresh_expires_in||3600*24*30),p.id_token&&l("id_token",p.id_token,p.expires_in),g}catch(s){return console.error("Auth error:",s),new Response("Internal Server Error",{status:500})}if(e.pathname==="/auth/logout"){let s=new Response(null,{status:302,headers:{Location:"/login"}}),r=i=>{s.headers.append("Set-Cookie",`${i}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return r("access_token"),r("refresh_token"),r("id_token"),s}if(e.pathname.startsWith("/s/")){let s=await Y(o,t,n);if(!s){let r=new URL("/login",e.origin);return r.searchParams.set("nextURL",`${e.pathname}${e.search}`),Response.redirect(r.toString(),302)}return{user:s}}}export{co as ANONYMOUS_RUN_USER_PREFIX,ze as AgentDO,mn as FLOW_INPUT_NAME_RE,Ct as FlowExecutionStoppedError,yn as GENERATION_PARAM_KEYS,hn as GENERATION_PRESETS,gn as MAX_USER_IDENTITY_LENGTH,Kn as MODEL_REGISTRY_SNAPSHOT,v as NodeType,Un as OUT_VAR_NAME_RE,wn as PRESET_PARAM_KEYS,$n as REASONING_EFFORT_LEVELS,fe as TOOL_REGISTRY_SNAPSHOT,Ze as TRIGGER_NONCE_HEADER,Be as TRIGGER_SIGNATURE_HEADER,Ai as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,ve as TRIGGER_TENANT_HEADER,Qe as TRIGGER_TIMESTAMP_HEADER,V as VariableResolutionError,In as applyPresetToOverrides,ee as buildReasoningProviderOptions,En as buildScope,Ci as buildSignedTriggerHeaders,Yt as buildTriggerMessageText,dn as buildUrl,Bo as canonicalUserEmail,rt as claimRun,xt as clearAllContext,wt as clearAllMessages,Tt as completeRun,an as convertTempMessure,Ft as createRun,Te as deleteContextToolsUpToCycle,Rn as deriveParamSupport,We as dispatchTrigger,Gt as embedText,Ae as ensureAgentTables,ao as ensureContextTable,io as ensureMessagesTable,Sn as extractTemplateReferences,jn as findScopedSourceNode,Re as getAllContext,z as getAllMessages,bn as getAncestorNodeIds,Rt as getContext,xe as getContextData,ht as getContextIndex,Mn as getDefaultOutVars,ft as getEffectiveOutVars,tt as getFlowInputDefs,Ne as getMaxContextCycle,Jn as getModelEntry,Ln as getRefTail,et as getUpstreamOutVars,bi as handleAgentsRoutes,qi as handleAuthRoutes,Ri as handleCommonRoutes,Li as handleIntancesRoutes,rn as handlePersistedSessionInspection,sn as handleSessionRunControl,no as handleTriggerRoutes,pn as hashText,at as initializeEngineState,Hn as isBinaryOutVar,pe as jsonSchemaToZod,ot as logc,E as messageTypes,tn as normalizeDestination,Tn as normalizeEffectiveParams,Wt as normalizeFlowInputs,Pn as normalizeModelEntry,kn as normalizeReasoning,An as openAiReasoningParamSupport,Nn as openAiStandardParamSupport,Ge as parseCookies,qn as parseTemplateExpression,Bt as parseUserAuth,dt as parseUserMessage,Qt as pickNodeOverrides,Fn as reasoningEffortLevels,vt as reasoningExposable,Oe as recordRun,Dn as registerProvider,fo as resolveAnswerMappings,Ie as resolveContextRef,ut as resolveModelById,Vn as resolveOutVarRef,xn as resolvePreset,te as resolveReasoningEffort,K as resolveReference,Ce as resolveRunUserId,le as resolveTemplate,Xn as rewriteTemplateNodeRefs,ct as runAgentTurn,ln as safeParseJSON,nt as sanitizeUserIdentity,Se as sendEvent,H as serverSend,he as setContext,we as setMessage,eo as signTriggerMaterial,je as startEngine,_n as stripUnsupportedFromNodeData,cn as tempTool,en as timingSafeEqualHex,Zt as toStreamTextSettings,to as triggerSignatureMaterial,un as twitter,fi as validateFlowStart,ce as validateOutVars,fn as vectorize,Qo as verifyToken,oo as verifyTriggerRequest,Y as verifyUser,mt as walkPath,On as workersAiParamSupport,Cn as xaiParamSupport};
|
|
@@ -40,7 +40,7 @@ export interface SessionEnv {
|
|
|
40
40
|
user?: UserInterface;
|
|
41
41
|
/** Origin derived from the WebSocket upgrade request (preferred over ORA_PUBLIC_URL for callbacks). */
|
|
42
42
|
publicOrigin?: string;
|
|
43
|
-
/** Auditable run currently executing
|
|
43
|
+
/** Auditable run currently executing, including turns from anonymous public sessions. */
|
|
44
44
|
runId?: string;
|
|
45
45
|
/** Turn-local structured output collector. Never persisted in Agent state. */
|
|
46
46
|
outputCollector?: RunOutputCollector;
|
|
@@ -92,8 +92,6 @@ export declare class AgentDO extends Agent<Env, State> {
|
|
|
92
92
|
onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
|
|
93
93
|
onMessage(connection: Connection, message: WSMessage): Promise<void>;
|
|
94
94
|
onUserMessage(connection: Connection, message: string): Promise<void>;
|
|
95
|
-
/** True while the session belongs to a signed-in user; anonymous sessions are not tracked. */
|
|
96
|
-
hasAuditableUser(userId?: string): boolean;
|
|
97
95
|
/** Registers a manual turn as a run so it shows up in history and notifications. */
|
|
98
96
|
registerManualRun(runId: string, text: string, requestUserId?: string): Promise<unknown>;
|
|
99
97
|
/** Closes a manual run once its turn resolved. */
|
|
@@ -24,7 +24,7 @@ export interface AgentTurnOptions {
|
|
|
24
24
|
skillRefCache?: Map<string, string>;
|
|
25
25
|
user?: UserInterface;
|
|
26
26
|
resolveUserId: () => string | undefined;
|
|
27
|
-
/** Existing auditable run id.
|
|
27
|
+
/** Existing auditable run id. Manual and triggered turns both provide one. */
|
|
28
28
|
runId?: string;
|
|
29
29
|
onServerEvent?: (event: FlowEngineEvent) => void | Promise<void>;
|
|
30
30
|
onError?: (error: string) => void;
|
|
@@ -27,6 +27,9 @@ export interface CreateRunInput {
|
|
|
27
27
|
inputs?: FlowInputValues;
|
|
28
28
|
label?: string;
|
|
29
29
|
}
|
|
30
|
+
export declare const ANONYMOUS_RUN_USER_PREFIX = "anonymous:";
|
|
31
|
+
/** D1 requires a run owner even when the public chat session itself is anonymous. */
|
|
32
|
+
export declare function resolveRunUserId(userId: string | null | undefined, sessionId: string): string;
|
|
30
33
|
export declare function createRun(env: Env, input: CreateRunInput): Promise<{
|
|
31
34
|
run: RunRecord;
|
|
32
35
|
created: boolean;
|
package/package.json
CHANGED
package/dist/chunk-ZX5BWOUG.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
var b=(a=>(a.START_NODE="startNode",a.CLASSIFIER_NODE="classifierNode",a.MEMO_NODE="memoNode",a.LLM_NODE="llmNode",a.ANSWER_NODE="answerNode",a.API_NODE="apiNode",a.TOOL_NODE="toolNode",a))(b||{});var R=/^[a-zA-Z][a-zA-Z0-9_]*$/,v=["string","number","boolean","json"];function D(e){let t=e==null?void 0:e.inputs;if(!Array.isArray(t))return[];let u=[],n=new Set;for(let r of t){let s=typeof(r==null?void 0:r.name)=="string"?r.name.trim():"";if(!s||!R.test(s)||n.has(s))continue;n.add(s);let i=v.includes(r==null?void 0:r.type)?r.type:"string";u.push({name:s,label:typeof(r==null?void 0:r.label)=="string"&&r.label.trim()?r.label.trim():void 0,type:i,required:(r==null?void 0:r.required)===!0,default:(r==null?void 0:r.default)??void 0})}return u}function L(e,t){let u=e.label||e.name;switch(e.type){case"number":{let n=typeof t=="number"?t:Number(String(t).trim());return Number.isFinite(n)?{value:n}:{error:`"${u}" must be a number`}}case"boolean":{if(typeof t=="boolean")return{value:t};let n=String(t).trim().toLowerCase();return["true","1","yes","si","s\xED"].includes(n)?{value:!0}:["false","0","no"].includes(n)?{value:!1}:{error:`"${u}" must be true or false`}}case"json":{if(typeof t=="object")return{value:t};try{return{value:JSON.parse(String(t))}}catch{return{error:`"${u}" must be valid JSON`}}}default:return{value:typeof t=="string"?t:String(t)}}}function S(e){return e==null||typeof e=="string"&&e.trim()===""}function C(e,t){let u={},n=[],r=t??{};for(let s of e){let i=r[s.name],a=S(i)?s.default:i;if(S(a)){s.required&&n.push(`"${s.label||s.name}" is required`);continue}let{value:p,error:y}=L(s,a);y?n.push(y):u[s.name]=p}return{values:u,errors:n}}function M(e){return typeof e=="string"?e:e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function J(e,t,u){let n=t.user_input;if(typeof n=="string"&&n.trim())return n;let r=e.filter(i=>i.name!=="user_input"&&t[i.name]!==void 0).map(i=>`- ${i.label||i.name}: ${M(t[i.name])}`),s=(u==null?void 0:u.trim())||"Automated execution";return r.length>0?`${s}
|
|
2
|
-
${r.join(`
|
|
3
|
-
`)}`:s}function F(e,t){if(!t)return e;if(e==null)return;let u=t.split("."),n=e;for(let r of u){if(n==null)return;n=n[r]}return n}function P(e){switch(e){case"startNode":return[{name:"user_input",path:"user_input",label:"User input",source:"default"},{name:"images",path:"images",label:"User images",type:"image",source:"default"},{name:"files",path:"files",label:"User docs",type:"file",source:"default"}];case"llmNode":return[{name:"output",path:"",label:"LLM text",source:"default"}];case"apiNode":return[{name:"ok",path:"ok",source:"default"},{name:"status",path:"status",source:"default"},{name:"data",path:"data",source:"default"}];case"toolNode":return[{name:"ok",path:"ok",source:"default"},{name:"data",path:"data",source:"default"},{name:"error",path:"error",source:"default"}];case"classifierNode":return[{name:"classification",path:"classification",source:"default"}];case"memoNode":return[{name:"context",path:"",label:"Retrieved context",source:"default"}];case"answerNode":return[];default:return[]}}function $(e){return e.type!=="startNode"?[]:D(e.data).map(t=>({name:t.name,path:t.name,label:t.label,type:t.type==="json"?"object":t.type,source:"default"}))}function V(e){var r;let t=P(e.type),u=((r=e.data)==null?void 0:r.outVars)||[],n=[...t,...$(e).filter(s=>!t.some(i=>i.name===s.name))];for(let s of u){let i=n.findIndex(a=>a.name===s.name);i>=0?n[i]={...s,source:"user"}:n.push({...s,source:"user"})}return n}function j(e,t){var c,N,l,g,O,o,f;if(e==="user_input")return(c=t.context)==null?void 0:c.user_input;if(e==="images")return(N=t.context)==null?void 0:N.user_images;if(e==="classified_id")return(l=t.context)==null?void 0:l.classified_id;if(e==="files"||e==="file_content")return((g=t.context)==null?void 0:g.files)||((O=t.context)==null?void 0:O.file_content);let u=e.indexOf(".");if(u===-1)return t.nodes.find(x=>x.id===e)?(o=t.results)==null?void 0:o[e]:Object.prototype.hasOwnProperty.call(t.context??{},e)?t.context[e]:void 0;let n=e.substring(0,u),r=e.substring(u+1),s=t.nodes.find(d=>d.id===n);if(!s)return;let i=V(s),a=r.split(".")[0],p=i.find(d=>d.name===a);if(!p)return;let y=(f=t.results)==null?void 0:f[n],m=F(y,p.path??"");if((m==null||m==="")&&s.type==="startNode"){let d=p.path||p.name;d&&Object.prototype.hasOwnProperty.call(t.context??{},d)&&(m=t.context[d])}let E=r.substring(a.length+1);return E?F(m,E):m}var T="\0__ORA_OB__\0",w="\0__ORA_CB__\0";function q(e,t,u,n){var m,E;if(!e)return e;let r=(n==null?void 0:n.serializeNonStrings)??!1,s=e.replace(/\\\{\{/g,T).replace(/\\\}\}/g,w),i={...u.context||{}};if((m=t.data)!=null&&m.varMapping&&Array.isArray(t.data.varMapping))for(let c of t.data.varMapping){let N=c.var||c.to,l=c.from;if(N&&l){let g=!1,O=!1;if(l==="images")g=!0;else if(l==="files"||l==="file_content")O=!0;else{let f=l.indexOf(".");if(f!==-1){let d=l.substring(0,f),x=l.substring(f+1).split(".")[0],I=u.nodes.find(h=>h.id===d);if(I){let _=V(I).find(A=>A.name===x);(_==null?void 0:_.type)==="image"&&(g=!0),(_==null?void 0:_.type)==="file"&&(O=!0)}}}if(g||O)continue;let o=j(l,u);(o==null||o==="")&&(o=c.default??""),i[N]=o}}let a=/\{\{\s*([^}]+?)\s*\}\}/g,p=c=>r?JSON.stringify(c).slice(1,-1):c;s=s.replace(a,(c,N)=>{var g,O;let l=N.trim();if(l.startsWith("secrets.")){let o=l.slice(8);return u.secrets?Object.prototype.hasOwnProperty.call(u.secrets,o)?p(u.secrets[o]):((O=n==null?void 0:n.onError)==null||O.call(n,`Secret "${o}" is not defined for this tenant`),c):((g=n==null?void 0:n.onError)==null||g.call(n,`Secret reference {{ ${l} }} cannot be resolved (no secrets context)`),c)}if(Object.prototype.hasOwnProperty.call(i,l)){let o=i[l],f;return typeof o=="string"?f=p(o):typeof o=="object"&&o!==null?f=r?JSON.stringify(o):JSON.stringify(o,null,2):o!=null?f=r?JSON.stringify(o):String(o):f="",f}return c});let y=s.match(/\{\{\s*[^}]+\s*\}\}/g);return y&&((E=n==null?void 0:n.onError)==null||E.call(n,`Mismatch detected: Unmatched placeholders found: ${y}`)),s=s.split(T).join("{{").split(w).join("}}"),s}export{b as a,R as b,D as c,C as d,J as e,F as f,P as g,V as h,j as i,q as j};
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
export interface FlowNode {
|
|
2
|
-
id: string;
|
|
3
|
-
type: string;
|
|
4
|
-
data?: any;
|
|
5
|
-
}
|
|
6
|
-
export interface VariableMapping {
|
|
7
|
-
var: string;
|
|
8
|
-
from: string;
|
|
9
|
-
default?: string;
|
|
10
|
-
}
|
|
11
|
-
export interface OutVar {
|
|
12
|
-
name: string;
|
|
13
|
-
path?: string;
|
|
14
|
-
label?: string;
|
|
15
|
-
description?: string;
|
|
16
|
-
type?: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'image' | 'file';
|
|
17
|
-
source?: 'default' | 'user';
|
|
18
|
-
}
|
|
19
|
-
export interface ResolveInput {
|
|
20
|
-
context: Record<string, any>;
|
|
21
|
-
results: Record<string, any>;
|
|
22
|
-
nodes: FlowNode[];
|
|
23
|
-
secrets?: Record<string, string>;
|
|
24
|
-
}
|
|
25
|
-
export interface ResolveOptions {
|
|
26
|
-
callerTag?: string;
|
|
27
|
-
serializeNonStrings?: boolean;
|
|
28
|
-
onError?: (msg: string) => void;
|
|
29
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as a,e as b}from"./chunk-YJQNSODK.js";import"./chunk-ZX5BWOUG.js";import"./chunk-V6JSMX5A.js";import"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{a as customHttpTool,b as default};
|
|
File without changes
|