@hugex/ai 2.9.17 → 2.9.20
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-A2IRPAD4.js +1 -0
- package/dist/chunk-ELMOSEQ7.js +1 -0
- package/dist/chunk-K4MP63XM.js +3 -0
- package/dist/chunk-MOYYZBTC.js +1 -0
- package/dist/chunk-OF6G42DM.js +1 -0
- package/dist/{chunk-RRS7SUF3.js → chunk-UBNZUUTD.js} +1 -1
- package/dist/{chunk-4FUIFBZO.js → chunk-W6DBEVOO.js} +1 -1
- package/dist/client.js +1 -1
- package/dist/common/types/node-types.d.ts +3 -2
- package/dist/common/types/user-types.d.ts +1 -0
- 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/composioDirectTool-H3GSCIPY.js +1 -0
- package/dist/composioTool-5LFWUQ7F.js +1 -0
- package/dist/httpTool-LSNJKMPR.js +1 -0
- package/dist/index.js +18 -18
- package/dist/oraApi-4O3W5LXD.js +1 -0
- package/dist/server/core/AgentDO.d.ts +10 -4
- package/dist/server/core/agentTurn.d.ts +1 -1
- package/dist/server/runners/toolNodeRunner.d.ts +4 -0
- package/dist/server/tools/composioDirectTool.d.ts +15 -0
- package/dist/server/types/node.d.ts +1 -0
- package/dist/server/utils/flowAccess.d.ts +6 -0
- package/dist/server/utils/oraApi.d.ts +8 -0
- package/dist/server/utils/oraTriggers.d.ts +3 -0
- package/dist/{skillTool-BSQFKZGK.js → skillTool-PLHCAODG.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-4WAWR4LB.js +0 -1
- package/dist/chunk-TGWG3SEO.js +0 -3
- package/dist/chunk-YHXUBVN2.js +0 -1
- package/dist/common/types/var-mapping.d.ts +0 -29
- package/dist/composioTool-44B637WM.js +0 -1
- package/dist/httpTool-MRMZWSXQ.js +0 -1
- package/dist/oraApi-YIJGMXX7.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 @@
|
|
|
1
|
+
async function s(o){let t=await fetch(`${o.HX_ORA_URL}/internal/tools`,{method:"GET",headers:{Authorization:`${o.HX_API_KEY}`},cache:"no-store"});if(!t.ok)throw new Error("Failed to fetch tool defs");return(await t.json()).tools??[]}async function a(o){let t=await fetch(`${o.HX_ORA_URL}/internal/tool-catalog`,{method:"GET",headers:{Authorization:`${o.HX_API_KEY}`},cache:"no-store"});if(!t.ok)throw new Error("Failed to fetch tool catalog");return(await t.json()).entries??[]}async function i(o,t){let n=await fetch(`${t.HX_ORA_URL}/internal/models/${o}`,{method:"GET",headers:{Authorization:`${t.HX_API_KEY}`},cache:"no-store"});if(!n.ok)throw new Error(`Failed to fetch model ${o} from registry`);return(await n.json()).model}async function c(o,t,n){let e=await fetch(`${o.HX_ORA_URL}/internal/tools/${t}/refs/${encodeURIComponent(n)}`,{method:"GET",headers:{Authorization:`${o.HX_API_KEY}`},cache:"no-store"});if(!e.ok)throw e.status===404?new Error(`Reference "${n}" not found`):new Error(`Failed to fetch skill reference "${n}"`);let r=await e.json();if(!r.ref)throw new Error(`Reference "${n}" not found in response`);return r.ref}export{s as a,a as b,i as c,c as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as t,c as i,j as s}from"./chunk-MOYYZBTC.js";import{Composio as m}from"@composio/core";function c(r){return typeof r!="string"?void 0:r.trim()||void 0}async function k(r,e){let l=i(r),u=new m({apiKey:l}),a=t(e.connectionScope),n=c(e.toolVersion)??c(e.toolkitVersion);try{n||console.warn(`[composioDirectTool] No toolVersion/toolkitVersion for ${e.toolSlug}; executing with dangerouslySkipVersionCheck`);let o=await u.tools.execute(e.toolSlug,{userId:a,arguments:e.arguments,...n?{version:n}:{dangerouslySkipVersionCheck:!0}});return o&&typeof o=="object"&&"successful"in o&&o.successful===!1?{ok:!1,data:null,error:typeof o.error=="string"&&o.error.trim()?o.error:"Tool execution failed"}:{ok:!0,data:o&&typeof o=="object"&&"data"in o?o.data:o,error:null}}catch(o){return s(o)?{ok:!1,error:"This connector is not connected. Ask a tenant admin to connect it in Tools."}:{ok:!1,error:o instanceof Error?o.message:String(o)}}}export{k as a};
|
|
@@ -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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SessionPreset as g}from"@composio/core";function U(n,o){var t;return(o==null?void 0:o.trim())||((t=n.connectionScope)==null?void 0:t.trim())||void 0}function R(n){let o=n.trim();if(!o)throw new Error("Composio connection scope is required");return o}var m=/https:\/\/connect\.composio\.dev\/link\/[^\s)\]"']+/i,C=/"redirect_?[Uu]rl"\s*:\s*"(https?:\/\/[^"]+)"/;function b(n){var t;let o=(t=n.publicOrigin)==null?void 0:t.trim();return o?o.replace(/\/$/,""):O(n.env)}function v(n){var e,s,i,r;let o=(s=(e=n.secrets)==null?void 0:e.COMPOSIO_API_KEY)==null?void 0:s.trim();if(o)return o;let t=(r=(i=n.env)==null?void 0:i.COMPOSIO_API_KEY)==null?void 0:r.trim();if(t)return t;throw new Error("COMPOSIO_API_KEY is not configured (register tenant secret or set env COMPOSIO_API_KEY)")}function k(n){if(!n)return[];let o=[];for(let t of Object.values(n))o.push(...a(t.enable));return[...new Set(o)].sort()}function A(n){return JSON.stringify({toolkits:n.toolkits,tools:n.tools,authMode:n.authMode,authConfigs:n.authConfigs,workbench:n.workbench,sessionPreset:n.sessionPreset,sessionPreload:n.sessionPreload})}function L(n,o){var s;let t=E(n.tools),e=n.sessionPreset==="direct_tools";return{toolkits:n.toolkits,...n.authConfigs?{authConfigs:n.authConfigs}:{},...t?{tools:t}:{},manageConnections:o.manageConnections,workbench:o.workbench,...e?{sessionPreset:g.DIRECT_TOOLS}:{},...!e&&((s=n.sessionPreload)!=null&&s.enabled)?(()=>{let i=k(n.tools);return i.length>0?{preload:{tools:i}}:{}})():{}}}function h(n,o){var e;let t=(e=n==null?void 0:n.context)==null?void 0:e.user;return t!=null&&t.email||t!=null&&t.id?t:o.user}function j(n,o,t){var r,c,l;let e=h(o,n),s=(r=e==null?void 0:e.email)==null?void 0:r.trim();if(s&&s!=="default")return s;if((t==null?void 0:t.allowChatIdFallback)===!1)throw new Error("Composio user ID unavailable \u2014 log in so your tool-editor connections apply to your email");let i=(l=(c=o==null?void 0:o.flowData)==null?void 0:c.chatId)==null?void 0:l.trim();if(i&&i!=="default")return i;throw new Error("Composio user ID unavailable \u2014 log in (access_token cookie) or provide a chat session id")}function y(n){let o=JSON.stringify(n);return(typeof btoa=="function"?btoa(o):Buffer.from(o,"utf8").toString("base64")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function O(n){var t;let o=(t=n==null?void 0:n.ORA_PUBLIC_URL)==null?void 0:t.trim();return o?o.replace(/\/$/,""):"http://localhost:5173"}function x(n,o,t,e){let s=b(n),i=y({flowId:o??"",sessionId:t??"",toolRowId:e});return`${s}/api/composio/callback?ctx=${encodeURIComponent(i)}`}function a(n){return Array.isArray(n)?n.filter(o=>typeof o=="string"&&!!o.trim()).map(o=>o.trim()):[]}function S(n,o){var i;let t=n.toUpperCase(),e=(i=t.split("_")[0])==null?void 0:i.toLowerCase();if(!e)return;let s=o.find(r=>r.toLowerCase()===e);return s||o.find(r=>t.startsWith(`${r.toUpperCase()}_`))}function w(n,o){let t={};for(let e of n){let s=S(e,o);s&&(t[s]||(t[s]=[]),t[s].push(e))}return Object.fromEntries(Object.entries(t).map(([e,s])=>[e,{enable:s}]))}function E(n){if(!n)return;let o={};for(let[t,e]of Object.entries(n)){let s=a(e.enable),i=a(e.disable);s.length?o[t]={enable:s}:i.length&&(o[t]={disable:i})}return Object.keys(o).length>0?o:void 0}function _(n,o,t){let e=new Set(o.map(c=>c.trim()).filter(Boolean)),s={};if(n&&typeof n=="object")for(let[c,l]of Object.entries(n)){if(!e.has(c)||!l||typeof l!="object")continue;let p=l,u=a(p.enable),f=a(p.disable);u.length===0&&f.length===0||(s[c]={...u.length?{enable:u}:{},...f.length?{disable:f}:{}})}if(Object.keys(s).length>0)return s;let i=a(t==null?void 0:t.tools);if(i.length===0)return;let r=w(i,o);return Object.keys(r).length>0?r:void 0}function M(n){var c;let o=n&&typeof n=="object"?n:{},t=Array.isArray(o.toolkits)?o.toolkits.filter(l=>typeof l=="string"&&l.trim()):[];if(t.length===0)throw new Error("Composio tool execution.toolkits must be a non-empty string array");let e=_(o.tools,t,o.preload),s=typeof o.connectionScope=="string"&&o.connectionScope.trim()?o.connectionScope.trim():void 0,i=o.sessionPreset==="direct_tools"?"direct_tools":void 0,r=((c=o.sessionPreload)==null?void 0:c.enabled)===!0?{enabled:!0}:void 0;return{toolkits:t,authMode:o.authMode==="manual"?"manual":"in_app",authConfigs:o.authConfigs,...s?{connectionScope:s}:{},...e?{tools:e}:{},manageConnections:o.manageConnections,workbench:o.workbench??{enable:!0},...i?{sessionPreset:i}:{},...r?{sessionPreload:r}:{}}}function F(n,o){var e,s;return n.authMode==="manual"?!1:{callbackUrl:((s=(e=n.manageConnections)==null?void 0:e.callbackUrl)==null?void 0:s.trim())||o}}function K(n){let o=String((n==null?void 0:n.message)??n??"").toLowerCase();return o.includes("not connected")||o.includes("not authenticated")||o.includes("connection required")||o.includes("no active connection")||o.includes("authorize")||o.includes("authentication")||o.includes("connect link")||o.includes("no connected account")||o.includes("composio_manage_connections")}function T(n){if(typeof n!="string")return;let o=n.trim();if(o.startsWith("http"))return o}function I(n){for(let o of["redirectUrl","redirect_url","composio_link_redirect_url","url","link"]){let t=T(n[o]);if(t)return d(t)??t}}function d(n){if(n&&typeof n=="object"&&!Array.isArray(n)){let e=I(n);return e||d(JSON.stringify(n))}if(typeof n!="string")return;let o=n.match(m);if(o!=null&&o[0])return o[0];let t=n.match(C);if(t!=null&&t[1]){let e=t[1].replace(/\\u0026/g,"&").replace(/\\\//g,"/");return d(e)??e}}function N(n,o){var t;if(typeof n=="string"){let e=n.toLowerCase();for(let s of(o==null?void 0:o.toolkits)??[])if(e.includes(s.toLowerCase()))return s}return(t=o==null?void 0:o.toolkits)==null?void 0:t[0]}export{U as a,R as b,v as c,A as d,L as e,j as f,x as g,M as h,F as i,K as j,d as k,N as l};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as F,b as S,c as v,d as U,e as P,f as K,g as N,h as O,i as M,j,k as g,l as h}from"./chunk-MOYYZBTC.js";import{Composio as L}from"@composio/core";import{VercelProvider as B}from"@composio/vercel";function w(o,n,i,s,t){let r=s?g(s)??s.trim():void 0;!r||!r.startsWith("http")||o==null||o({type:"info:composio:auth_required",content:{toolkit:t,redirectUrl:r,toolRowId:n.id}})}function q(o){let n=g(o);if(n)return n;if(typeof o=="string")return g(o);try{return g(JSON.stringify(o))}catch{return}}async function W(o,n,i,s,t,r=!0){var e;let l=await o.toolkits({toolkits:n.toolkits});for(let u of l.items)if(!(u.isNoAuth||(e=u.connection)!=null&&e.isActive))try{let p=await o.authorize(u.slug,{callbackUrl:i});r&&w(t,s,n,p.redirectUrl,u.slug);break}catch(p){`${u.slug}${String(p)}`}}function H(o,n,i,s,t=!0){let r={};for(let[l,e]of Object.entries(o)){if(!e||typeof e!="object"||typeof e.execute!="function"){r[l]=e;continue}let u=e.execute.bind(e);r[l]={...e,execute:async(...p)=>{try{let c=await u(...p);if(t){let m=q(c);m&&w(s,n,i,m,h(String(c),i))}return c}catch(c){if(j(c)){let m=q(c);w(s,n,i,m,h(String(c),i))}throw c}}}}return r}async function X(o,n,i,s){var R,$,I,A,T,E;if(o.kind!=="composio")throw new Error(`loadComposioTools: unsupported kind '${o.kind}' for tool '${o.name}'`);let t=O(o.execution),r=v(n),l=t.authMode==="manual",e;if(l){let a=F(t,o.id);if(!a)throw new Error(`Composio manual tool '${o.name}' is missing connection scope (tool id or execution.connectionScope)`);e=S(a)}else e=K(n,i,{allowChatIdFallback:!0});let u=(R=i.flowData)==null?void 0:R.flowId,p=($=i.flowData)==null?void 0:$.chatId,c=((I=t.manageConnections)==null?void 0:I.callbackUrl)||N(n,u,p,o.id),m=M(t,c),C=new L({apiKey:r,provider:new B});n.composioSessions||(n.composioSessions={});let b=U(t),z=l?!1:((A=t.workbench)==null?void 0:A.enable)!==!1,d,f=n.composioSessions[o.id];f!=null&&f.sessionId&&f.userId===e&&f.configKey===b?(d=await C.use(f.sessionId),`${f.sessionId}${o.name}${e}`,void 0):(d=await C.create(e,P(t,{manageConnections:m,workbench:{enable:z}})),n.composioSessions[o.id]={sessionId:d.sessionId,userId:e,configKey:b},`${d.sessionId}${o.name}${e}${t.authMode}${t.sessionPreset??"default"}`,(T=t.sessionPreload)!=null&&T.enabled,void 0);try{let a=await d.toolkits({toolkits:t.toolkits});for(let k of a.items){let x=!!(k.isNoAuth||(E=k.connection)!=null&&E.isActive);`${k.slug}${x}${e}`}await W(d,t,c,o,s,!l)}catch(a){`${o.name}${String(a)}`}let y=await d.tools(),D=Array.isArray(y)?Object.fromEntries(y.map(a=>[a.name??a.toolName,a])):y;return H(D,o,t,s,!l)}export{X as a};
|
|
@@ -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};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{d as g}from"./chunk-A2IRPAD4.js";import{tool as k}from"ai";import{z as m}from"zod";function R(e,c){if(c.length===0)return;let u=c.map(t=>`- "${t.name}"${t.description?` \u2014 applies when: ${t.description}`:""}`);return`MANDATORY REFERENCE CHECK. This skill has reference documents, each listed below with the condition under which it applies. On EVERY turn, BEFORE you answer, evaluate whether the user's message \u2014 or the reply you are about to give \u2014 matches any condition. If it does, you MUST first call \`readSkillRef({ skill: "${e}", ref: "<name>" })\`, read the document, and follow it in your response. Never guess, summarize, or apply a reference you have not loaded this turn.
|
|
2
2
|
|
|
3
3
|
References:
|
|
4
4
|
${u.join(`
|
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};
|
|
@@ -4,6 +4,7 @@ export declare enum NodeType {
|
|
|
4
4
|
MEMO_NODE = "memoNode",
|
|
5
5
|
LLM_NODE = "llmNode",
|
|
6
6
|
ANSWER_NODE = "answerNode",
|
|
7
|
-
API_NODE = "apiNode"
|
|
7
|
+
API_NODE = "apiNode",
|
|
8
|
+
TOOL_NODE = "toolNode"
|
|
8
9
|
}
|
|
9
|
-
export type NODETYPES = NodeType.START_NODE | NodeType.CLASSIFIER_NODE | NodeType.MEMO_NODE | NodeType.LLM_NODE | NodeType.ANSWER_NODE | NodeType.API_NODE;
|
|
10
|
+
export type NODETYPES = NodeType.START_NODE | NodeType.CLASSIFIER_NODE | NodeType.MEMO_NODE | NodeType.LLM_NODE | NodeType.ANSWER_NODE | NodeType.API_NODE | NodeType.TOOL_NODE;
|
|
@@ -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{a}from"./chunk-ELMOSEQ7.js";import"./chunk-MOYYZBTC.js";import"./chunk-3TXHFKDN.js";export{a as executeComposioCatalogTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-OF6G42DM.js";import"./chunk-MOYYZBTC.js";import"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{a as loadComposioTools};
|
|
@@ -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 fe}from"./chunk-ELMOSEQ7.js";import{a as B,b as st,c as me,d as yt}from"./chunk-UBNZUUTD.js";import{a as ye}from"./chunk-OF6G42DM.js";import"./chunk-MOYYZBTC.js";import{a as we,b as he}from"./chunk-W6DBEVOO.js";import{a as Pn,b as ut,c as Un,d as pt,e as $t,f as se,g as re,h as ie,i as ae,j as ce,k as kt,l as le}from"./chunk-57TCP6J4.js";import{a as M,b as dt,c as yn,d as nt,e as Zt,f as ge,g as Jn,h as zn}from"./chunk-E7BCWUTG.js";import{a as v,b as gn,c as tt,d as Bt,e as Qt,f as bn,g as Mn,h as de,i as ft,j as En,k as et,l as jn,m as Ln,n as Hn,o as Sn,p as S,q as mt,r as K,s as Vn,t as qn,u as Xn,v as Kn,w as ue}from"./chunk-K4MP63XM.js";import{a as wn,b as hn,c as Rn,d as xn,e as In,f as Tn,g as vt,h as Nn,i as te,j as An,k as Cn,l as On,m as _n,n as $n,o as kn,p as Fn,q as Dn,r as ee,s as oe,t as ne}from"./chunk-GRZ6ZRHM.js";import{a as cn}from"./chunk-RYHQGPX5.js";import{a as ln}from"./chunk-R6EKV3WR.js";import{a as pn}from"./chunk-6HY7QUMP.js";import{a as dn,b as un}from"./chunk-V6JSMX5A.js";import{a as W,b as Z,c as fn,d as Yt,e as mn}from"./chunk-G3SGJ7XJ.js";import{a as ot}from"./chunk-U56YWPSI.js";import{a as gt,b as pe}from"./chunk-A2IRPAD4.js";import{a as lt}from"./chunk-3TXHFKDN.js";import{Agent as Ge}from"agents";import{nanoid as Go}from"nanoid";var L=(o,t,n)=>{o.send(t+"::"+n)};async function co(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 Re(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 lo(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,37 +6,37 @@ import{a as et,b as Tt,c as se,d as ne}from"./chunk-RRS7SUF3.js";import{a as ie,
|
|
|
6
6
|
cycle INTEGER NOT NULL,
|
|
7
7
|
meta TEXT,
|
|
8
8
|
ts INTEGER NOT NULL
|
|
9
|
-
)`}async function
|
|
10
|
-
VALUES (${
|
|
9
|
+
)`}async function xe(o,t){let n=t.data??null,e=n!=null?ie(n):{data:null,truncated:!1},s=e.truncated?le(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
|
+
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,
|
|
13
13
|
description = excluded.description,
|
|
14
14
|
data = excluded.data,
|
|
15
15
|
cycle = excluded.cycle,
|
|
16
16
|
meta = excluded.meta,
|
|
17
|
-
ts = excluded.ts`}async function pt(o){return o.sql`SELECT ref, domain, description, cycle, meta, ts FROM context ORDER BY ts ASC`}async function de(o){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context ORDER BY ts ASC`}async function ft(o,e){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${e} LIMIT 1`[0]??null}async function ue(o,e){var t;return((t=o.sql`SELECT data FROM context WHERE ref = ${e} LIMIT 1`[0])==null?void 0:t.data)??null}async function pe(o,e){let s=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${e} LIMIT 1`;if(s[0])return s[0];let t=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref LIKE ${e+"%"} LIMIT 2`;return t.length===1?t[0]:null}async function fe(o,e){o.sql`DELETE FROM context WHERE domain = 'tool' AND cycle <= ${e}`}async function me(o){var s;return((s=o.sql`SELECT COALESCE(MAX(cycle), 0) AS maxCycle FROM context`[0])==null?void 0:s.maxCycle)??0}async function mt(o){o.sql`DELETE FROM context`}async function ge(o){await Ye(o),await Be(o)}function Nt(o){return{"Content-Type":"application/json",Authorization:o.HX_API_KEY}}function gt(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function Ct(o,e){if(!gt(o))return null;let s=await fetch(`${o.HX_ORA_URL}/internal/runs`,{method:"POST",headers:Nt(o),body:JSON.stringify(e)});return s.ok?await s.json():(console.error("[oraTriggers] createRun failed",s.status,await s.text().catch(()=>"")),null)}async function ot(o,e){if(!gt(o))return{claimed:!0};let s=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/claim`,{method:"POST",headers:Nt(o)});if(!s.ok){let t=await s.text().catch(()=>"");throw new Error(`claimRun ${e} failed with ${s.status}: ${t}`)}return await s.json()}async function yt(o,e,s,t=3){if(!gt(o))return!0;for(let n=1;n<=t;n++){try{let r=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/complete`,{method:"POST",headers:Nt(o),body:JSON.stringify(s)});if(r.ok||r.status===409)return!0;if(r.status===404)return console.error(`[oraTriggers] completeRun ${e} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${e} attempt ${n} failed with ${r.status}`)}catch(r){console.warn(`[oraTriggers] completeRun ${e} attempt ${n} threw`,r)}n<t&&await new Promise(r=>setTimeout(r,250*n))}return console.error(`[oraTriggers] completeRun ${e} exhausted ${t} attempts; hx-ora will time the run out`),!1}async function ye(o,e){if(!gt(o))return Promise.resolve();try{return await Ct(o,e)}catch(s){return console.error("[oraTriggers] recordRun failed",s),null}}var At=Object.freeze({}),Qe="__SYSTEM_";function we(o){return o.startsWith(Qe)}function Ze(o){let e={};for(let[s,t]of Object.entries(o))we(s)||(e[s]=t);return Object.freeze(e)}async function wt(o,e){if(!e)return At;if(o.HX_ORA_URL&&o.HX_API_KEY)try{let n=await fetch(`${o.HX_ORA_URL}/internal/secrets`,{headers:{Authorization:o.HX_API_KEY}});if(n.ok){let r=await n.json();if(r.secrets)return Ze(r.secrets)}else console.warn(`[secrets] API failed with status ${n.status}, falling back to KV`)}catch(n){console.error("[secrets] API request failed, falling back to KV",n)}let s=o.ORA_SECRETS;if(!s)return At;let t=`${e}:`;try{let n=await s.list({prefix:t,limit:1e3});n.list_complete===!1&&console.warn(`[secrets] tenant=${e} exceeded list page; truncating to first 1000 keys`);let r=n.keys.filter(d=>!we(d.name.slice(t.length))),i=await Promise.all(r.map(async d=>{let f=await s.get(d.name);return f!==null?[d.name.slice(t.length),f]:null})),l={};for(let d of i){if(!d)continue;let[f,u]=d;f&&(l[f]=u)}return Object.freeze(l)}catch(n){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,err:n}),At}}import{nanoid as ws}from"nanoid";function st(o){var n,r;let e=(n=o==null?void 0:o.flowData)==null?void 0:n.state,t=((e==null?void 0:e.nodes)??((r=o==null?void 0:o.flowData)==null?void 0:r.nodes)??[]).find(i=>i.type==="startNode");return t==null?void 0:t.data}async function he(o,e){return typeof e.cycle=="number"&&Number.isFinite(e.cycle)?e.cycle+1:await me(o)+1}function Re(o,e,s,t,n){let r=dt(st(s));return{...e,memoryConfig:r,cycle:t,setContext:async l=>{await le(o,l),await(n==null?void 0:n(l.ref))},getContextIndex:async()=>pt(o),getContextData:async l=>ue(o,l),getContext:async l=>ft(o,l),resolveContext:async l=>pe(o,l),pruneContext:async l=>fe(o,l)}}import{nanoid as ho}from"nanoid";async function xe(o,e){return o.length?!e||!e.HX_ORA_URL||!e.HX_API_KEY?(console.error("extractDocuments: missing HX_ORA_URL or HX_API_KEY"),o.map(t=>({name:t.name,text:""}))):await Promise.all(o.map(async t=>{try{let n=await fetch(`${e.HX_ORA_URL}/internal/files/extract`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e.HX_API_KEY},body:JSON.stringify(t)});if(!n.ok)return console.error(`extractDocuments: ${t.name} failed ${n.status}`),{name:t.name,text:""};let r=await n.json();return{name:t.name,text:r.text||""}}catch(n){return console.error(`extractDocuments: ${t.name} threw`,n),{name:t.name,text:""}}})):[]}function ve(o,e){if(o==="images"||o==="files"||o==="file_content")return!0;let s=o.indexOf(".");if(s===-1)return!1;let t=e.find(i=>i.id===o.slice(0,s));if(!t)return!1;let n=o.slice(s+1).split(".")[0],r=G(t).find(i=>i.name===n);return(r==null?void 0:r.type)==="image"||(r==null?void 0:r.type)==="file"}function to(o,e){var i,l,d,f,u;let s=Array.isArray((i=o.data)==null?void 0:i.varMapping)?o.data.varMapping:[];if(s.length===0)return null;let t=((d=(l=e.flowData)==null?void 0:l.state)==null?void 0:d.nodes)||[],n={},r=new Set;for(let p of s){let c=(f=p.var)==null?void 0:f.trim(),m=(u=p.from)==null?void 0:u.trim();if(!c||!m)throw new Error(`Answer node ${o.id} has an incomplete variable mapping`);if(r.has(c))throw new Error(`Answer node ${o.id} has duplicate output key "${c}"`);if(ve(m,t))throw new Error(`Answer node ${o.id} cannot persist binary source "${m}"`);let a=v(m,{context:e.context||{},results:e.results||{},nodes:t});(a==null||a==="")&&(a=p.default??""),n[c]=a,r.add(c)}try{JSON.stringify(n)}catch{throw new Error(`Answer node ${o.id} produced a value that is not JSON serializable`)}return n}async function Ot(o,e,s,t,n,r,i){var d,f,u;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let l;try{l=to(e,s)}catch(p){throw t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(p)}}),p}l&&o.outputCollector&&o.outputCollector.add(e.id,l);try{let p=await((d=o.getMessages)==null?void 0:d.call(o))??[],c=((f=p[p.length-1])==null?void 0:f.type)==="text"?p[p.length-1].content:"NO-TEXT";i==null||i({type:"answer_node",payload:{userMessage:(u=s==null?void 0:s.context)==null?void 0:u.user_input,answer:c}})}catch(p){console.error("answerNodeRunner: failed to emit answer telemetry:",p),t==null||t({type:"debug",content:"Warning: failed to emit answer telemetry"})}n==null||n(e.id,{type:"answerNode",message:"Answer response for: "+e.data.response,saved:!0,persistenceRequested:!!l&&!!o.outputCollector,persisted:!1,...o.runId?{runId:o.runId}:{}}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}function W(o,e,s,t,n){var l,d,f;let r=(n==null?void 0:n.callerTag)??"llmNodeRunner",i=(n==null?void 0:n.serializeNonStrings)??!1;try{return te(o,e,{context:s.context??{},results:s.results??{},nodes:((d=(l=s.flowData)==null?void 0:l.state)==null?void 0:d.nodes)??[],secrets:(f=n==null?void 0:n.sessionEnv)==null?void 0:f.secrets},{callerTag:r,serializeNonStrings:i,onError:u=>{t==null||t({type:`error:${r}`,content:u})}})}catch(u){return console.error(u),"error"}}var _t="[redacted]",Ie=8*1024;function eo(o){if(o==null)return{value:o,truncated:!1};let e=typeof o=="string"?o:JSON.stringify(o),s=new TextEncoder().encode(e);if(s.byteLength<=Ie){if(typeof o=="string")return{value:o,truncated:!1};try{return{value:JSON.parse(e),truncated:!1}}catch{return{value:e,truncated:!1}}}let t=s.slice(0,Ie);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(t),truncated:!0}}function oo(o,e){let s={};for(let t of G(o))s[t.name]=vt(e,t.path??"");return s}var $t=(o,e,s,t,n)=>W(o,e,s,n,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function Pt(o,e,s,t,n,r,i){var f,u,p,c,m,a;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let l=null,d=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(s.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(s.results||{}));let g=((f=e.data)==null?void 0:f.url)||"",y=$t(g,e,s,o,t);if(console.log("[apiNodeRunner] resolved url:",et(g)?Tt(y):y),!y){t==null||t({type:"error:apiNodeRunner",content:"Missing url"}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:"Missing url"}}),n==null||n(e.id,l);return}let h=(((u=e.data)==null?void 0:u.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",h);let w=((p=e.data)==null?void 0:p.headers)||{},x={},R={};for(let E in w)if(Object.prototype.hasOwnProperty.call(w,E)){let J=String(w[E]??"");R[E]=et(J),x[E]=$t(J,e,s,o,t)}let T,P=!1;if(h!=="GET"&&h!=="HEAD"&&((c=e.data)==null?void 0:c.body)!==void 0){let E=typeof e.data.body=="string"?e.data.body:JSON.stringify(e.data.body);P=et(E),T=$t(E,e,s,o,t),!x["Content-Type"]&&!x["content-type"]&&(x["Content-Type"]="application/json")}let A={};for(let E in x)A[E]=R[E]?_t:x[E];console.log("[apiNodeRunner] headers:",JSON.stringify(A)),console.log("[apiNodeRunner] body:",P?_t:T),t==null||t({type:"info:apiNodeRunner:request",content:{nodeId:e.id,method:h,url:et(g)?Tt(y):y,headers:A,body:P?_t:T}});let M=Number((m=e.data)==null?void 0:m.timeoutMs),b=new AbortController,F=Number.isFinite(M)&&M>0?setTimeout(()=>b.abort(),M):null,$;try{console.log("[apiNodeRunner] fetching..."),$=await fetch(y,{method:h,headers:x,body:T,signal:b.signal}),console.log("[apiNodeRunner] fetch returned status:",$.status)}finally{F&&clearTimeout(F)}let j=$.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",j);let I;j.includes("application/json")?I=await $.json():I=await $.text(),console.log("[apiNodeRunner] payload preview:",typeof I=="string"?I.slice(0,200):JSON.stringify(I).slice(0,200)),l={ok:$.ok,status:$.status,data:I};let _=Date.now()-d;i==null||i({type:"api_call",payload:{nodeId:e.id,url:y,method:h,status:$.status,latencyMs:_}});let{value:U,truncated:H}=eo(I);t==null||t({type:"info:apiNodeRunner:response",content:{nodeId:e.id,ok:$.ok,status:$.status,latencyMs:_,data:U,truncated:H,outVars:oo(e,l)}}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}catch(g){console.error("Error processing ApiNode:",g),t==null||t({type:"error:apiNodeRunner",content:`API node execution failed: ${g}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(g)}})}finally{console.log("[apiNodeRunner] final result:",(a=JSON.stringify(l))==null?void 0:a.slice(0,300)),n==null||n(e.id,l)}}import{generateObject as so}from"ai";import{z as Te}from"zod";async function Ft(o,e,s,t,n,r,i){var g,y,h;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let l=(s==null?void 0:s.context)??{},d=String(((g=e==null?void 0:e.data)==null?void 0:g.input_variable)||"user_input").trim(),f=(l==null?void 0:l[d])??"",u=Array.isArray((y=e==null?void 0:e.data)==null?void 0:y.items)?e.data.items:[];if(u.length===0){t==null||t({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let p=String((h=u[u.length-1])==null?void 0:h.id);if(!f||String(f).trim().length===0){t==null||t({type:"warning:classifier",content:"No input for classification \u2014 falling back to last item."}),n==null||n(e.id,{classification:p}),s.context=s.context||{},s.context.classified_id=p,r==null||r(s);return}let m=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
|
|
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 Ie(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 Te(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 Ne(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 Ae(o,t){o.sql`DELETE FROM context WHERE domain = 'tool' AND cycle <= ${t}`}async function Ce(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 Oe(o){await co(o),await lo(o)}function Ft(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 uo="anonymous:";function _e(o,t){return(o==null?void 0:o.trim())||`${uo}${t}`}async function Dt(o,t){if(!It(o))return null;let n=await fetch(`${o.HX_ORA_URL}/internal/runs`,{method:"POST",headers:Ft(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:Ft(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:Ft(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 $e(o,t){if(!It(o))return Promise.resolve();try{return await Dt(o,t)}catch(n){return console.error("[oraTriggers] recordRun failed",n),null}}var Pt=Object.freeze({}),po="__SYSTEM_";function ke(o){return o.startsWith(po)}function fo(o){let t={};for(let[n,e]of Object.entries(o))ke(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 fo(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=>!ke(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})),a={};for(let d of i){if(!d)continue;let[u,p]=d;u&&(a[u]=p)}return Object.freeze(a)}catch(s){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:t,err:s}),Pt}}import{nanoid as vn}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 Fe(o,t){return typeof t.cycle=="number"&&Number.isFinite(t.cycle)?t.cycle+1:await Ce(o)+1}function De(o,t,n,e,s){let r=pt(it(n));return{...t,memoryConfig:r,cycle:e,setContext:async a=>{await xe(o,a),await(s==null?void 0:s(a.ref))},getContextIndex:async()=>ht(o),getContextData:async a=>Te(o,a),getContext:async a=>Rt(o,a),resolveContext:async a=>Ne(o,a),pruneContext:async a=>Ae(o,a)}}import{nanoid as Ko}from"nanoid";async function Pe(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 mo(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(a=>a.ref===o&&(a.type==="image"||a.type==="file"))}function go(o,t){var i,a,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=(a=t.flowData)==null?void 0:a.state)==null?void 0:d.nodes)||[],s={},r=new Set;for(let f of n){let c=(u=f.key)==null?void 0:u.trim(),m=(p=f.from)==null?void 0:p.trim();if(!c||!m)throw new Error(`Answer node ${o.id} has an incomplete variable mapping`);if(r.has(c))throw new Error(`Answer node ${o.id} has duplicate output key "${c}"`);if(mo(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 S(y.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Answer node ${o.id} could not resolve output "${m}"`);w=f.default}s[c]=w,r.add(c)}try{JSON.stringify(s)}catch{throw new Error(`Answer node ${o.id} produced a value that is not JSON serializable`)}return s}async function Ut(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 a;try{a=go(t,n)}catch(g){throw e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(g)}}),g}a&&o.outputCollector&&o.outputCollector.add(t.id,a);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:!!a&&!!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 a,d,u,p,g;let r=(s==null?void 0:s.callerTag)??"llmNodeRunner",i=(s==null?void 0:s.serializeNonStrings)??!1;return ue(o,t,{context:n.context??{},results:n.results??{},nodes:((d=(a=n.flowData)==null?void 0:a.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 bt="[redacted]",Ue=8*1024;function yo(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<=Ue){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,Ue);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(e),truncated:!0}}function wo(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 Et(o,t,n,e,s,r,i){var u,p,g,l,f,c;`${t.id}`,e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let a=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,a);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 b in h)if(Object.prototype.hasOwnProperty.call(h,b)){let X=String(h[b]??"");R[b]=B(X),I[b]=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 b=typeof t.data.body=="string"?t.data.body:JSON.stringify(t.data.body);O=B(b),x=Mt(b,t,n,o,e),!I["Content-Type"]&&!I["content-type"]&&(I["Content-Type"]="application/json")}let A={};for(let b in I)A[b]=R[b]?bt:I[b];console.log("[apiNodeRunner] headers:",JSON.stringify(A)),console.log("[apiNodeRunner] body:",O?bt:x),e==null||e({type:"info:apiNodeRunner:request",content:{nodeId:t.id,method:w,url:B(m)?st(y):y,headers:A,body:O?bt:x}});let U=Number((f=t.data)==null?void 0:f.timeoutMs),E=new AbortController,F=Number.isFinite(U)&&U>0?setTimeout(()=>E.abort(),U):null,_;try{console.log("[apiNodeRunner] fetching..."),_=await fetch(y,{method:w,headers:I,body:x,signal:E.signal}),console.log("[apiNodeRunner] fetch returned status:",_.status)}finally{F&&clearTimeout(F)}let C=_.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",C);let $;C.includes("application/json")?$=await _.json():$=await _.text(),console.log("[apiNodeRunner] payload preview:",typeof $=="string"?$.slice(0,200):JSON.stringify($).slice(0,200)),a={ok:_.ok,status:_.status,data:$};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:P,truncated:H}=yo($);e==null||e({type:"info:apiNodeRunner:response",content:{nodeId:t.id,ok:_.ok,status:_.status,latencyMs:T,data:P,truncated:H,outVars:wo(t,a)}}),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:",(c=JSON.stringify(a))==null?void 0:c.slice(0,300)),s==null||s(t.id,a)}}var ho="[redacted]",be=8*1024;function jt(o,t){if(typeof o=="string")return B(o)?typeof t=="string"&&/^https?:\/\//i.test(t)?st(t):ho: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]=jt(r,e[s]);return n}if(Array.isArray(o)){let n=Array.isArray(t)?t:[];return o.map((e,s)=>jt(e,n[s]))}return t}function Ro(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<=be){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,be);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(e),truncated:!0}}function xo(o,t){let n={};for(let e of ft(o))n[e.name]=mt(t,e.path??"");return n}var Io=(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 To(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 No(o,t){var i,a;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]=To(u);return{types:n,properties:e}}let r=(a=o.data)==null?void 0:a.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 Ao(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 Co(o){return o===void 0||typeof o=="string"&&o.trim()===""}function Lt(o,t,n,e,s,r,i){if(typeof o=="string"){let a=o.includes("{{")?Io(o,t,n,e,s):o;return Ao(a,r,i)}if(o&&typeof o=="object"&&!Array.isArray(o)){let a={};for(let[d,u]of Object.entries(o))a[d]=Lt(u,t,n,e,s);return a}return Array.isArray(o)?o.map(a=>Lt(a,t,n,e,s)):o}function Oo(o,t,n,e,s,r){let i={};for(let[a,d]of Object.entries(o)){let u=Lt(d,t,n,e,s,r.types[a],r.properties[a]);Co(u)||(i[a]=u)}return i}async function _o(o){if(o.toolCatalog)return o.toolCatalog;if(!o.env)return o.toolCatalog={},o.toolCatalog;let t=await pe(o.env),n={};for(let e of t)e!=null&&e.id&&(n[e.id]=e);return o.toolCatalog=n,n}async function $o(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 Ht(o,t,n,e,s,r,i){var p,g,l,f,c,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 a={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:{},A,U;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(U=(await $o(o))[T],!U)throw new Error(`Tool ${T} not found`);A=U.inputSchema}let E=No(t,A),F=Oo(O,t,n,o,e,E);if(e==null||e({type:"info:toolNodeRunner:request",content:{nodeId:t.id,source:u,catalogId:(f=t.data)==null?void 0:f.catalogId,toolSlug:(c=t.data)==null?void 0:c.toolSlug,toolId:(m=t.data)==null?void 0:m.toolId,args:jt(O,F)}}),u==="catalog"){let T=typeof((y=t.data)==null?void 0:y.catalogId)=="string"?t.data.catalogId.trim():"",P=typeof((w=t.data)==null?void 0:w.toolSlug)=="string"?t.data.toolSlug.trim():"";if(!T||!P)throw new Error("Catalog tool nodes require catalogId and toolSlug");let b=(await _o(o))[T];if(!b)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():"",j=await fe(o,{toolSlug:P,connectionScope:b.connectionScope,toolVersion:X||null,toolkitVersion:b.toolkitVersion,arguments:F});a={ok:j.ok,data:j.ok?j.data:null,error:j.ok?null:j.error??"Tool execution failed"}}else{let T=yt(U,o,n,e);if(!T.execute)throw new Error(`Tool ${(I=t.data)==null?void 0:I.toolId} is missing an execute handler`);let P=await T.execute(F,{}),H=P&&typeof P=="object"&&"error"in P&&P.error?String(P.error):null;a={ok:!H,data:P,error:H}}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:a.ok?200:502,latencyMs:_}});let{value:C,truncated:$}=Ro(a.data);e==null||e({type:"info:toolNodeRunner:response",content:{nodeId:t.id,ok:a.ok,latencyMs:_,data:C,truncated:$,error:a.error,outVars:xo(t,a)}}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:a.ok?"success":"error",error:a.error??void 0}})}catch(O){let A=O instanceof Error?O.message:String(O);a={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,a)}}import{generateObject as ko}from"ai";import{z as Me}from"zod";async function St(o,t,n,e,s,r,i){var c,m,y,w,h,I,R;e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let a=String(((c=t==null?void 0:t.data)==null?void 0:c.input_variable)||"user_input").trim(),d;try{let x=K(a,{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 "${a}" 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
|
-
${u.map(
|
|
22
|
-
label: ${
|
|
23
|
-
keywords/topics: ${
|
|
21
|
+
${u.map(x=>{let O=x.keywords??x["keywords/topics"]??"",A=Array.isArray(O)?O.join(", "):String(O||"");return`- id: ${x.id}
|
|
22
|
+
label: ${x.label}
|
|
23
|
+
keywords/topics: ${A}`}).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)),A="gpt_4_1_mini",U=await ut(A,o);if(!U)throw new Error(`Model '${A}' not found in registry`);let{modelHandle:E,effectiveParams:F}=U,_=await ko({model:E,messages:[{role:"system",content:l},{role:"user",content:f}],schema:Me.object({classification:Me.enum(O).describe("The id of the best matching category")}),temperature:F.temperature??0}),C=Date.now()-x,$=_.object.classification;i==null||i({type:"class_telemetry",payload:{nodeId:t.id,totalLatency:C,model:_.response.modelId,usage:_.usage,options:O}}),i==null||i({type:"class_result",payload:{result:_}}),s==null||s(t.id,{classification:$}),n.context=n.context||{},n.context.classified_id=$,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 Uo,streamText as bo}from"ai";import{nanoid as Mo}from"nanoid";import"zod";function Ee(o,t){var a,d,u,p,g;let n=((a=o.data)==null?void 0:a.attachments)??[];if(!Array.isArray(n))throw new S("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 S("INVALID_EXPRESSION",`Node ${o.id} has an invalid attachment reference`);let f=r.find(m=>m.ref===l);if(!f)throw new S("OUT_OF_SCOPE",`Attachment "${l}" is not in this node's connection scope`);if(f.type!=="file"&&f.type!=="image")throw new S("UNKNOWN_OUTPUT",`Attachment "${l}" is not an image or file output`);if(f.type!=="file")continue;let c=K(l,{context:t.context??{},results:t.results??{},nodes:e,edges:s,currentNodeId:o.id});if(c.missing)throw new S(c.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${l}" did not produce a value`);if(typeof c.value!="string")throw new S("PATH_NOT_FOUND",`Attachment "${l}" must resolve to file text`);c.value.trim()&&(i+=(i?`
|
|
29
29
|
|
|
30
|
-
`:"")+c)}}return s}function Ce(o,e){var t,n,r,i,l,d;let s=[];if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let f of o.data.varMapping){let u=f.from;if(!u)continue;let p=!1;if(u==="images")p=!0;else{let c=u.indexOf(".");if(c!==-1){let m=u.substring(0,c),a=u.substring(c+1).split(".")[0],g=(i=(r=(n=e.flowData)==null?void 0:n.state)==null?void 0:r.nodes)==null?void 0:i.find(y=>y.id===m);if(g){let h=G(g).find(w=>w.name===a);(h==null?void 0:h.type)==="image"&&(p=!0)}}}if(p){let c=v(u,{context:e.context||{},results:e.results||{},nodes:((d=(l=e.flowData)==null?void 0:l.state)==null?void 0:d.nodes)||[]});Array.isArray(c)&&s.push(...c)}}return s}var no=it({"../tools/composioTool.ts":()=>import("./composioTool-44B637WM.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-MRMZWSXQ.js"),"../tools/recall.ts":()=>import("./recall-IABRCSHY.js"),"../tools/skillTool.ts":()=>import("./skillTool-BSQFKZGK.js"),"../tools/tempTool.ts":()=>import("./tempTool-2RXAF56M.js"),"../tools/twitter.ts":()=>import("./twitter-OMDEG7T2.js"),"../tools/vectorize.ts":()=>import("./vectorize-UJXIDL2E.js")});var ro=it({});function Mt(o,e,s,t,n){var i;if(!((i=t.memoryConfig)!=null&&i.enabled)||!t.memoryConfig.toolCache||!s.cacheable||!e||typeof e.execute!="function")return e;let r=e.execute.bind(e);return e.execute=async(l,...d)=>{var c;if(!t.getContextIndex)return r(l,...d);let f=await xt(l),p=(await t.getContextIndex()).find(m=>{if(m.domain!=="tool")return!1;let a=It(m.meta);return a.toolName===o&&a.paramsHash===f});if(p){let m=await((c=t.getContext)==null?void 0:c.call(t,p.ref));if((m==null?void 0:m.data)!=null&&It(m.meta).truncated!==!0){n==null||n({type:"info:memory:cacheHit",content:{ref:m.ref,toolName:o}});try{return JSON.parse(m.data)}catch{return m.data}}}return r(l,...d)},e}async function lo(o,e,s,t){var u,p;if(!((u=s.memoryConfig)!=null&&u.enabled)||!s.setContext||s.cycle==null)return;let n=o.toolCalls??[],r=o.toolResults??[];if(!n.length||!r.length)return;let i=new Map;for(let c of r)c!=null&&c.toolCallId&&i.set(c.toolCallId,c);let l=Array.isArray((p=e==null?void 0:e.data)==null?void 0:p.tools)?e.data.tools:[],d=new Map;for(let c of l)c&&typeof c.id=="string"&&d.set(c.id,c);let f=new Map;for(let c of Object.values(s.toolDefs??{}))c&&c.name&&f.set(c.name,c);for(let c of n){let m=c.toolCallId,a=c.toolName,g=i.get(m);if(!a||!g||a==="readSkillRef")continue;let y=c.args??c.input,h=g.result??g.output,w=!1,x="",R="tool",T="",P=f.get(a);P&&P.kind==="skill"&&(w=!0,x=`skill:${a}`,R="skill",T=`Skill instructions for ${a}`),x||(x=await Wt(a,y),T=zt(y,h));let A=d.get(a)??l.find(F=>F.id===a),M=await xt(y),b=typeof h=="string"?h:JSON.stringify(h??null);await s.setContext({ref:x,domain:R,description:T,data:b,cycle:s.cycle,meta:JSON.stringify({toolName:a,paramsHash:M,cacheable:(A==null?void 0:A.cacheable)===!0})}),t==null||t({type:"info:memory:updated",content:{ref:x}})}}async function uo(o,e,s,t){var p;let n=Array.isArray((p=s==null?void 0:s.data)==null?void 0:p.tools)?s.data.tools:[];if(n.length===0)return{};let r={},i=c=>{var x,R;let m=typeof(c==null?void 0:c.description)=="string"?c.description:"",a=c==null?void 0:c.inputSchema,g;try{let T=(a==null?void 0:a.shape)??(typeof((x=a==null?void 0:a._def)==null?void 0:x.shape)=="function"?a._def.shape():(R=a==null?void 0:a._def)==null?void 0:R.shape);T&&typeof T=="object"&&(g=T)}catch{}let y=g?Object.keys(g):[],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}`},l=(()=>{let c=[],m=[],a=[],g=[];for(let h=0;h<n.length;h++){let w=n[h];!w||typeof w!="object"||typeof w.id!="string"?g.push(h):w.kind==="builtin"?c.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 c.length&&y.push(`builtin[${c.join(", ")}]`),m.length&&y.push(`custom[${m.join(", ")}]`),a.length&&y.push(`skill[${a.join(", ")}]`),g.length&&y.push(`invalid@[${g.join(", ")}]`),y.join(" ")||"(none)"})();console.log(`[tools] node ${s.id} requested (${n.length}): ${l}`);let d=!1,f=async()=>{if(d&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},d=!0,o.toolDefs;try{let c=await re(o.env),m={};for(let a of c)a&&a.id&&(m[a.id]=a);o.toolDefs=m}catch(c){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(c)}`}),o.toolDefs=o.toolDefs||{}}return d=!0,o.toolDefs},u=[];for(let c=0;c<n.length;c++){let m=n[c];if(!m||typeof m!="object"||typeof m.id!="string"||m.kind!=="builtin"&&m.kind!=="http"&&m.kind!=="mcp"&&m.kind!=="composio"&&m.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${c}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let a=m;if(a.kind!=="builtin"){let y=(await f())[a.id];if(!y){console.error(`[tools] \u2717 custom '${a.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${a.id}' not found for this tenant`});continue}if(a.kind==="composio"){try{let w=await oe(y,o,e,t),x=Object.keys(w);for(let[R,T]of Object.entries(w))r[R]=Mt(R,T,a,o,t);console.log(`[tools] \u2713 composio '${a.id}' \u2192 ${x.length} tool(s)`)}catch(w){console.error(`[tools] \u2717 composio '${a.id}': ${String(w)}`),t==null||t({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'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${a.id}' is not a skill`});continue}let w=y.name;if(r[w]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin/other already registered, skipping skill '${a.id}'`});continue}try{r[w]=ie(y,o,e,t),u.push(y);let x=typeof y.execution=="string"?JSON.parse(y.execution):y.execution||{},R=Array.isArray(x.references)?x.references.map(T=>T==null?void 0:T.name):[];console.log(`[tools] \u2713 skill '${a.id}' \u2192 '${w}' (refs: ${R.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:w,refCount:R.length,refs:R}})}catch(x){console.error(`[tools] \u2717 skill '${a.id}': ${String(x)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${a.id}': ${String(x)}`})}continue}let h=y.name;if(r[h]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${h}' \u2014 builtin already registered, skipping custom tool '${a.id}'`});continue}try{let w=ne(y,o,e,t);r[h]=Mt(h,w,a,o,t),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)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${a.id}': ${String(w)}`})}continue}if(!ee[a.id]){console.error(`[tools] \u2717 builtin '${a.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${a.id}' not found in registry`});continue}try{let g;try{g=await no(`../tools/${a.id}.ts`)}catch{g=await ro(`../tools/${a.id}.js`)}let y;if(g[a.id])y=g[a.id];else if(g.default)y=g.default;else if(g.create)y=g.create;else{let A=Object.values(g);A.length>0&&(y=A[0])}if(!y){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${a.id}'`});continue}let 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&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${a.id}' \u2014 must be a string`})),a.params.inputSchema!==void 0){let A=a.params.inputSchema;typeof A=="object"&&(typeof A.safeParse=="function"||A._def)?w=A:typeof A=="object"&&A!==null&&A.type==="object"&&A.properties?(w=se(A),w||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${a.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${a.id}' \u2014 must be a Zod schema or JSON Schema object`})}a.params.defaults!==void 0?typeof a.params.defaults=="object"&&a.params.defaults!==null&&!Array.isArray(a.params.defaults)?x=a.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${a.id}' \u2014 must be an object`}),x={}):a.params.source!==void 0||a.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${a.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),x={}):x={}}let R=y(o,e,x,t);h&&R&&typeof R=="object"&&(R.description=h),w&&R&&typeof R=="object"&&(R.inputSchema=w),r[a.id]=Mt(a.id,R,a,o,t);let T=[];h&&T.push("description"),w&&T.push("inputSchema"),Object.keys(x).length&&T.push(`defaults(${Object.keys(x).join(",")})`);let P=T.length?` [overrides: ${T.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${a.id}'${P}`),console.log(`[tools] ${i(R)}`)}catch(g){console.error(`[tools] \u2717 builtin '${a.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${a.id}': ${String(g)}`});continue}}if(u.length>0)if(r.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{r.readSkillRef=ae(o,u,e,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${u.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:u.map(c=>c.name)}})}catch(c){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(c)}`)}return r}async function Dt(o,e,s,t,n,r,i){var M,b,F,$,j;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let l=!1;try{let I=(M=s.flowData)==null?void 0:M.state;if(I&&I.edges&&I.nodes){let _=I.edges.filter(U=>U.source===e.id);if(_.length>0){let U=I.nodes.find(H=>H.id===_[0].target);U&&U.type==="answerNode"&&(l=!0)}}}catch(I){console.error("Error determining next node for streaming:",I)}let d=W(e.data.template,e,s,t,{sessionEnv:o});(!d||!d.trim())&&(d="Answer straight forward to the user, dont offer any other option to continue");let f=d,u="";if((b=o.memoryConfig)!=null&&b.enabled){let I=await((F=o.getContextIndex)==null?void 0:F.call(o))??[];u=Bt(I),d+=u}let p=W(e.data.user_template||"",e,s,t,{sessionEnv:o}),c=I=>I&&Object.fromEntries(Object.keys(I).map(_=>[_,"[redacted]"])),m=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:c(o.secrets),userAuth:c(o.userAuth)}:o,a=W(e.data.template,e,s,void 0,{sessionEnv:m})||f;a+=u;let g=W(e.data.user_template||"",e,s,void 0,{sessionEnv:m});t==null||t({type:`info:llmNodeRunner:${e.id}`,content:a}),t==null||t({type:`info:llmNodeRunner:${e.id}`,content:g});let y=($=e==null?void 0:e.data)==null?void 0:$.window_size,h=Number(y);(!Number.isInteger(h)||h<=0)&&(h=5);let w=Ce(e,s),x=Ne(e,s),T=(await((j=o.getMessages)==null?void 0:j.call(o))??[]).slice(-h),P=T.filter(I=>I&&typeof I.role=="string"&&typeof I.content=="string");P.length!==T.length&&console.warn(`Filtered ${T.length-P.length} invalid messages from history`);let A=fo(P,p,w,x);await po(d,A,o.conn,t,e,l,n,s,r,o,i)}async function po(o,e,s,t,n,r,i,l,d,f,u){var c;let p=Date.now();if(!((c=f.env)!=null&&c.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(m,a)=>{var j,I,_,U,H,E,J;let g,y={},h,w="none",x=!1,R,T=!1,P=!1,A=0,M=0,b=(j=n==null?void 0:n.data)==null?void 0:j.sendReasoning,F=b!==!1;try{let L=(I=n==null?void 0:n.data)==null?void 0:I.model,Y=Array.isArray(L)?L[0]:L||"gpt_5_nano",N=Kt(n==null?void 0:n.data),O=await lt(Y,f,N);if(!O)throw new Error(`Model '${Y}' not found in registry`);g=O.modelHandle,y=O.effectiveParams||{},w=O.reasoning.kind;let C=St(O.reasoning,(_=n==null?void 0:n.data)==null?void 0:_.reasoningEffort);x=F&&Jt(O.reasoning);let V=typeof((U=n==null?void 0:n.data)==null?void 0:U.reasoningMaxTokens)=="number"?n.data.reasoningMaxTokens:void 0;h=Gt(O.provider,{effort:C,exposeReasoning:x,maxTokens:V}),C&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:C})),console.log(`[reasoning] ${JSON.stringify({model:Y,provider:O.provider,capability:O.reasoning,requestedEffort:((H=n==null?void 0:n.data)==null?void 0:H.reasoningEffort)??null,resolvedEffort:C??null,sendReasoning:F,exposeReasoning:x,providerOptions:h??null},null,2)}`);for(let q of O.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:q});t==null||t({type:"info:llmNodeRunner:model",content:Y}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(E=n==null?void 0:n.data)!=null&&E.generationPreset?{preset:n.data.generationPreset}:{},...y,...w!=="none"?{reasoning:w,configuredSendReasoning:b,sendReasoning:F,exposeReasoning:x,...C?{effort:C}:{}}:{}}})}catch(L){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(L)}`}),L}let $=await uo(f,l,n,t);if((J=f.memoryConfig)!=null&&J.enabled){let{recall:L}=await import("./recall-IABRCSHY.js");$.recall=L(f,l,void 0,t)}console.log(`[tools] node ${n.id} loaded ${Object.keys($).length}: ${Object.keys($).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:n.id,tools:Object.keys($)}});try{let L=ao({model:g,system:o,messages:e,stopWhen:(()=>{var q;let O=!!$.readSkillRef?10:5,C=Number(((q=n.data)==null?void 0:q.max_steps)??O),V=Number.isFinite(C)?Math.max(1,Math.min(30,C)):O;return io(V)})(),...Xt(y),...h?{providerOptions:h}:{},tools:$,onFinish:async N=>{var Et,Lt;let O=N.text||"",C=N.reasoningText??((Et=N.reasoning)==null?void 0:Et.text)??"";if(console.log(`[reasoning] done: deltas=${A} chars=${M} result.reasoningText=${C.length} finishReason=${N.finishReason??"n/a"} reasoningTokens=${((Lt=N.usage)==null?void 0:Lt.reasoningTokens)??"n/a"}`),F&&x&&!T&&C&&s){T=!0;try{k(s,D.SERVER_REASONING_STREAM,C)}catch(We){console.warn("Failed to send finished reasoning over connection",We)}}let V={id:co(),role:"assistant",type:"text",content:O,ts:Date.now()};r&&(f.setMessages?await f.setMessages(V):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),s&&F&&T&&!P&&(P=!0,k(s,D.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),r&&s&&k(s,D.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),i==null||i((n==null?void 0:n.id)||"llm_result",O),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(N)});let q=Date.now()-p,ze=R?R-p:void 0;u==null||u({type:"llm_telemetry",payload:{nodeId:n.id,totalLatency:q,timeToFirstToken:ze,model:N.response.modelId,usage:N.usage}}),u==null||u({type:"llm_result",payload:{result:N}})},onStepFinish:async N=>{let O=(C,V=200)=>{let q=typeof C=="string"?C:JSON.stringify(C);return q?q.length>V?`${q.slice(0,V)}\u2026(+${q.length-V})`:q:""};if(N.toolCalls&&N.toolCalls.length>0){for(let C of N.toolCalls)console.log(`[tools] \u2192 ${C.toolName}(${O(C.args??C.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${n.id}`,content:JSON.stringify(N.toolCalls)})}if(N.toolResults&&N.toolResults.length>0){for(let C of N.toolResults)console.log(`[tools] \u2190 ${C.toolName} \u2192 ${O(C.result??C.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${n.id}`,content:JSON.stringify(N.toolResults)})}await lo(N,n,f,t)},experimental_onToolCallStart:N=>{var O;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(O=N==null?void 0:N.toolCall)==null?void 0:O.toolName,status:"start"}})},experimental_onToolCallFinish:N=>{var O,C;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(O=N==null?void 0:N.toolCall)==null?void 0:O.toolName,status:((C=N==null?void 0:N.toolOutput)==null?void 0:C.type)==="tool-error"?"error":"success"}})},onError:N=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),a(N)},onChunk:N=>{if(N.chunk.type==="reasoning-delta"){let C=N.chunk.text??N.chunk.delta??"";if(C&&(T=!0,A+=1,M+=C.length,A===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),F&&s&&C)try{k(s,D.SERVER_REASONING_STREAM,C)}catch(V){console.warn("Failed to send reasoning chunk over connection",V)}return}if(N.chunk.type==="text-delta"){if(R||(R=Date.now()),s&&F&&T&&!P){P=!0;try{k(s,D.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(C){console.warn("Failed to send reasoning complete over connection",C)}}return}u==null||u({type:N.chunk.type,payload:{nodeId:n.id,chunk:N.chunk}});let O=`llm_chunk:${N.chunk.type}`;t==null||t({type:O,content:{...N}})}}),Y=async()=>{let N="";for await(let O of L.fullStream)if(O.type==="text-delta"){if(N+=O.text,r&&s)try{k(s,D.SERVER_TEXT_STREAM,O.text)}catch(C){console.warn("Failed to send chunk over connection",C)}}else if(O.type==="finish-step"&&O.finishReason==="tool-calls"){if(r&&s&&N.trim())try{k(s,D.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(C){console.warn("Failed to flush text segment over connection",C)}N=""}};await Promise.all([L,Y()]),m(),t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"success"}})}catch(L){t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"error",error:String(L)}}),a(L)}})}function fo(o,e,s,t){let n=!!(s&&s.length>0),r=!!t,i=n||r,d=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,f=u=>{let p=[],c="";if(r&&(c+=`[Attached files]
|
|
31
|
-
${
|
|
30
|
+
`:"")+c.value)}return i}function Fo(o,t){var s,r,i,a,d;let n=((s=o.data)==null?void 0:s.attachments)??[];if(!Array.isArray(n))throw new S("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=(a=t.flowData)==null?void 0:a.state)==null?void 0:d.edges)??[],o.id);return n.map(u=>{if(typeof u!="string")throw new S("INVALID_EXPRESSION",`Node ${o.id} has an invalid attachment reference`);let p=e.find(g=>g.ref===u);if(!p)throw new S("OUT_OF_SCOPE",`Attachment "${u}" is not in this node's connection scope`);if(p.type!=="image"&&p.type!=="file")throw new S("UNKNOWN_OUTPUT",`Attachment "${u}" is not a binary output`);return p.type==="image"?u:null}).filter(u=>u!==null)}function je(o,t){var s,r,i,a;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:((a=(i=t.flowData)==null?void 0:i.state)==null?void 0:a.edges)??[],currentNodeId:o.id};for(let d of Fo(o,t)){let u=K(d,e);if(u.missing)throw new S(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 S("PATH_NOT_FOUND",`Attachment "${d}" must resolve to an image array`);n.push(...u.value)}return n}var Do=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 Po=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(a,...d)=>{var l;if(!e.getContextIndex)return r(a,...d);let u=await $t(a),g=(await e.getContextIndex()).find(f=>{if(f.domain!=="tool")return!1;let c=kt(f.meta);return c.toolName===o&&c.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&&kt(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(a,...d)},t}async function Eo(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 a=Array.isArray((g=t==null?void 0:t.data)==null?void 0:g.tools)?t.data.tools:[],d=new Map;for(let l of a)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,c=l.toolName,m=i.get(f);if(!c||!m||c==="readSkillRef")continue;let y=l.args??l.input,w=m.result??m.output,h=!1,I="",R="tool",x="",O=u.get(c);O&&O.kind==="skill"&&(h=!0,I=`skill:${c}`,R="skill",x=`Skill instructions for ${c}`),I||(I=await re(c,y),x=se(y,w));let A=d.get(c)??a.find(F=>F.id===c),U=await $t(y),E=typeof w=="string"?w:JSON.stringify(w??null);await n.setContext({ref:I,domain:R,description:x,data:E,cycle:n.cycle,meta:JSON.stringify({toolName:c,paramsHash:U,cacheable:(A==null?void 0:A.cacheable)===!0})}),e==null||e({type:"info:memory:updated",content:{ref:I}})}}async function jo(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:"",c=l==null?void 0:l.inputSchema,m;try{let x=(c==null?void 0:c.shape)??(typeof((I=c==null?void 0:c._def)==null?void 0:I.shape)=="function"?c._def.shape():(R=c==null?void 0:c._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}`},a=(()=>{let l=[],f=[],c=[],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"?c.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(", ")}]`),c.length&&y.push(`skill[${c.join(", ")}]`),m.length&&y.push(`invalid@[${m.join(", ")}]`),y.join(" ")||"(none)"})();console.log(`[tools] node ${n.id} requested (${s.length}): ${a}`);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 c of l)c&&c.id&&(f[c.id]=c);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 c=f;if(c.kind!=="builtin"){let y=(await u())[c.id];if(!y){console.error(`[tools] \u2717 custom '${c.id}': not found for tenant`),e==null||e({type:"error:llmNodeRunner",content:`custom tool '${c.id}' not found for this tenant`});continue}if(c.kind==="composio"){try{let h=await ye(y,o,t,e),I=Object.keys(h);for(let[R,x]of Object.entries(h))r[R]=Vt(R,x,c,o,e);console.log(`[tools] \u2713 composio '${c.id}' \u2192 ${I.length} tool(s)`)}catch(h){console.error(`[tools] \u2717 composio '${c.id}': ${String(h)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading composio tool '${c.id}': ${String(h)}`})}continue}if(c.kind==="skill"){if(y.kind!=="skill"){console.error(`[tools] \u2717 skill '${c.id}': row is of kind '${y.kind}', not 'skill'`),e==null||e({type:"error:llmNodeRunner",content:`tool '${c.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 '${c.id}'`});continue}try{r[h]=we(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 '${c.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 '${c.id}': ${String(I)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading skill tool '${c.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 '${c.id}'`});continue}try{let h=yt(y,o,t,e);r[w]=Vt(w,h,c,o,e),console.log(`[tools] \u2713 custom '${c.id}' \u2192 '${w}'`),console.log(`[tools] ${i(r[w])}`)}catch(h){console.error(`[tools] \u2717 custom '${c.id}': ${String(h)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading custom tool '${c.id}': ${String(h)}`})}continue}if(!ge[c.id]){console.error(`[tools] \u2717 builtin '${c.id}': not in registry`),e==null||e({type:"error:llmNodeRunner",content:`Tool '${c.id}' not found in registry`});continue}try{let m;try{m=await Do(`../tools/${c.id}.ts`)}catch{m=await Po(`../tools/${c.id}.js`)}let y;if(m[c.id])y=m[c.id];else if(m.default)y=m.default;else if(m.create)y=m.create;else{let A=Object.values(m);A.length>0&&(y=A[0])}if(!y){e==null||e({type:"error:llmNodeRunner",content:`No factory export found for tool '${c.id}'`});continue}let w,h,I={};if(c.params&&typeof c.params=="object"){if(typeof c.params.description=="string"?w=c.params.description:c.params.description!==void 0&&(e==null||e({type:"error:llmNodeRunner",content:`Invalid description for tool '${c.id}' \u2014 must be a string`})),c.params.inputSchema!==void 0){let A=c.params.inputSchema;typeof A=="object"&&(typeof A.safeParse=="function"||A._def)?h=A:typeof A=="object"&&A!==null&&A.type==="object"&&A.properties?(h=me(A),h||e==null||e({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${c.id}' \u2014 must be a Zod schema or JSON Schema object`})):e==null||e({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${c.id}' \u2014 must be a Zod schema or JSON Schema object`})}c.params.defaults!==void 0?typeof c.params.defaults=="object"&&c.params.defaults!==null&&!Array.isArray(c.params.defaults)?I=c.params.defaults:(e==null||e({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${c.id}' \u2014 must be an object`}),I={}):c.params.source!==void 0||c.params.target!==void 0?(e==null||e({type:"error:llmNodeRunner",content:`Invalid params for tool '${c.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[c.id]=Vt(c.id,R,c,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 '${c.id}'${O}`),console.log(`[tools] ${i(R)}`)}catch(m){console.error(`[tools] \u2717 builtin '${c.id}': ${String(m)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading tool '${c.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=he(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 U,E,F,_,C,$;`${t.id}`,e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let a=!1;try{let T=(U=n.flowData)==null?void 0:U.state;if(T&&T.edges&&T.nodes){let P=T.edges.filter(H=>H.source===t.id);if(P.length>0){let H=T.nodes.find(b=>b.id===P[0].target);H&&H.type==="answerNode"&&(a=!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((E=o.memoryConfig)!=null&&E.enabled){let T=await((F=o.getContextIndex)==null?void 0:F.call(o))??[];p=ae(T),d+=p}let g=G(t.data.user_template||"",t,n,e,{sessionEnv:o}),l=T=>T&&Object.fromEntries(Object.keys(T).map(P=>[P,"[redacted]"])),f=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:l(o.secrets),userAuth:l(o.userAuth)}:o,c=G(t.data.template,t,n,void 0,{sessionEnv:f})||u;c+=p;let m=G(t.data.user_template||"",t,n,void 0,{sessionEnv:f});e==null||e({type:`info:llmNodeRunner:${t.id}`,content:c}),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=je(t,n),I=Ee(t,n);e==null||e({type:"info:llmNodeRunner:attachments",content:{nodeId:t.id,refs:Array.isArray((C=t.data)==null?void 0:C.attachments)?t.data.attachments:[],images:h.length,documents:I?1:0}});let x=(await(($=o.getMessages)==null?void 0:$.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 A=Ho(O,g,h,I);await Lo(d,A,o.conn,e,t,a,s,n,r,o,i)}async function Lo(o,t,n,e,s,r,i,a,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,c)=>{var C,$,T,P,H,b,X;let m,y={},w,h="none",I=!1,R,x=!1,O=!1,A=0,U=0,E=(C=s==null?void 0:s.data)==null?void 0:C.sendReasoning,F=E!==!1;try{let j=($=s==null?void 0:s.data)==null?void 0:$.model,Q=Array.isArray(j)?j[0]:j||"gpt_5_nano",N=vt(s==null?void 0:s.data),D=await ut(Q,u,N);if(!D)throw new Error(`Model '${Q}' not found in registry`);m=D.modelHandle,y=D.effectiveParams||{},h=D.reasoning.kind;let k=oe(D.reasoning,(T=s==null?void 0:s.data)==null?void 0:T.reasoningEffort);I=F&&ee(D.reasoning);let q=typeof((P=s==null?void 0:s.data)==null?void 0:P.reasoningMaxTokens)=="number"?s.data.reasoningMaxTokens:void 0;w=ne(D.provider,{effort:k,exposeReasoning:I,maxTokens:q}),k&&(e==null||e({type:"info:llmNodeRunner:reasoningEffort",content:k})),console.log(`[reasoning] ${JSON.stringify({model:Q,provider:D.provider,capability:D.reasoning,requestedEffort:((H=s==null?void 0:s.data)==null?void 0:H.reasoningEffort)??null,resolvedEffort:k??null,sendReasoning:F,exposeReasoning:I,providerOptions:w??null},null,2)}`);for(let V of D.paramAdjustments??[])e==null||e({type:"warn:llmNodeRunner",content:V});e==null||e({type:"info:llmNodeRunner:model",content:Q}),e==null||e({type:"info:llmNodeRunner:generationParams",content:{...(b=s==null?void 0:s.data)!=null&&b.generationPreset?{preset:s.data.generationPreset}:{},...y,...h!=="none"?{reasoning:h,configuredSendReasoning:E,sendReasoning:F,exposeReasoning:I,...k?{effort:k}:{}}:{}}})}catch(j){throw e==null||e({type:"error:llmNodeRunner",content:`Model error: ${String(j)}`}),j}let _=await jo(u,a,s,e);if((X=u.memoryConfig)!=null&&X.enabled){let{recall:j}=await import("./recall-IABRCSHY.js");_.recall=j(u,a,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 j=bo({model:m,system:o,messages:t,stopWhen:(()=>{var V;let D=!!_.readSkillRef?10:5,k=Number(((V=s.data)==null?void 0:V.max_steps)??D),q=Number.isFinite(k)?Math.max(1,Math.min(30,k)):D;return Uo(q)})(),...te(y),...w?{providerOptions:w}:{},tools:_,onFinish:async N=>{var Gt,Wt;let D=N.text||"",k=N.reasoningText??((Gt=N.reasoning)==null?void 0:Gt.text)??"";if(console.log(`[reasoning] done: deltas=${A} chars=${U} result.reasoningText=${k.length} finishReason=${N.finishReason??"n/a"} reasoningTokens=${((Wt=N.usage)==null?void 0:Wt.reasoningTokens)??"n/a"}`),F&&I&&!x&&k&&n){x=!0;try{L(n,M.SERVER_REASONING_STREAM,k)}catch(ao){console.warn("Failed to send finished reasoning over connection",ao)}}let q={id:Mo(),role:"assistant",type:"text",content:D,ts:Date.now()};r&&(u.setMessages?await u.setMessages(q):e==null||e({type:"error:llmNodeRunner",content:"setMessages callback missing"})),n&&F&&x&&!O&&(O=!0,L(n,M.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),r&&n&&L(n,M.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),i==null||i((s==null?void 0:s.id)||"llm_result",D),e==null||e({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(N)});let V=Date.now()-g,io=R?R-g:void 0;p==null||p({type:"llm_telemetry",payload:{nodeId:s.id,totalLatency:V,timeToFirstToken:io,model:N.response.modelId,usage:N.usage}}),p==null||p({type:"llm_result",payload:{result:N}})},onStepFinish:async N=>{let D=(k,q=200)=>{let V=typeof k=="string"?k:JSON.stringify(k);return V?V.length>q?`${V.slice(0,q)}\u2026(+${V.length-q})`:V:""};if(N.toolCalls&&N.toolCalls.length>0){for(let k of N.toolCalls)console.log(`[tools] \u2192 ${k.toolName}(${D(k.args??k.input)})`);e==null||e({type:`info:llmNodeRunner:toolCalls:${s.id}`,content:JSON.stringify(N.toolCalls)})}if(N.toolResults&&N.toolResults.length>0){for(let k of N.toolResults)console.log(`[tools] \u2190 ${k.toolName} \u2192 ${D(k.result??k.output)}`);e==null||e({type:`info:llmNodeRunner:toolResults:${s.id}`,content:JSON.stringify(N.toolResults)})}await Eo(N,s,u,e)},experimental_onToolCallStart:N=>{var D;e==null||e({type:"tool:execution",content:{nodeId:s.id,toolName:(D=N==null?void 0:N.toolCall)==null?void 0:D.toolName,status:"start"}})},experimental_onToolCallFinish:N=>{var D,k;e==null||e({type:"tool:execution",content:{nodeId:s.id,toolName:(D=N==null?void 0:N.toolCall)==null?void 0:D.toolName,status:((k=N==null?void 0:N.toolOutput)==null?void 0:k.type)==="tool-error"?"error":"success"}})},onError:N=>{e==null||e({type:"error:llmNodeRunner",content:"Execution error"}),c(N)},onChunk:N=>{if(N.chunk.type==="reasoning-delta"){let k=N.chunk.text??N.chunk.delta??"";if(k&&(x=!0,A+=1,U+=k.length,A===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),F&&n&&k)try{L(n,M.SERVER_REASONING_STREAM,k)}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&&F&&x&&!O){O=!0;try{L(n,M.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(k){console.warn("Failed to send reasoning complete over connection",k)}}return}p==null||p({type:N.chunk.type,payload:{nodeId:s.id,chunk:N.chunk}});let D=`llm_chunk:${N.chunk.type}`;e==null||e({type:D,content:{...N}})}}),Q=async()=>{let N="";for await(let D of j.fullStream)if(D.type==="text-delta"){if(N+=D.text,r&&n)try{L(n,M.SERVER_TEXT_STREAM,D.text)}catch(k){console.warn("Failed to send chunk over connection",k)}}else if(D.type==="finish-step"&&D.finishReason==="tool-calls"){if(r&&n&&N.trim())try{L(n,M.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(k){console.warn("Failed to flush text segment over connection",k)}N=""}};await Promise.all([j,Q()]),f(),e==null||e({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"success"}})}catch(j){e==null||e({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"error",error:String(j)}}),c(j)}})}function Ho(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
|
+
${e}
|
|
32
32
|
[End of attached files]
|
|
33
33
|
|
|
34
|
-
`),
|
|
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 Xt(o,t,n,e,s,r,i){var p,g,l,f,c,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 a="",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:((c=(f=n.flowData)==null?void 0:f.state)==null?void 0:c.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,a);return}if(!t.data.rag_id){e==null||e({type:"error:memoNodeRunner",content:"Missing rag_id"}),s==null||s(t.id,a);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 Yt(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 F of x){e==null||e({type:"info:memoNodeRunner",content:`Executing RAG query with namespace: ${F}`});let _=await o.env[`VDB_${(m=n.flowData)==null?void 0:m.tenant}_1024`].query(R.data[0],{namespace:F,topK:t.data.topk,returnMetadata:"all"});e==null||e({type:"info:memoNodeRunner",content:`RAG query completed for namespace ${F}, matches: ${((y=_.matches)==null?void 0:y.length)||0}`}),Array.isArray(_.matches)&&O.push(..._.matches)}let A=Date.now()-u;a=O.map(F=>{var _;return(_=F.metadata)==null?void 0:_.value}).filter(F=>typeof F=="string").join(`
|
|
35
35
|
|
|
36
|
-
`),i==null||i({type:"memo_search",payload:{nodeId:
|
|
37
|
-
${
|
|
36
|
+
`),i==null||i({type:"memo_search",payload:{nodeId:t.id,searchLatencyMs:A,retrievedContext:a}}),e==null||e({type:"info:memoNodeRunner",content:`Context retrieval complete, length: ${a.length}, preview: ${a.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,a),e==null||e({type:"info:memoNodeRunner",content:`onResult called with context length: ${a.length}`}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"success"}}))}}async function Kt(o,t,n,e,s,r,i){var p,g,l,f,c,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 a=((g=t.data)==null?void 0:g.allow_images)!==!1,d=((l=t.data)==null?void 0:l.allow_documents)!==!1;!a&&(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:(c=n==null?void 0:n.context)==null?void 0:c.user_input,images:a?(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 He(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=qo(p,e.flowData,e)}async function i(u){var c;let p=d[u.type];if(!p){(c=n==null?void 0:n.onError)==null||c.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 a=async u=>{var f,c,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)||[],A=(R==null?void 0:R.documents)||[],U=await Pe(A,o.env),E=U.length>0?U.map(C=>`--- file: ${C.name} ---
|
|
37
|
+
${C.text}`).join(`
|
|
38
38
|
|
|
39
|
-
`):"";t.context={user_input:T,user_images:P,files:b},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},(m=s==null?void 0:s.onServerEvent)==null||m.call(s,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:F,error:$}=mo(t.flowData);if(!F)p="failed",c=$||"Flow Format Error",(a=s==null?void 0:s.onError)==null||a.call(s,c);else{let j=Z(F.data),{values:I,errors:_}=Ht(j,R==null?void 0:R.inputs);if(_.length>0)return p="failed",c=`Invalid flow inputs: ${_.join("; ")}`,(g=s==null?void 0:s.onError)==null||g.call(s,c),{status:p,error:c};t.context={...t.context,inputs:I,...I},t.context.user_input||(t.context.user_input=T),await r(F),(y=s==null?void 0:s.onServerEvent)==null||y.call(s,{type:"agent:telemetry",content:{durationMs:Date.now()-u,tokenUsage:t.tokenUsage},timestamp:Date.now()})}}catch(R){R instanceof ht?(p="stopped",c=R.message,(h=s==null?void 0:s.onServerEvent)==null||h.call(s,{type:"agent:stopped",content:c,timestamp:Date.now()})):(p="failed",c=R instanceof Error?R.message:"Agent execution failed",(w=s==null?void 0:s.onError)==null||w.call(s,c))}finally{(x=s==null?void 0:s.onServerEvent)==null||x.call(s,{type:"agent:complete",content:{status:p,durationMs:Date.now()-u},timestamp:Date.now()})}return{status:p,error:c}},d={startNode:kt,classifierNode:Ft,llmNode:Dt,memoNode:Ut,answerNode:Ot,apiNode:Pt};return l}var ht=class extends Error{constructor(){super("Stopped by user"),this.name="FlowExecutionStoppedError"}};function mo(o){var u;let e=(o==null?void 0:o.state)??o;if(!e||!e.nodes||!e.edges||e.edges.length===0)return{error:"Flow is missing state, nodes, or edges."};let s=e.nodes.filter(p=>p.type==="startNode");if(s.length!==1)return{error:`Flow must include exactly one START node, found ${s.length}.`};let t=s[0],n=e.nodes.filter(p=>p.type==="answerNode");if(n.length===0)return{error:"Flow must include at least one ANSWER node."};let r=new Map;for(let p of e.edges)r.has(p.source)||r.set(p.source,[]),r.get(p.source).push(p.target);let i=new Map;for(let p of e.edges)i.has(p.target)||i.set(p.target,[]),i.get(p.target).push(p.source);let l=Ae(t.id,r),d=new Set;for(let p of n){let c=Ae(p.id,i);for(let m of c)d.add(m)}let f=[];for(let p of l)if(!d.has(p)){let c=e.nodes.find(m=>m.id===p);if(c){let m=((u=c.data)==null?void 0:u.label)||"";f.push(`${p}(${m},${c.type})`)}}return f.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${f.join(", ")}`}:{startNode:t}}function Ae(o,e){let s=new Set,t=[o];for(s.add(o);t.length>0;){let n=t.shift(),r=e.get(n)||[];for(let i of r)s.has(i)||(s.add(i),t.push(i))}return s}function go(o,e){var s;return((s=o.state)==null?void 0:s.nodes.find(t=>t.id===e))||null}function yo(o,e,s){var l;let t=e==null?void 0:e.state;if(!t)return null;let n=t.edges.filter(d=>d.source===o.id);if(n.length===0)return null;let r=n[0].target;if(o.type==="classifierNode"&&((l=s==null?void 0:s.context)!=null&&l.classified_id)){let d=s.context.classified_id,f=n.find(u=>u.sourceHandle===`source-${d}`);f?r=f.target:console.log(`No matching edge, falling back to first: ${r}`)}return go(e,r)}async function _e(o,e){var t,n;let s=(t=e==null?void 0:e.flowData)==null?void 0:t.flowId;if(!(o!=null&&o.HX_CORE_URL)||!s)return{engineState:e,refreshed:!1};try{let r=await B(s,o),i={...e,flowData:{...r,tenant:e.flowData.tenant,flowId:s,chatId:e.flowData.chatId}},l=r==null?void 0:r.stateVersion,d=typeof l=="number"&&l!==((n=e.flowData)==null?void 0:n.stateVersion);return{engineState:i,refreshed:d}}catch(r){return console.error(`[flowRefresh] fetch failed for flow ${s}:`,r),{engineState:e,refreshed:!1}}}function $e(o,e){return!o||!o.HX_ORA_URL||!o.HX_API_KEY?Promise.resolve():fetch(`${o.HX_ORA_URL}/internal/sessions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:o.HX_API_KEY},body:JSON.stringify(e)}).catch(s=>{console.error("[sessionIndex] failed to index session",s)})}function Pe(){let o={};return{add(e,s){o[e]=s},hasOutputs(){return Object.keys(o).length>0},answerNodeIds(){return Object.keys(o)},snapshotData(){let e=Object.entries(o);return e.length===1?e[0][1]:Object.fromEntries(e)}}}function wo(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function Fe(o,e){if(!wo(o))throw new Error("Structured outputs require HX_ORA_URL and HX_API_KEY");let s=await fetch(`${o.HX_ORA_URL}/internal/outputs/${encodeURIComponent(e.flowId)}/${encodeURIComponent(e.sessionId)}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:o.HX_API_KEY},body:JSON.stringify({runId:e.runId,createdAt:e.createdAt,data:e.data,answerNodeIds:e.answerNodeIds})});if(!s.ok){let t=await s.text().catch(()=>"");throw new Error(`Structured output persistence failed with ${s.status}${t?`: ${t}`:""}`)}}var Me=async(o,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),`${JSON.stringify(o)}`};async function nt(o,e){var r,i;let s=o.id||o.name||"",[t,n]=String(s).split("::");if(!t||!n)return null;try{let d=(r=(await S(t,e)).metadata)==null?void 0:r.tenant,f=await B(t,e),u=(i=o.state)==null?void 0:i.user,p={flowData:{...f,tenant:d,flowId:t,chatId:n},executedNodes:[],context:u?{user:u}:{}};return o.setState({...o.state,engineState:p}),p}catch(l){return console.error("Failed to initialize engine state:",l),null}}async function rt(o){var M,b,F,$,j;let{agent:e,env:s,ctx:t,payload:n,connection:r}=o,i=Date.now(),l=[],d=o.runId?Pe():void 0,f=async()=>await X(e),u=async I=>{await ce(e,I)},p=async I=>{if(e.state.modelsCache&&e.state.modelsCache[I])return e.state.modelsCache[I];try{let{fetchOraModel:_}=await import("./oraApi-YIJGMXX7.js"),U=await _(I,s);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[I]:U}}),U}catch(_){throw console.error(`Error fetching model ${I}:`,_),_}},c={id:ho(),role:"user",type:"text",content:n.text,images:n.images,ts:Date.now()};await u(c);let m={onChangeState:I=>{e.setState({...e.state,engineState:I})},onServerEvent:async I=>{var _;await((_=o.onServerEvent)==null?void 0:_.call(o,I)),l.push(I)},onTelemetry:async I=>{var _,U,H,E,J,L;await Me({...I,userId:o.resolveUserId(),tenant:((U=(_=e.state.engineState)==null?void 0:_.flowData)==null?void 0:U.tenant)||"",flowId:((E=(H=e.state.engineState)==null?void 0:H.flowData)==null?void 0:E.flowId)||"",sessionId:((L=(J=e.state.engineState)==null?void 0:J.flowData)==null?void 0:L.chatId)||""},s)},onError:I=>{var _;(_=o.onError)==null||_.call(o,I),e.setState({...e.state,error:I})},shouldStop:o.shouldStop},a=e.state.engineState?{...e.state.engineState}:null;if(a){let{engineState:I,refreshed:_}=await _e(s,a);a=I,_&&e.setState({...e.state,engineState:a,modelsCache:{}})}else if(a=await nt(e,s),!a){let I="Failed to initialize agent";return m.onError(I),{status:"failed",error:I}}let g=o.secrets;if(!g||Object.keys(g).length===0){let I=(M=a.flowData)==null?void 0:M.tenant;g=I?await wt(s,I):{},(b=o.onSecretsLoaded)==null||b.call(o,g)}let y=o.user??e.state.user??void 0;y&&!((F=a.context)!=null&&F.user)&&(a.context={...a.context||{},user:y});let h=dt(st(a)),w=typeof a.cycle=="number"?a.cycle:0;h.enabled&&(w=await he(e,a),a.cycle=w,e.setState({...e.state,engineState:a}));let x=Re(e,{env:s,ctx:t,conn:r,getMessages:f,setMessages:u,getOraModel:p,secrets:g,userAuth:o.userAuth,user:y,composioSessions:o.composioSessions,publicOrigin:o.publicOrigin,skillRefCache:o.skillRefCache,runId:o.runId,outputCollector:d},a,w,o.onMemoryRef),R=await Oe(x,a,m)(n);if(R.status==="completed"&&o.runId&&(d!=null&&d.hasOutputs())){let{flowId:I,chatId:_}=a.flowData??{};if(!I||!_)R={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await Fe(s,{flowId:I,sessionId:_,runId:o.runId,createdAt:new Date(i).toISOString(),data:d.snapshotData(),answerNodeIds:d.answerNodeIds()});let U={...a.results||{}};for(let H of d.answerNodeIds())U[H]={...U[H]||{},persisted:!0,runId:o.runId};a={...a,results:U},e.setState({...e.state,engineState:a})}catch(U){let H=U instanceof Error?U.message:"Structured output persistence failed";m.onError(H),await m.onServerEvent({type:"error:answer-output",content:{runId:o.runId,error:H},timestamp:Date.now()}),R={status:"failed",error:H}}}let{tenant:T,flowId:P,chatId:A}=a.flowData??{};return T&&P&&A&&t.waitUntil($e(s,{id:`${P}::${A}`,tenant:T,flowId:P,sessionId:A,userId:o.resolveUserId(),title:($=n.text)==null?void 0:$.slice(0,120),turnTs:i,events:l})),R.status==="completed"&&((j=x.memoryConfig)!=null&&j.enabled)&&x.memoryConfig.mode==="summarize"&&t&&t.waitUntil(Qt(e,x,w)),e.setState({...e.state,lastUpdated:new Date}),{status:R.status,error:R.error,engineState:a}}import{nanoid as Ro}from"nanoid";function xo(o){let e=o.headers.get("X-User-Payload");if(!e)return null;try{let s=JSON.parse(e),t=typeof(s==null?void 0:s.email)=="string"?tt(s.email):null;return t?{...s,email:t}:null}catch{return null}}async function De(o,e,s,t){var n;try{let r=await e.json(),i=r.message;if(!i||typeof i!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let l=typeof r.userId=="string"?tt(r.userId):null,d=xo(e),f=d==null?void 0:d.email;d?o.setState({...o.state,user:d,injectedUserId:f}):l&&!((n=o.state.user)!=null&&n.email)&&o.setState({...o.state,injectedUserId:l});let u=()=>f??l??o.state.injectedUserId??void 0;o.skillRefCache||(o.skillRefCache=new Map);let p=r.inputs&&typeof r.inputs=="object"?r.inputs:void 0;if(!o.state.engineState&&!await nt(o,s))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let c=f?`run-${Ro(12)}`:null;c&&(await o.registerManualRun(c,i,f),await ot(s,c).catch(y=>{console.warn(`[AgentHTTP] could not mark manual run ${c} as running`,y)}));let m;try{m=await rt({agent:o,env:s,ctx:t,payload:{text:i,inputs:p},skillRefCache:o.skillRefCache,user:d??void 0,resolveUserId:u,runId:c??void 0,shouldStop:c?()=>o.isRunStopRequested(c):void 0}),c&&t.waitUntil(o.completeManualRun(c,m.status==="completed"?"succeeded":m.status==="stopped"?"skipped":"failed",m.error))}finally{c&&await o.clearRunStopRequest(c)}if(m.status==="failed")return new Response(JSON.stringify({error:m.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});if(m.status==="stopped")return new Response(JSON.stringify({error:m.error||"Stopped by user"}),{status:409,headers:{"content-type":"application/json"}});let g=(await X(o)).reverse().find(y=>y.role==="assistant");return new Response(JSON.stringify({answer:(g==null?void 0:g.content)||""}),{headers:{"content-type":"application/json"}})}catch(r){return new Response(JSON.stringify({error:r.message}),{status:500,headers:{"content-type":"application/json"}})}}async function Ue(o){try{return await ut(o),await mt(o),o.skillRefCache&&o.skillRefCache.clear(),o.setState({...o.state,error:"",engineState:void 0,modelsCache:{},lastUpdated:new Date}),new Response(JSON.stringify({success:!0,messages:[]}),{headers:{"content-type":"application/json"}})}catch(e){return new Response(JSON.stringify({error:e.message}),{status:500,headers:{"content-type":"application/json"}})}}var ke="trigger:nonce:",No=900*1e3,bt="run:stop:",be=class extends Io{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{}};resolveSessionUserId(){var e;return((e=this.state.user)==null?void 0:e.email)??this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async inspectPersistedSession(e){return e==="state"?{state:this.state}:e==="messages"?{messages:await X(this)}:{context:await de(this)}}async requestRunStop(e){return e!=null&&e.trim()?(await this.ctx.storage.put(`${bt}${e}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(e){return!!await this.ctx.storage.get(`${bt}${e}`)}async clearRunStopRequest(e){await this.ctx.storage.delete(`${bt}${e}`)}async onRequest(e){let s=new URL(e.url);if(s.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(s.pathname.endsWith("/history")){let t=await X(this);return new Response(JSON.stringify(t),{headers:{"content-type":"application/json"}})}if(s.pathname.endsWith("/context")){let t={"content-type":"application/json","access-control-allow-origin":"*"};if(!e.headers.get("X-User-Payload"))return new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:t});let n=s.searchParams.get("ref");if(n){let i=await ft(this,n);return i?new Response(JSON.stringify({entry:i}),{headers:t}):new Response(JSON.stringify({error:"Not found"}),{status:404,headers:t})}let r=await pt(this);return new Response(JSON.stringify({entries:r}),{headers:t})}return e.method==="POST"&&s.pathname.endsWith("/message")?De(this,e,this.env,this.ctx):e.method==="DELETE"&&s.pathname.endsWith("/clear")?Ue(this):new Response("Ready to assist.")}async onConnect(e,s){var c,m,a,g,y;let[t,n]=e.server.split("::"),i=(c=(await S(t,this.env)).metadata)==null?void 0:c.tenant;this.secrets=await wt(this.env,i),this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let l=null;if(s.request){try{this.publicOrigin=new URL(s.request.url).origin}catch{}let h=s.request.headers.get("X-User-Payload");if(h)try{l=JSON.parse(h)}catch(w){console.warn("Failed to parse X-User-Payload",w)}}let d=await B(t,this.env);this.setState({...this.state,user:l||null,sessionId:n,engineState:{flowData:{...d,tenant:i,flowId:t,chatId:n},executedNodes:[],context:l?{user:l}:{}}}),l||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let f=await X(this);k(e,D.SERVER_HISTORY,JSON.stringify({messages:f}));let p=(((m=d==null?void 0:d.state)==null?void 0:m.nodes)??(d==null?void 0:d.nodes)??[]).find(h=>h.type==="startNode");if(p){let h={allow_images:((a=p.data)==null?void 0:a.allow_images)??!1,allow_documents:((g=p.data)==null?void 0:g.allow_documents)??!1,greeting:(y=p.data)==null?void 0:y.greeting};k(e,D.SERVER_CONFIG,JSON.stringify(h))}}async onMessage(e,s){if(typeof s!="string")return;let t=s.indexOf(":");if(t===-1)return;let n=s.substring(0,t),r=s.substring(t+1);if(!n||!r)return;let l={[D.USER_MESSAGE]:d=>this.onUserMessage(e,d),[D.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[D.USER_AUTH]:d=>this.onUserAuth(e,d),[D.USER_IDENTITY]:d=>this.onUserIdentity(e,d)}[n];l&&await l(r)}async onUserMessage(e,s){let t=ct(s),n=this.hasAuditableUser()?`run-${To(12)}`:null;n&&(await this.registerManualRun(n,t.text),await ot(this.env,n).catch(r=>{console.warn(`[AgentDO] could not mark manual run ${n} as running`,r)}));try{let r=await rt({agent:this,env:this.env,ctx:this.ctx,payload:t,connection:e,secrets:this.secrets,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:this.state.user,resolveUserId:()=>this.resolveSessionUserId(),runId:n??void 0,shouldStop:n?()=>this.isRunStopRequested(n):void 0,onServerEvent:i=>{k(e,D.SERVER_EVENT,JSON.stringify(i))},onError:i=>{k(e,D.SERVER_ERROR,i)},onMemoryRef:i=>{k(e,D.SERVER_EVENT,JSON.stringify({type:"info:memory:updated",content:{ref:i}}))},onSecretsLoaded:i=>{this.secrets=i}});n&&this.ctx.waitUntil(this.completeManualRun(n,r.status==="completed"?"succeeded":r.status==="stopped"?"skipped":"failed",r.error))}finally{n&&await this.clearRunStopRequest(n)}}hasAuditableUser(e){var s;return!!(e||(s=this.state.user)!=null&&s.email)}registerManualRun(e,s,t){var d,f;let{tenant:n,flowId:r,chatId:i}=((d=this.state.engineState)==null?void 0:d.flowData)??{},l=t||((f=this.state.user)==null?void 0:f.email);return!n||!r||!i||!l?Promise.resolve():ye(this.env,{id:e,tenant:n,flowId:r,userId:l,sessionId:i,label:s==null?void 0:s.slice(0,120)})}completeManualRun(e,s,t){return yt(this.env,e,{status:s,error:t})}async enqueueTrigger(e){var n;if(!(e!=null&&e.runId)||!(e!=null&&e.flowId))return{queued:!1};if(e.nonce&&!await this.claimTriggerNonce(e.nonce))return console.warn(`[AgentDO] rejected replayed trigger nonce ${e.nonce}`),{queued:!1,duplicate:!0};let s=e.runAsUserId;return s&&!((n=this.state.user)!=null&&n.email)&&this.state.injectedUserId!==s&&this.setState({...this.state,injectedUserId:s}),{queued:!0,taskId:await this.queue("processTrigger",e)}}async claimTriggerNonce(e){let s=`${ke}${e}`;if(await this.ctx.storage.get(s))return!1;let t=Date.now();await this.ctx.storage.put(s,t);let r=[...(await this.ctx.storage.list({prefix:ke})).entries()].filter(([,i])=>t-i>No).map(([i])=>i);return r.length>0&&await this.ctx.storage.delete(r),!0}async processTrigger(e){if(!(await ot(this.env,e.runId)).claimed){console.warn(`[AgentDO] activation ${e.activationId} skipped \u2014 run ${e.runId} already claimed`);return}try{this.state.engineState||await nt(this,this.env);let t=Z(st(this.state.engineState)),n=qt(t,e.inputs||{},e.label),r=await rt({agent:this,env:this.env,ctx:this.ctx,payload:{text:n,inputs:e.inputs||{}},secrets:this.secrets,composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>e.runAsUserId||this.resolveSessionUserId(),runId:e.runId,shouldStop:()=>this.isRunStopRequested(e.runId),onSecretsLoaded:i=>{this.secrets=i}});await yt(this.env,e.runId,{status:r.status==="completed"?"succeeded":r.status==="stopped"?"skipped":"failed",error:r.error})}catch(t){let n=t instanceof Error?t.message:"Trigger execution failed";throw await yt(this.env,e.runId,{status:"failed",error:n}),t}finally{await this.clearRunStopRequest(e.runId)}}async onUserIdentity(e,s){let t=tt(s);if(!t){k(e,D.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:t}),k(e,D.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,s){let t=Vt(s);if(!t){k(e,D.SERVER_ERROR,"Invalid auth payload");return}let n=t.value.trim();n===""?delete this.userAuth[t.name]:this.userAuth[t.name]=t.value,k(e,D.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:t.name,set:n!==""}}))}async onClearHistory(e){await ut(this),await mt(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear();let s=this.state.engineState?{...this.state.engineState,cycle:void 0}:void 0;this.setState({...this.state,error:"",engineState:s,modelsCache:{},lastUpdated:new Date}),e&&k(e,D.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await ge(this);let e=await X(this);`${JSON.stringify(e)}`}async onClose(e,s,t,n){console.log(`Session closed: ${this.state.sessionId} ${s} - ${t}`)}async onError(e){console.error("AgentDO encountered an error:",e)}};function hr(o){let e=o.state;if(!e)return null;let s=["startNode","answerNode"];for(let t of s)if(!e.nodes.some(r=>r.type===t))return!1;return e.nodes.find(t=>t.type==="startNode")}import{importSPKI as Co,jwtVerify as Ao}from"jose";function Ee(o){let e={};if(!o)return e;let s=o.split(";");for(let t of s){let n=t.indexOf("=");if(n>-1){let r=t.slice(0,n).trim(),i=t.slice(n+1).trim();r&&(e[r]=decodeURIComponent(i))}}return e}function Oo(o){return(typeof o.email=="string"?o.email.trim():"")||null}async function z(o,e,s){let t=Ee(o.headers.get("cookie")),n=new URL(o.url),r=t.access_token||n.searchParams.get("access_token"),i=await _o(e,r);if(i.ok){let l=i.payload,d=Oo(l);return d?{id:l.sub,email:d,name:l.name,first_name:l.given_name,last_name:l.family_name,tenant:l.tenant,roles:l["ora-roles"],db_name:l.db_name||null,user_id:l.user_id||null}:null}return null}async function _o(o,e){if(!e||typeof e!="string")return{ok:!1,payload:null,protectedHeader:null};if(!o.KC_RS256_PK)throw new Error("PK is not defined");let s=`-----BEGIN PUBLIC KEY-----
|
|
39
|
+
`):"";e.context={user_input:x,user_images:O,files:E},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:F,error:_}=So(e.flowData);if(!F)g="failed",l=_||"Flow Format Error",(c=n==null?void 0:n.onError)==null||c.call(n,l);else{let C=tt(F.data),{values:$,errors:T}=Bt(C,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:$,...$},e.context.user_input||(e.context.user_input=x),await r(F),(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:Kt,classifierNode:St,llmNode:qt,memoNode:Xt,answerNode:Ut,apiNode:Et,toolNode:Ht};return a}var Ct=class extends Error{constructor(){super("Stopped by user"),this.name="FlowExecutionStoppedError"}};function So(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=de(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 a=Le(e.id,r),d=new Set;for(let l of s){let f=Le(l.id,i);for(let c of f)d.add(c)}let u=[];for(let l of a)if(!d.has(l)){let f=t.nodes.find(c=>c.id===l);if(f){let c=((g=f.data)==null?void 0:g.label)||"";u.push(`${l}(${c},${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 Le(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 Vo(o,t){var n;return((n=o.state)==null?void 0:n.nodes.find(e=>e.id===t))||null}function qo(o,t,n){var a;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"&&((a=n==null?void 0:n.context)!=null&&a.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 Vo(t,r)}async function Se(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}},a=r==null?void 0:r.stateVersion,d=typeof a=="number"&&a!==((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 Ve(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 qe(){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 Xo(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function Xe(o,t){if(!Xo(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 Ke=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;let n=o.id||o.name||"",[e,s]=String(n).split("::");if(!e||!s)return null;try{let a=(r=(await W(e,t)).metadata)==null?void 0:r.tenant,u={flowData:{...await Z(e,t),tenant:a,flowId:e,chatId:s},executedNodes:[],context:{}};return o.setState({...o.state,engineState:u}),u}catch(i){return console.error("Failed to initialize engine state:",i),null}}async function ct(o){var U,E,F,_;let{agent:t,env:n,ctx:e,payload:s,connection:r}=o,i=Date.now(),a=[],d=o.runId?qe():void 0,u=async()=>await z(t),p=async C=>{await Re(t,C)},g=async C=>{if(t.state.modelsCache&&t.state.modelsCache[C])return t.state.modelsCache[C];try{let{fetchOraModel:$}=await import("./oraApi-4O3W5LXD.js"),T=await $(C,n);return t.setState({...t.state,modelsCache:{...t.state.modelsCache||{},[C]:T}}),T}catch($){throw console.error(`Error fetching model ${C}:`,$),$}},l={id:Ko(),role:"user",type:"text",content:s.text,images:s.images,ts:Date.now()};await p(l);let f={onChangeState:C=>{t.setState({...t.state,engineState:C})},onServerEvent:async C=>{var $;await(($=o.onServerEvent)==null?void 0:$.call(o,C)),a.push(C)},onTelemetry:async C=>{var $,T,P,H,b,X;await Ke({...C,userId:o.resolveUserId(),tenant:((T=($=t.state.engineState)==null?void 0:$.flowData)==null?void 0:T.tenant)||"",flowId:((H=(P=t.state.engineState)==null?void 0:P.flowData)==null?void 0:H.flowId)||"",sessionId:((X=(b=t.state.engineState)==null?void 0:b.flowData)==null?void 0:X.chatId)||""},n)},onError:C=>{var $;($=o.onError)==null||$.call(o,C),t.setState({...t.state,error:C})},shouldStop:o.shouldStop},c=t.state.engineState?{...t.state.engineState}:null;if(c){let{engineState:C,refreshed:$}=await Se(n,c);c=C,$&&t.setState({...t.state,engineState:c,modelsCache:{}})}else if(c=await at(t,n),!c){let C="Failed to initialize agent";return f.onError(C),{status:"failed",error:C}}let m=o.secrets;if(!m||Object.keys(m).length===0){let C=(U=c.flowData)==null?void 0:U.tenant;m=C?await Nt(n,C):{},(E=o.onSecretsLoaded)==null||E.call(o,m)}let y=o.user??void 0;c={...c,context:{...c.context||{},user:y}},t.setState({...t.state,user:y,engineState:c});let w=pt(it(c)),h=typeof c.cycle=="number"?c.cycle:0;w.enabled&&(h=await Fe(t,c),c.cycle=h,t.setState({...t.state,engineState:c}));let I=De(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},c,h,o.onMemoryRef),R=await He(I,c,f)(s);if(R.status==="completed"&&o.runId&&(d!=null&&d.hasOutputs())){let{flowId:C,chatId:$}=c.flowData??{};if(!C||!$)R={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await Xe(n,{flowId:C,sessionId:$,runId:o.runId,createdAt:new Date(i).toISOString(),data:d.snapshotData(),answerNodeIds:d.answerNodeIds()});let T={...c.results||{}};for(let P of d.answerNodeIds())T[P]={...T[P]||{},persisted:!0,runId:o.runId};c={...c,results:T},t.setState({...t.state,engineState:c})}catch(T){let P=T instanceof Error?T.message:"Structured output persistence failed";f.onError(P),await f.onServerEvent({type:"error:answer-output",content:{runId:o.runId,error:P},timestamp:Date.now()}),R={status:"failed",error:P}}}let{tenant:x,flowId:O,chatId:A}=c.flowData??{};return x&&O&&A&&e.waitUntil(Ve(n,{id:`${O}::${A}`,tenant:x,flowId:O,sessionId:A,userId:o.resolveUserId(),title:(F=s.text)==null?void 0:F.slice(0,120),turnTs:i,events:a})),R.status==="completed"&&((_=I.memoryConfig)!=null&&_.enabled)&&I.memoryConfig.mode==="summarize"&&e&&e.waitUntil(ce(t,I,h)),t.setState({...t.state,lastUpdated:new Date}),{status:R.status,error:R.error,engineState:c}}import{nanoid as Jo}from"nanoid";function zo(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 Je(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 a=typeof r.userId=="string"?nt(r.userId):null,d=zo(t),u=d==null?void 0:d.email;d?o.setState({...o.state,user:d,injectedUserId:u}):a&&!((s=o.state.user)!=null&&s.email)&&o.setState({...o.state,injectedUserId:a});let p=()=>u??a??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-${Jo(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 ze(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 We="trigger:nonce:",Wo=900*1e3,Jt="run:stop:",Ye=class extends Ge{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{}};constructor(t,n){super(t,n),this.requireStateValidation()}validateStateChange(t,n){if(n!=="server")throw new Error("Client state updates are forbidden")}requireStateValidation(){if(typeof Ge.prototype.validateStateChange!="function")throw new Error("AgentDO requires agents >= 0.8.7 with validateStateChange; upgrade the tenant SDK")}resolveSessionUserId(){return 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 Ie(this)}}async requestRunStop(t){return t!=null&&t.trim()?(await this.ctx.storage.put(`${Jt}${t}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(t){return!!await this.ctx.storage.get(`${Jt}${t}`)}async clearRunStopRequest(t){await this.ctx.storage.delete(`${Jt}${t}`)}async onRequest(t){this.requireStateValidation();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")?Je(this,t,this.env,this.ctx):t.method==="DELETE"&&n.pathname.endsWith("/clear")?ze(this):new Response("Ready to assist.")}async onConnect(t,n){var l,f,c,m,y;this.requireStateValidation();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 a=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{a=JSON.parse(w)}catch(h){console.warn("Failed to parse X-User-Payload",h)}}t.setState({...t.state,authorizedUser:a});let d=await Z(e,this.env);this.setState({...this.state,user:a||null,sessionId:s,engineState:{flowData:{...d,tenant:i,flowId:e,chatId:s},executedNodes:[],context:a?{user:a}:{}}}),a||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let u=await z(this);L(t,M.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:((c=g.data)==null?void 0:c.allow_images)??!1,allow_documents:((m=g.data)==null?void 0:m.allow_documents)??!1,greeting:(y=g.data)==null?void 0:y.greeting};L(t,M.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 a={[M.USER_MESSAGE]:d=>this.onUserMessage(t,d),[M.USER_CLEAR_HISTORY]:()=>this.onClearHistory(t),[M.USER_AUTH]:d=>this.onUserAuth(t,d),[M.USER_IDENTITY]:d=>this.onUserIdentity(t,d)}[s];a&&await a(r)}async onUserMessage(t,n){var a;let e=dt(n),s=((a=t.state)==null?void 0:a.authorizedUser)??void 0,r=()=>(s==null?void 0:s.email)??this.resolveSessionUserId(),i=`run-${Go(12)}`;await this.registerManualRun(i,e.text,r()),await rt(this.env,i).catch(d=>{console.warn(`[AgentDO] could not mark manual run ${i} as running`,d)});try{let d=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:s,resolveUserId:r,runId:i,shouldStop:()=>this.isRunStopRequested(i),onServerEvent:u=>{L(t,M.SERVER_EVENT,JSON.stringify(u))},onError:u=>{L(t,M.SERVER_ERROR,u)},onMemoryRef:u=>{L(t,M.SERVER_EVENT,JSON.stringify({type:"info:memory:updated",content:{ref:u}}))},onSecretsLoaded:u=>{this.secrets=u}});this.ctx.waitUntil(this.completeManualRun(i,d.status==="completed"?"succeeded":d.status==="stopped"?"skipped":"failed",d.error))}finally{await this.clearRunStopRequest(i)}}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 a=_e(e||this.resolveSessionUserId(),i);return $e(this.env,{id:t,tenant:s,flowId:r,userId:a,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=`${We}${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:We})).entries()].filter(([,i])=>e-i>Wo).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=Qt(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){L(t,M.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:e}),L(t,M.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(t,n){let e=Zt(n);if(!e){L(t,M.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,M.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&&L(t,M.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await Oe(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 mi(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 Yo,jwtVerify as Bo}from"jose";function Ot(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 Qo(o){return(typeof o.email=="string"?o.email.trim():"")||null}async function Y(o,t,n){let e=Ot(o.headers.get("cookie")),s=new URL(o.url),r=e.access_token||s.searchParams.get("access_token"),i=await Zo(t,r);if(i.ok){let a=i.payload,d=Qo(a);return d?{id:a.sub,email:d,name:a.name,first_name:a.given_name,last_name:a.family_name,tenant:a.tenant,org:typeof a.org=="string"?a.org:null,roles:a["ora-roles"],db_name:a.db_name||null,user_id:a.user_id||null}:null}return null}async function Zo(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-----`,
|
|
42
|
-
`)}async function Je(o,e){let s=await crypto.subtle.importKey("raw",je.encode(o),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return Po(await crypto.subtle.sign("HMAC",s,je.encode(e)))}function Mo(o,e){if(o.length!==e.length)return!1;let s=0;for(let t=0;t<o.length;t++)s|=o.charCodeAt(t)^e.charCodeAt(t);return s===0}async function Fr(o){let e=String(o.timestamp??Math.floor(Date.now()/1e3)),s=await Je(o.secret,Xe({timestamp:e,nonce:o.nonce,tenant:o.tenant,destination:o.destination,body:o.body}));return{"content-type":"application/json",[Ke]:o.tenant,[qe]:e,[Ve]:o.nonce,[He]:`v1=${s}`}}async function Se(o){var f,u,p,c,m;if(!((f=o.secret)!=null&&f.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(u=o.headers.get(Ke))==null?void 0:u.trim(),s=(p=o.headers.get(qe))==null?void 0:p.trim(),t=(c=o.headers.get(Ve))==null?void 0:c.trim(),n=(m=o.headers.get(He))==null?void 0:m.trim();if(!e||!s||!t||!n)return{ok:!1,error:"missing signature headers"};if(!n.startsWith("v1="))return{ok:!1,error:"unsupported signature version"};let r=Number(s);if(!Number.isFinite(r))return{ok:!1,error:"invalid timestamp"};let i=Math.floor((o.now??Date.now())/1e3),l=o.toleranceSeconds??300;if(Math.abs(i-r)>l)return{ok:!1,error:"stale timestamp"};let d=await Je(o.secret.trim(),Xe({timestamp:s,nonce:t,tenant:e,destination:o.url,body:o.body}));return Mo(n.slice(3),d)?{ok:!0,tenant:e,nonce:t,timestamp:r}:{ok:!1,error:"signature mismatch"}}var K=(o,e=200)=>new Response(JSON.stringify(o),{status:e,headers:{"content-type":"application/json"}});async function Ge(o,e,s){var f;if(new URL(o.url).pathname!=="/api/triggers/dispatch")return;if(o.method!=="POST")return K({error:"Method not allowed"},405);let n=await o.text(),r=await Se({secret:e.HX_API_KEY,body:n,url:o.url,headers:o.headers});if(!r.ok)return console.warn(`[triggers] rejected dispatch: ${r.error}`),K({error:"Invalid signature"},401);let i;try{i=JSON.parse(n)}catch{return K({error:"Invalid payload"},400)}if(!(i!=null&&i.runId)||!(i!=null&&i.flowId)||!(i!=null&&i.runAsUserId)||!(i!=null&&i.tenant)||!(i!=null&&i.activationId)||!(i!=null&&i.triggerId)||!(i!=null&&i.triggerKind)||!(i!=null&&i.invocationMode))return K({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(i.tenant!==r.tenant)return K({error:"Tenant mismatch"},403);let l;try{l=await S(i.flowId,e)}catch{return K({error:"Flow not found"},404)}if(!((f=l==null?void 0:l.metadata)!=null&&f.tenant)||l.metadata.tenant!==i.tenant)return console.warn(`[triggers] flow ${i.flowId} does not belong to tenant ${i.tenant}`),K({error:"Tenant mismatch"},403);let d=await Le(e,{...i,sessionId:i.sessionId||i.runAsUserId,nonce:r.nonce});return d.status==="error"?K({error:d.error},502):d.status==="deduped"?K({deduped:!0,runId:d.runId},200):K({accepted:!0,runId:d.runId,taskId:d.taskId},202)}var Do=/^[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}$/,Uo=new Set(["state","messages","context"]);async function ko(o,e){let s=new URL(o.url);if(!s.pathname.startsWith("/api/internal/sessions/"))return;let t=s.pathname.split("/");if(t[6]!=="runs"||t[8]!=="stop"||t.length!==9)return;if(o.method!=="POST")return new Response("Method not allowed",{status:405});if(!e.HX_API_KEY||o.headers.get("Authorization")!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let n=decodeURIComponent(t[4]||""),r=decodeURIComponent(t[5]||""),i=decodeURIComponent(t[7]||"");if(!n||!r||!i)return new Response("Not found",{status:404});try{let l=await Rt(e.AGENT,`${n}::${r}`);return Response.json(await l.requestRunStop(i))}catch(l){return console.error("[agents] failed to request run stop",l),Response.json({error:"Failed to stop run"},{status:502})}}async function bo(o,e){let s=new URL(o.url);if(!s.pathname.startsWith("/api/internal/sessions/"))return;if(o.method!=="GET")return new Response("Method not allowed",{status:405});let t=o.headers.get("Authorization")||"";if(!e.HX_API_KEY||t!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let n=s.pathname.split("/"),r=decodeURIComponent(n[4]||""),i=decodeURIComponent(n[5]||""),l=n[6];if(!r||!i||!l||!Uo.has(l))return new Response("Not found",{status:404});try{let f=await(await Rt(e.AGENT,`${r}::${i}`)).inspectPersistedSession(l);return Response.json(f)}catch(d){return console.error("[agents] failed to inspect persisted session",d),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function qr(o,e,s){var l,d,f,u;let t=new URL(o.url),n=await Ge(o,e,s);if(n instanceof Response)return n;let r=await ko(o,e);if(r instanceof Response)return r;let i=await bo(o,e);if(i instanceof Response)return i;if(t.pathname.startsWith("/a/")){let p=t.pathname.split("/"),c=p[2],m=p[3];try{if(!c)return Response.redirect(new URL("/",t.origin).toString(),302);let a;try{a=await S(c,e)}catch{return new Response("Flow not found",{status:404})}if(!a.metadata||((l=a.metadata)==null?void 0:l.status)!=="active")return new Response("NO chat",{status:404});if(((d=a.metadata)==null?void 0:d.visibility)==="private"&&!await z(o,e,s)){let y=new URL("/login",t.origin);return y.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(y.toString(),302)}if(!m){let g=crypto.randomUUID(),y=new URL(`/a/${c}/${g}`,t.origin);return Response.redirect(y.toString(),302)}if(!Do.test(m))return new Response("Id del chat no v\xE1lido",{status:400})}catch(a){return console.error("Error accessing flow KV:",a),new Response("Flow error",{status:500})}}if(t.pathname.startsWith("/api/agent/flow")){let p=t.pathname.split("/"),c=p[4],m=p[5],a=`${c}::${m}`;try{let g=await z(o,e,s);if(!g){let R=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${R}) \u2014 Composio connections from tool editor will not apply`)}let y=new Headers(o.headers);y.delete("X-User-Payload"),g&&y.set("X-User-Payload",JSON.stringify(g));let h=new Request(o,{headers:y});return(await Rt(e.AGENT,a)).fetch(h)}catch(g){return console.error("Error accessing agent:",g),new Response("Agent error",{status:500})}}if(t.pathname.startsWith("/api/ora/connect")){let p=t.pathname.split("/"),c=p[4],m=p[5];if(!c||!m)return new Response("Missing flowId or sessionId",{status:400});let a=o.headers.get("Authorization")||t.searchParams.get("authorization");if(!a)return new Response("Missing Authorization header",{status:401});try{let g=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${c}`,h=await(await fetch(g,{method:"GET",headers:{Authorization:a}})).json();if(((f=h.payload)==null?void 0:f.flowId)!==c)return console.error("FlowId mismatch:",(u=h.payload)==null?void 0:u.flowId,"!==",c),new Response("Validation error",{status:403});let w=`${c}::${m}`,x=await z(o,e,s);if(!x){let M=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${M}) \u2014 Composio connections from tool editor will not apply`)}let R=new Headers(o.headers);R.delete("X-User-Payload"),x&&R.set("X-User-Payload",JSON.stringify(x));let T=new Request(o,{headers:R});return(await Rt(e.AGENT,w)).fetch(T)}catch(g){return console.error("Error in /api/ora/connect:",g),new Response("Internal error",{status:500})}}}async function Xr(o,e,s){let t=new URL(o.url),n=o.method;if(!t.pathname.startsWith("/api/instances"))return;let r=await z(o,e,s);if(!r)return new Response("Unauthorized",{status:401});let i=e.HX_CORE_URL,l=e.HX_API_KEY;if(!i||!l)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let f=t.pathname.slice("/api/instances".length);f.startsWith("/")&&(f=f.slice(1)),f.endsWith("/")&&(f=f.slice(0,-1));let u="/ora/instances";f&&(u+=`/${f}`);let p=i.endsWith("/")?i.slice(0,-1):i,c=new URL(`${p}${u}`);t.searchParams.forEach((g,y)=>{c.searchParams.set(y,g)}),n==="GET"&&!f&&c.searchParams.set("filter_user_id",r.email);let m=new Headers;m.set("Authorization",l),m.set("Content-Type","application/json"),m.set("X-User-Payload",JSON.stringify(r));let a={method:n,headers:m};if(["POST","PATCH","PUT"].includes(n))try{a.body=await o.text()}catch(g){console.error("Error reading request body:",g)}try{let g=await fetch(c.toString(),a),y=await g.text();return new Response(y,{status:g.status,headers:{"Content-Type":"application/json"}})}catch(g){return console.error("Error proxying to flow instance backend:",g),new Response("Internal Server Error",{status:500})}}async function Gr(o,e,s){let t=new URL(o.url);if(o.method==="POST"&&t.pathname==="/auth/login")try{let n=await o.formData(),r=n.get("username"),i=n.get("password"),l=n.get("nextURL")||"/";if(!r||!i)return new Response("Missing username or password",{status:400});let d=new URLSearchParams;d.append("username",r),d.append("password",i),d.append("grant_type","password"),d.append("client_id",e.KC_CLIENT_ID),d.append("client_secret",e.KC_CLIENT_SECRET);let f=await fetch(`${e.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:d});if(!f.ok)return new Response("Unauthorized",{status:401});let u=await f.json(),p=new Response(null,{status:302,headers:{Location:l}}),c=(m,a,g)=>{p.headers.append("Set-Cookie",`${m}=${a}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${g}`)};return u.access_token&&c("access_token",u.access_token,u.expires_in),u.refresh_token&&c("refresh_token",u.refresh_token,u.refresh_expires_in||3600*24*30),u.id_token&&c("id_token",u.id_token,u.expires_in),p}catch(n){return console.error("Auth error:",n),new Response("Internal Server Error",{status:500})}if(t.pathname==="/auth/logout"){let n=new Response(null,{status:302,headers:{Location:"/login"}}),r=i=>{n.headers.append("Set-Cookie",`${i}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return r("access_token"),r("refresh_token"),r("id_token"),n}if(t.pathname.startsWith("/s/")){let n=await z(o,e,s);if(!n){let r=new URL("/login",t.origin);return r.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(r.toString(),302)}return{user:n}}}export{be as AgentDO,Xo as FLOW_INPUT_NAME_RE,ht as FlowExecutionStoppedError,So as GENERATION_PARAM_KEYS,zo as GENERATION_PRESETS,Jo as MAX_USER_IDENTITY_LENGTH,ls as MODEL_REGISTRY_SNAPSHOT,Q as NodeType,Go as PRESET_PARAM_KEYS,ss as REASONING_EFFORT_LEVELS,ee as TOOL_REGISTRY_SNAPSHOT,Ve as TRIGGER_NONCE_HEADER,He as TRIGGER_SIGNATURE_HEADER,Pr as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,Ke as TRIGGER_TENANT_HEADER,qe as TRIGGER_TIMESTAMP_HEADER,Bo as applyPresetToOverrides,Gt as buildReasoningProviderOptions,Fr as buildSignedTriggerHeaders,qt as buildTriggerMessageText,Ho as buildUrl,Oo as canonicalUserEmail,ot as claimRun,mt as clearAllContext,ut as clearAllMessages,yt as completeRun,Eo as convertTempMessure,Ct as createRun,fe as deleteContextToolsUpToCycle,Wo as deriveParamSupport,Le as dispatchTrigger,jt as embedText,ge as ensureAgentTables,Be as ensureContextTable,Ye as ensureMessagesTable,de as getAllContext,X as getAllMessages,ft as getContext,ue as getContextData,pt as getContextIndex,cs as getDefaultOutVars,G as getEffectiveOutVars,Z as getFlowInputDefs,me as getMaxContextCycle,ds as getModelEntry,qr as handleAgentsRoutes,Gr as handleAuthRoutes,Cr as handleCommonRoutes,Xr as handleIntancesRoutes,bo as handlePersistedSessionInspection,ko as handleSessionRunControl,Ge as handleTriggerRoutes,Vo as hashText,nt as initializeEngineState,se as jsonSchemaToZod,at as logc,D as messageTypes,Fo as normalizeDestination,Qo as normalizeEffectiveParams,Ht as normalizeFlowInputs,is as normalizeModelEntry,ns as normalizeReasoning,vo as openAiReasoningParamSupport,Zo as openAiStandardParamSupport,Ee as parseCookies,Vt as parseUserAuth,ct as parseUserMessage,Kt as pickNodeOverrides,rs as reasoningEffortLevels,Jt as reasoningExposable,ye as recordRun,as as registerProvider,to as resolveAnswerMappings,pe as resolveContextRef,lt as resolveModelById,v as resolveOutVarRef,Yo as resolvePreset,St as resolveReasoningEffort,te as resolveTemplate,rt as runAgentTurn,jo as safeParseJSON,tt as sanitizeUserIdentity,Me as sendEvent,k as serverSend,le as setContext,ce as setMessage,Je as signTriggerMaterial,Oe as startEngine,os as stripUnsupportedFromNodeData,Lo as tempTool,Mo as timingSafeEqualHex,Xt as toStreamTextSettings,Xe as triggerSignatureMaterial,qo as twitter,hr as validateFlowStart,Ko as vectorize,_o as verifyToken,Se as verifyTriggerRequest,z as verifyUser,vt as walkPath,es as workersAiParamSupport,ts as xaiParamSupport};
|
|
41
|
+
-----END PUBLIC KEY-----`,e=await Yo(n,"RS256");try{let{payload:s,protectedHeader:r}=await Bo(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 xi(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 _t}from"agents";import{getAgentByName as vo}from"agents";async function Be(o,t){let n=t.sessionId||t.runAsUserId,e=t.inputs||{},s=t.runId;if(!s){let d=await Dt(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},a=await(await vo(o.AGENT,`${t.flowId}::${n}`)).enqueueTrigger(r);return a.duplicate?{status:"deduped",runId:s}:a.queued?{status:"queued",runId:s,activation:r,taskId:a.taskId}:{status:"error",error:"Failed to queue trigger"}}var Ze="x-ora-signature",ve="x-ora-timestamp",to="x-ora-nonce",eo="x-ora-tenant",Ci=300,Qe=new TextEncoder;function tn(o){return[...new Uint8Array(o)].map(t=>t.toString(16).padStart(2,"0")).join("")}function en(o){try{let t=new URL(o);return`${t.origin}${t.pathname.replace(/\/$/,"")}`}catch{return o.replace(/\/$/,"")}}function oo(o){return["v1",o.timestamp,o.nonce,o.tenant,en(o.destination),o.body].join(`
|
|
42
|
+
`)}async function no(o,t){let n=await crypto.subtle.importKey("raw",Qe.encode(o),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return tn(await crypto.subtle.sign("HMAC",n,Qe.encode(t)))}function on(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 Oi(o){let t=String(o.timestamp??Math.floor(Date.now()/1e3)),n=await no(o.secret,oo({timestamp:t,nonce:o.nonce,tenant:o.tenant,destination:o.destination,body:o.body}));return{"content-type":"application/json",[eo]:o.tenant,[ve]:t,[to]:o.nonce,[Ze]:`v1=${n}`}}async function so(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(eo))==null?void 0:p.trim(),n=(g=o.headers.get(ve))==null?void 0:g.trim(),e=(l=o.headers.get(to))==null?void 0:l.trim(),s=(f=o.headers.get(Ze))==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),a=o.toleranceSeconds??300;if(Math.abs(i-r)>a)return{ok:!1,error:"stale timestamp"};let d=await no(o.secret.trim(),oo({timestamp:n,nonce:e,tenant:t,destination:o.url,body:o.body}));return on(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 ro(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 so({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 a;try{a=await W(i.flowId,t)}catch{return J({error:"Flow not found"},404)}if(!((u=a==null?void 0:a.metadata)!=null&&u.tenant)||a.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 Be(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 nn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function zt(o,t,n,e,s,r=!1){let i=(l,f)=>({response:new Response(l,{status:f})});if(!/^[A-Za-z0-9_-]+$/.test(e))return i("Invalid flowId",400);if((!r||s)&&(!s||!nn.test(s)))return i("Invalid sessionId",400);let a;try{a=await W(e,t)}catch{return i("Flow not found",404)}let d=a==null?void 0:a.metadata;if(!d||!["active","activo"].includes(d.status))return i("Flow not found",404);if(!t.TENANT||d.tenant!==t.TENANT)return i("Forbidden",403);let u=await Y(o,t,n),p=u&&typeof u=="object"?u:void 0;if(p&&p.tenant!==t.TENANT)return i("Forbidden",403);if(d.visibility==="public")return{user:p};if(!p){if(!r)return i("Unauthorized",401);let l=new URL(o.url),f=new URL("/login",l.origin);return f.searchParams.set("nextURL",`${l.pathname}${l.search}`),{response:Response.redirect(f.toString(),302)}}if((d.org||"default")!==(p.org||"default"))return i("Forbidden",403);let g=Ot(o.headers.get("cookie")).access_token||new URL(o.url).searchParams.get("access_token");if(!g)return i("Unauthorized",401);try{let l=await fetch(`${t.HX_CORE_URL}/flows/${encodeURIComponent(e)}`,{headers:{Authorization:g},cache:"no-store"});if(!l.ok||(await l.json()).id!==e)return i("Forbidden",403)}catch{return i("Forbidden",403)}return{user:p}}var sn=new Set(["state","messages","context"]);async function rn(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 a=await _t(t.AGENT,`${s}::${r}`);return Response.json(await a.requestRunStop(i))}catch(a){return console.error("[agents] failed to request run stop",a),Response.json({error:"Failed to stop run"},{status:502})}}async function an(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]||""),a=s[6];if(!r||!i||!a||!sn.has(a))return new Response("Not found",{status:404});try{let u=await(await _t(t.AGENT,`${r}::${i}`)).inspectPersistedSession(a);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 Si(o,t,n){var a,d;let e=new URL(o.url),s=await ro(o,t,n);if(s instanceof Response)return s;let r=await rn(o,t);if(r instanceof Response)return r;let i=await an(o,t);if(i instanceof Response)return i;if(e.pathname.startsWith("/a/")){let u=e.pathname.split("/"),p=u[2],g=u[3];try{if(!p)return Response.redirect(new URL("/",e.origin).toString(),302);let l=await zt(o,t,n,p,g,!0);if(l.response)return l.response;if(!g){let f=crypto.randomUUID(),c=new URL(`/a/${p}/${f}`,e.origin);return Response.redirect(c.toString(),302)}}catch(l){return console.error("Error accessing flow KV:",l),new Response("Flow error",{status:500})}}if(e.pathname.startsWith("/api/agent/flow/")){let u=e.pathname.split("/"),p=u[4],g=u[5],l=`${p}::${g}`;try{let f=await zt(o,t,n,p,g);if(f.response)return f.response;let c=f.user,m=new Headers(o.headers);m.delete("X-User-Payload"),c&&m.set("X-User-Payload",JSON.stringify(c));let y=new Request(o,{headers:m});return(await _t(t.AGENT,l)).fetch(y)}catch(f){return console.error("Error accessing agent:",f),new Response("Agent error",{status:500})}}if(e.pathname.startsWith("/api/ora/connect")){let u=e.pathname.split("/"),p=u[4],g=u[5];if(!p||!g)return new Response("Missing flowId or sessionId",{status:400});let l=o.headers.get("Authorization")||e.searchParams.get("authorization");if(!l)return new Response("Missing Authorization header",{status:401});try{let f=`${t.HX_CORE_URL}/p/v1/validation/key/agent/${p}`,m=await(await fetch(f,{method:"GET",headers:{Authorization:l}})).json();if(((a=m.payload)==null?void 0:a.flowId)!==p)return console.error("FlowId mismatch:",(d=m.payload)==null?void 0:d.flowId,"!==",p),new Response("Validation error",{status:403});let y=`${p}::${g}`,w=await Y(o,t,n);if(!w){let O=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${O}) \u2014 Composio connections from tool editor will not apply`)}let h=new Headers(o.headers);h.delete("X-User-Payload"),w&&h.set("X-User-Payload",JSON.stringify(w));let I=new Request(o,{headers:h});return(await _t(t.AGENT,y)).fetch(I)}catch(f){return console.error("Error in /api/ora/connect:",f),new Response("Internal error",{status:500})}}}async function Xi(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,a=t.HX_API_KEY;if(!i||!a)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",a),f.set("Content-Type","application/json"),f.set("X-User-Payload",JSON.stringify(r));let c={method:s,headers:f};if(["POST","PATCH","PUT"].includes(s))try{c.body=await o.text()}catch(m){console.error("Error reading request body:",m)}try{let m=await fetch(l.toString(),c),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 zi(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"),a=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:a}}),l=(f,c,m)=>{g.headers.append("Set-Cookie",`${f}=${c}; 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{uo as ANONYMOUS_RUN_USER_PREFIX,Ye as AgentDO,gn as FLOW_INPUT_NAME_RE,Ct as FlowExecutionStoppedError,wn as GENERATION_PARAM_KEYS,Rn as GENERATION_PRESETS,yn as MAX_USER_IDENTITY_LENGTH,Jn as MODEL_REGISTRY_SNAPSHOT,v as NodeType,bn as OUT_VAR_NAME_RE,hn as PRESET_PARAM_KEYS,kn as REASONING_EFFORT_LEVELS,ge as TOOL_REGISTRY_SNAPSHOT,to as TRIGGER_NONCE_HEADER,Ze as TRIGGER_SIGNATURE_HEADER,Ci as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,eo as TRIGGER_TENANT_HEADER,ve as TRIGGER_TIMESTAMP_HEADER,S as VariableResolutionError,Tn as applyPresetToOverrides,ne as buildReasoningProviderOptions,jn as buildScope,Oi as buildSignedTriggerHeaders,Qt as buildTriggerMessageText,un as buildUrl,Qo as canonicalUserEmail,rt as claimRun,xt as clearAllContext,wt as clearAllMessages,Tt as completeRun,cn as convertTempMessure,Dt as createRun,Ae as deleteContextToolsUpToCycle,xn as deriveParamSupport,Be as dispatchTrigger,Yt as embedText,Oe as ensureAgentTables,lo as ensureContextTable,co as ensureMessagesTable,Xn as extractTemplateReferences,Ln as findScopedSourceNode,Ie as getAllContext,z as getAllMessages,En as getAncestorNodeIds,Rt as getContext,Te as getContextData,ht as getContextIndex,Mn as getDefaultOutVars,ft as getEffectiveOutVars,tt as getFlowInputDefs,Ce as getMaxContextCycle,zn as getModelEntry,Hn as getRefTail,et as getUpstreamOutVars,Si as handleAgentsRoutes,zi as handleAuthRoutes,xi as handleCommonRoutes,Xi as handleIntancesRoutes,an as handlePersistedSessionInspection,rn as handleSessionRunControl,ro as handleTriggerRoutes,fn as hashText,at as initializeEngineState,Sn as isBinaryOutVar,me as jsonSchemaToZod,ot as logc,M as messageTypes,en as normalizeDestination,Nn as normalizeEffectiveParams,Bt as normalizeFlowInputs,Pn as normalizeModelEntry,Fn as normalizeReasoning,Cn as openAiReasoningParamSupport,An as openAiStandardParamSupport,Ot as parseCookies,qn as parseTemplateExpression,Zt as parseUserAuth,dt as parseUserMessage,vt as pickNodeOverrides,Dn as reasoningEffortLevels,ee as reasoningExposable,$e as recordRun,Un as registerProvider,go as resolveAnswerMappings,Ne as resolveContextRef,ut as resolveModelById,Vn as resolveOutVarRef,In as resolvePreset,oe as resolveReasoningEffort,K as resolveReference,_e as resolveRunUserId,ue as resolveTemplate,Kn as rewriteTemplateNodeRefs,ct as runAgentTurn,dn as safeParseJSON,nt as sanitizeUserIdentity,Ke as sendEvent,L as serverSend,xe as setContext,Re as setMessage,no as signTriggerMaterial,He as startEngine,$n as stripUnsupportedFromNodeData,ln as tempTool,on as timingSafeEqualHex,te as toStreamTextSettings,oo as triggerSignatureMaterial,pn as twitter,mi as validateFlowStart,de as validateOutVars,mn as vectorize,Zo as verifyToken,so as verifyTriggerRequest,Y as verifyUser,mt as walkPath,_n as workersAiParamSupport,On as xaiParamSupport};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d}from"./chunk-A2IRPAD4.js";import"./chunk-3TXHFKDN.js";export{c as fetchOraModel,d as fetchSkillRef,b as fetchToolCatalog,a as fetchToolDefs};
|
|
@@ -5,8 +5,10 @@ import type { ContextIndexEntry, ContextRow, ContextUpsertInput, MemoryConfig }
|
|
|
5
5
|
import type { TriggerActivation } from '../../common/types/trigger-types';
|
|
6
6
|
import type { FlowEngineState } from '../logic/FlowEngine';
|
|
7
7
|
import type { ComposioSessionMeta } from '../utils/composio';
|
|
8
|
+
import type { ToolCatalogEntry } from '../utils/oraApi';
|
|
8
9
|
import type { RunOutputCollector } from '../utils/oraOutputs';
|
|
9
10
|
import { type SecretsMap } from '../utils/secrets';
|
|
11
|
+
export type { ToolCatalogEntry };
|
|
10
12
|
export interface SessionEnv {
|
|
11
13
|
env?: Env;
|
|
12
14
|
ctx?: DurableObjectState;
|
|
@@ -28,6 +30,8 @@ export interface SessionEnv {
|
|
|
28
30
|
userAuth?: SecretsMap;
|
|
29
31
|
/** Custom tool definitions for the tenant, lazy-loaded on first custom-tool reference and cached for the session. Keyed by row.id. */
|
|
30
32
|
toolDefs?: Record<string, any>;
|
|
33
|
+
/** Curated tool catalog entries for the tenant, lazy-loaded and cached for the session. Keyed by entry id. */
|
|
34
|
+
toolCatalog?: Record<string, ToolCatalogEntry>;
|
|
31
35
|
/** In-memory cache for skill references fetched during this session. Keyed by toolId:refName. */
|
|
32
36
|
skillRefCache?: Map<string, string>;
|
|
33
37
|
/** Composio session metadata keyed by composio tool row id — reused within the agent chat session. */
|
|
@@ -36,7 +40,7 @@ export interface SessionEnv {
|
|
|
36
40
|
user?: UserInterface;
|
|
37
41
|
/** Origin derived from the WebSocket upgrade request (preferred over ORA_PUBLIC_URL for callbacks). */
|
|
38
42
|
publicOrigin?: string;
|
|
39
|
-
/** Auditable run currently executing
|
|
43
|
+
/** Auditable run currently executing, including turns from anonymous public sessions. */
|
|
40
44
|
runId?: string;
|
|
41
45
|
/** Turn-local structured output collector. Never persisted in Agent state. */
|
|
42
46
|
outputCollector?: RunOutputCollector;
|
|
@@ -62,7 +66,11 @@ export type PersistedSessionSectionResult = {
|
|
|
62
66
|
};
|
|
63
67
|
export declare class AgentDO extends Agent<Env, State> {
|
|
64
68
|
initialState: State;
|
|
65
|
-
|
|
69
|
+
constructor(ctx: DurableObjectState, env: Env);
|
|
70
|
+
/** Only the server may change SDK-synchronized state. Supported since agents 0.8.7. */
|
|
71
|
+
validateStateChange(_nextState: State, source: Connection | 'server'): void;
|
|
72
|
+
private requireStateValidation;
|
|
73
|
+
/** Declared anonymous identity only; authorized user comes from the connection/request. */
|
|
66
74
|
private resolveSessionUserId;
|
|
67
75
|
private secrets;
|
|
68
76
|
private userAuth;
|
|
@@ -88,8 +96,6 @@ export declare class AgentDO extends Agent<Env, State> {
|
|
|
88
96
|
onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
|
|
89
97
|
onMessage(connection: Connection, message: WSMessage): Promise<void>;
|
|
90
98
|
onUserMessage(connection: Connection, message: string): Promise<void>;
|
|
91
|
-
/** True while the session belongs to a signed-in user; anonymous sessions are not tracked. */
|
|
92
|
-
hasAuditableUser(userId?: string): boolean;
|
|
93
99
|
/** Registers a manual turn as a run so it shows up in history and notifications. */
|
|
94
100
|
registerManualRun(runId: string, text: string, requestUserId?: string): Promise<unknown>;
|
|
95
101
|
/** 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;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { SessionEnv } from '../core/AgentDO';
|
|
2
|
+
import type { FlowEngineEvent, FlowEngineState } from '../logic/FlowEngine';
|
|
3
|
+
import type { TelemetryEvent } from '../utils/telemetry';
|
|
4
|
+
export default function toolNodeRunner(sessionEnv: SessionEnv, node: any, engineState: FlowEngineState, onServerEvent?: (event: FlowEngineEvent) => void, onResult?: (key: string, result: any) => void, onChangeState?: (state: FlowEngineState) => void, onTelemetry?: (event: TelemetryEvent) => void): Promise<void>;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { SessionEnv } from '../core/AgentDO';
|
|
2
|
+
export type ComposioDirectToolResult = {
|
|
3
|
+
ok: boolean;
|
|
4
|
+
data?: unknown;
|
|
5
|
+
error?: string | null;
|
|
6
|
+
};
|
|
7
|
+
export declare function executeComposioCatalogTool(sessionEnv: SessionEnv, opts: {
|
|
8
|
+
toolSlug: string;
|
|
9
|
+
connectionScope: string;
|
|
10
|
+
/** Pinned version of the selected tool (preferred — from node.data.toolVersion). */
|
|
11
|
+
toolVersion?: string | null;
|
|
12
|
+
/** Catalog-level hint from toolkit snapshot (may be first-tool only). */
|
|
13
|
+
toolkitVersion?: string | null;
|
|
14
|
+
arguments: Record<string, unknown>;
|
|
15
|
+
}): Promise<ComposioDirectToolResult>;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { UserInterface } from '../../common/types/user-types';
|
|
2
|
+
/** Shared admission for the chat page and its HTTP/WebSocket transport. */
|
|
3
|
+
export declare function authorizeFlowChat(request: Request, env: Env, ctx: ExecutionContext, flowId: string, sessionId?: string, page?: boolean): Promise<{
|
|
4
|
+
response?: Response;
|
|
5
|
+
user?: UserInterface;
|
|
6
|
+
}>;
|
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
export declare function fetchToolDefs(env: Env): Promise<any[]>;
|
|
2
|
+
export type ToolCatalogEntry = {
|
|
3
|
+
id: string;
|
|
4
|
+
toolkitSlug: string;
|
|
5
|
+
toolkitVersion: string | null;
|
|
6
|
+
connectionScope: string;
|
|
7
|
+
label: string;
|
|
8
|
+
};
|
|
9
|
+
export declare function fetchToolCatalog(env: Env): Promise<ToolCatalogEntry[]>;
|
|
2
10
|
export declare function fetchOraModel(modelId: string, env: Env): Promise<any>;
|
|
3
11
|
export declare function fetchSkillRef(env: Env, toolId: string, refName: string): Promise<{
|
|
4
12
|
name: string;
|
|
@@ -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;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b}from"./chunk-
|
|
1
|
+
import{a,b}from"./chunk-W6DBEVOO.js";import"./chunk-A2IRPAD4.js";import"./chunk-3TXHFKDN.js";export{b as readSkillRef,a as skillTool};
|
package/package.json
CHANGED
package/dist/chunk-4WAWR4LB.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Composio as eo}from"@composio/core";import{VercelProvider as io}from"@composio/vercel";import{SessionPreset as J}from"@composio/core";function A(o,n){var t;return(n==null?void 0:n.trim())||((t=o.connectionScope)==null?void 0:t.trim())||void 0}function U(o){let n=o.trim();if(!n)throw new Error("Composio connection scope is required");return n}var q=/https:\/\/connect\.composio\.dev\/link\/[^\s)\]"']+/i,z=/"redirect_?[Uu]rl"\s*:\s*"(https?:\/\/[^"]+)"/;function Y(o){var t;let n=(t=o.publicOrigin)==null?void 0:t.trim();return n?n.replace(/\/$/,""):G(o.env)}function x(o){var i,e,s,c;let n=(e=(i=o.secrets)==null?void 0:i.COMPOSIO_API_KEY)==null?void 0:e.trim();if(n)return n;let t=(c=(s=o.env)==null?void 0:s.COMPOSIO_API_KEY)==null?void 0:c.trim();if(t)return t;throw new Error("COMPOSIO_API_KEY is not configured (register tenant secret or set env COMPOSIO_API_KEY)")}function W(o){if(!o)return[];let n=[];for(let t of Object.values(o))n.push(...C(t.enable));return[...new Set(n)].sort()}function v(o){return JSON.stringify({toolkits:o.toolkits,tools:o.tools,authMode:o.authMode,authConfigs:o.authConfigs,workbench:o.workbench,sessionPreset:o.sessionPreset,sessionPreload:o.sessionPreload})}function $(o,n){var e;let t=Z(o.tools),i=o.sessionPreset==="direct_tools";return{toolkits:o.toolkits,...o.authConfigs?{authConfigs:o.authConfigs}:{},...t?{tools:t}:{},manageConnections:n.manageConnections,workbench:n.workbench,...i?{sessionPreset:J.DIRECT_TOOLS}:{},...!i&&((e=o.sessionPreload)!=null&&e.enabled)?(()=>{let s=W(o.tools);return s.length>0?{preload:{tools:s}}:{}})():{}}}function H(o,n){var i;let t=(i=o==null?void 0:o.context)==null?void 0:i.user;return t!=null&&t.email||t!=null&&t.id?t:n.user}function F(o,n,t){var c,r,l;let i=H(n,o),e=(c=i==null?void 0:i.email)==null?void 0:c.trim();if(e&&e!=="default")return e;if((t==null?void 0:t.allowChatIdFallback)===!1)throw new Error("Composio user ID unavailable \u2014 log in so your tool-editor connections apply to your email");let s=(l=(r=n==null?void 0:n.flowData)==null?void 0:r.chatId)==null?void 0:l.trim();if(s&&s!=="default")return s;throw new Error("Composio user ID unavailable \u2014 log in (access_token cookie) or provide a chat session id")}function V(o){let n=JSON.stringify(o);return(typeof btoa=="function"?btoa(n):Buffer.from(n,"utf8").toString("base64")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function G(o){var t;let n=(t=o==null?void 0:o.ORA_PUBLIC_URL)==null?void 0:t.trim();return n?n.replace(/\/$/,""):"http://localhost:5173"}function L(o,n,t,i){let e=Y(o),s=V({flowId:n??"",sessionId:t??"",toolRowId:i});return`${e}/api/composio/callback?ctx=${encodeURIComponent(s)}`}function C(o){return Array.isArray(o)?o.filter(n=>typeof n=="string"&&!!n.trim()).map(n=>n.trim()):[]}function Q(o,n){var s;let t=o.toUpperCase(),i=(s=t.split("_")[0])==null?void 0:s.toLowerCase();if(!i)return;let e=n.find(c=>c.toLowerCase()===i);return e||n.find(c=>t.startsWith(`${c.toUpperCase()}_`))}function X(o,n){let t={};for(let i of o){let e=Q(i,n);e&&(t[e]||(t[e]=[]),t[e].push(i))}return Object.fromEntries(Object.entries(t).map(([i,e])=>[i,{enable:e}]))}function Z(o){if(!o)return;let n={};for(let[t,i]of Object.entries(o)){let e=C(i.enable),s=C(i.disable);e.length?n[t]={enable:e}:s.length&&(n[t]={disable:s})}return Object.keys(n).length>0?n:void 0}function oo(o,n,t){let i=new Set(n.map(r=>r.trim()).filter(Boolean)),e={};if(o&&typeof o=="object")for(let[r,l]of Object.entries(o)){if(!i.has(r)||!l||typeof l!="object")continue;let u=l,a=C(u.enable),f=C(u.disable);a.length===0&&f.length===0||(e[r]={...a.length?{enable:a}:{},...f.length?{disable:f}:{}})}if(Object.keys(e).length>0)return e;let s=C(t==null?void 0:t.tools);if(s.length===0)return;let c=X(s,n);return Object.keys(c).length>0?c:void 0}function j(o){var r;let n=o&&typeof o=="object"?o:{},t=Array.isArray(n.toolkits)?n.toolkits.filter(l=>typeof l=="string"&&l.trim()):[];if(t.length===0)throw new Error("Composio tool execution.toolkits must be a non-empty string array");let i=oo(n.tools,t,n.preload),e=typeof n.connectionScope=="string"&&n.connectionScope.trim()?n.connectionScope.trim():void 0,s=n.sessionPreset==="direct_tools"?"direct_tools":void 0,c=((r=n.sessionPreload)==null?void 0:r.enabled)===!0?{enabled:!0}:void 0;return{toolkits:t,authMode:n.authMode==="manual"?"manual":"in_app",authConfigs:n.authConfigs,...e?{connectionScope:e}:{},...i?{tools:i}:{},manageConnections:n.manageConnections,workbench:n.workbench??{enable:!0},...s?{sessionPreset:s}:{},...c?{sessionPreload:c}:{}}}function M(o,n){var i,e;return o.authMode==="manual"?!1:{callbackUrl:((e=(i=o.manageConnections)==null?void 0:i.callbackUrl)==null?void 0:e.trim())||n}}function K(o){let n=String((o==null?void 0:o.message)??o??"").toLowerCase();return n.includes("not connected")||n.includes("not authenticated")||n.includes("connection required")||n.includes("no active connection")||n.includes("authorize")||n.includes("authentication")||n.includes("connect link")||n.includes("no connected account")||n.includes("composio_manage_connections")}function no(o){if(typeof o!="string")return;let n=o.trim();if(n.startsWith("http"))return n}function to(o){for(let n of["redirectUrl","redirect_url","composio_link_redirect_url","url","link"]){let t=no(o[n]);if(t)return d(t)??t}}function d(o){if(o&&typeof o=="object"&&!Array.isArray(o)){let i=to(o);return i||d(JSON.stringify(o))}if(typeof o!="string")return;let n=o.match(q);if(n!=null&&n[0])return n[0];let t=o.match(z);if(t!=null&&t[1]){let i=t[1].replace(/\\u0026/g,"&").replace(/\\\//g,"/");return d(i)??i}}function h(o,n){var t;if(typeof o=="string"){let i=o.toLowerCase();for(let e of(n==null?void 0:n.toolkits)??[])if(i.includes(e.toLowerCase()))return e}return(t=n==null?void 0:n.toolkits)==null?void 0:t[0]}function y(o,n,t,i,e){let s=i?d(i)??i.trim():void 0;!s||!s.startsWith("http")||o==null||o({type:"info:composio:auth_required",content:{toolkit:e,redirectUrl:s,toolRowId:n.id}})}function N(o){let n=d(o);if(n)return n;if(typeof o=="string")return d(o);try{return d(JSON.stringify(o))}catch{return}}async function so(o,n,t,i,e,s=!0){var r;let c=await o.toolkits({toolkits:n.toolkits});for(let l of c.items)if(!(l.isNoAuth||(r=l.connection)!=null&&r.isActive))try{let u=await o.authorize(l.slug,{callbackUrl:t});s&&y(e,i,n,u.redirectUrl,l.slug);break}catch(u){`${l.slug}${String(u)}`}}function ro(o,n,t,i,e=!0){let s={};for(let[c,r]of Object.entries(o)){if(!r||typeof r!="object"||typeof r.execute!="function"){s[c]=r;continue}let l=r.execute.bind(r);s[c]={...r,execute:async(...u)=>{try{let a=await l(...u);if(e){let f=N(a);f&&y(i,n,t,f,h(String(a),t))}return a}catch(a){if(K(a)){let f=N(a);y(i,n,t,f,h(String(a),t))}throw a}}}}return s}async function mo(o,n,t,i){var S,O,T,I,_,R;if(o.kind!=="composio")throw new Error(`loadComposioTools: unsupported kind '${o.kind}' for tool '${o.name}'`);let e=j(o.execution),s=x(n),c=e.authMode==="manual",r;if(c){let p=A(e,o.id);if(!p)throw new Error(`Composio manual tool '${o.name}' is missing connection scope (tool id or execution.connectionScope)`);r=U(p)}else r=F(n,t,{allowChatIdFallback:!0});let l=(S=t.flowData)==null?void 0:S.flowId,u=(O=t.flowData)==null?void 0:O.chatId,a=((T=e.manageConnections)==null?void 0:T.callbackUrl)||L(n,l,u,o.id),f=M(e,a),w=new eo({apiKey:s,provider:new io});n.composioSessions||(n.composioSessions={});let E=v(e),D=c?!1:((I=e.workbench)==null?void 0:I.enable)!==!1,g,m=n.composioSessions[o.id];m!=null&&m.sessionId&&m.userId===r&&m.configKey===E?(g=await w.use(m.sessionId),`${m.sessionId}${o.name}${r}`,void 0):(g=await w.create(r,$(e,{manageConnections:f,workbench:{enable:D}})),n.composioSessions[o.id]={sessionId:g.sessionId,userId:r,configKey:E},`${g.sessionId}${o.name}${r}${e.authMode}${e.sessionPreset??"default"}`,(_=e.sessionPreload)!=null&&_.enabled,void 0);try{let p=await g.toolkits({toolkits:e.toolkits});for(let b of p.items){let P=!!(b.isNoAuth||(R=b.connection)!=null&&R.isActive);`${b.slug}${P}${r}`}await so(g,e,a,o,i,!c)}catch(p){`${o.name}${String(p)}`}let k=await g.tools(),B=Array.isArray(k)?Object.fromEntries(k.map(p=>[p.name??p.toolName,p])):k;return ro(B,o,e,i,!c)}export{mo as a};
|
package/dist/chunk-TGWG3SEO.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
var S=(u=>(u.START_NODE="startNode",u.CLASSIFIER_NODE="classifierNode",u.MEMO_NODE="memoNode",u.LLM_NODE="llmNode",u.ANSWER_NODE="answerNode",u.API_NODE="apiNode",u))(S||{});var T=/^[a-zA-Z][a-zA-Z0-9_]*$/,v=["string","number","boolean","json"];function F(e){let t=e==null?void 0:e.inputs;if(!Array.isArray(t))return[];let o=[],n=new Set;for(let r of t){let s=typeof(r==null?void 0:r.name)=="string"?r.name.trim():"";if(!s||!T.test(s)||n.has(s))continue;n.add(s);let u=v.includes(r==null?void 0:r.type)?r.type:"string";o.push({name:s,label:typeof(r==null?void 0:r.label)=="string"&&r.label.trim()?r.label.trim():void 0,type:u,required:(r==null?void 0:r.required)===!0,default:(r==null?void 0:r.default)??void 0})}return o}function M(e,t){let o=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:`"${o}" 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:`"${o}" must be true or false`}}case"json":{if(typeof t=="object")return{value:t};try{return{value:JSON.parse(String(t))}}catch{return{error:`"${o}" must be valid JSON`}}}default:return{value:typeof t=="string"?t:String(t)}}}function h(e){return e==null||typeof e=="string"&&e.trim()===""}function C(e,t){let o={},n=[],r=t??{};for(let s of e){let u=r[s.name],d=h(u)?s.default:u;if(h(d)){s.required&&n.push(`"${s.label||s.name}" is required`);continue}let{value:p,error:O}=M(s,d);O?n.push(O):o[s.name]=p}return{values:o,errors:n}}function P(e){return typeof e=="string"?e:e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function J(e,t,o){let n=t.user_input;if(typeof n=="string"&&n.trim())return n;let r=e.filter(u=>u.name!=="user_input"&&t[u.name]!==void 0).map(u=>`- ${u.label||u.name}: ${P(t[u.name])}`),s=(o==null?void 0:o.trim())||"Automated execution";return r.length>0?`${s}
|
|
2
|
-
${r.join(`
|
|
3
|
-
`)}`:s}function D(e,t){if(!t)return e;if(e==null)return;let o=t.split("."),n=e;for(let r of o){if(n==null)return;n=n[r]}return n}function L(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"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"?[]:F(e.data).map(t=>({name:t.name,path:t.name,label:t.label,type:t.type==="json"?"object":t.type,source:"default"}))}function A(e){var r;let t=L(e.type),o=((r=e.data)==null?void 0:r.outVars)||[],n=[...t,...$(e).filter(s=>!t.some(u=>u.name===s.name))];for(let s of o){let u=n.findIndex(d=>d.name===s.name);u>=0?n[u]={...s,source:"user"}:n.push({...s,source:"user"})}return n}function j(e,t){var l,N,a,g,y,i,c;if(e==="user_input")return(l=t.context)==null?void 0:l.user_input;if(e==="images")return(N=t.context)==null?void 0:N.user_images;if(e==="classified_id")return(a=t.context)==null?void 0:a.classified_id;if(e==="files"||e==="file_content")return((g=t.context)==null?void 0:g.files)||((y=t.context)==null?void 0:y.file_content);let o=e.indexOf(".");if(o===-1)return t.nodes.find(E=>E.id===e)?(i=t.results)==null?void 0:i[e]:Object.prototype.hasOwnProperty.call(t.context??{},e)?t.context[e]:void 0;let n=e.substring(0,o),r=e.substring(o+1),s=t.nodes.find(f=>f.id===n);if(!s)return;let u=A(s),d=r.split(".")[0],p=u.find(f=>f.name===d);if(!p)return;let O=(c=t.results)==null?void 0:c[n],m=D(O,p.path??"");if((m==null||m==="")&&s.type==="startNode"){let f=p.path||p.name;f&&Object.prototype.hasOwnProperty.call(t.context??{},f)&&(m=t.context[f])}let x=r.substring(d.length+1);return x?D(m,x):m}var w="\0__ORA_OB__\0",V="\0__ORA_CB__\0";function q(e,t,o,n){var m,x;if(!e)return e;let r=(n==null?void 0:n.serializeNonStrings)??!1,s=e.replace(/\\\{\{/g,w).replace(/\\\}\}/g,V),u={...o.context||{}};if((m=t.data)!=null&&m.varMapping&&Array.isArray(t.data.varMapping))for(let l of t.data.varMapping){let N=l.var||l.to,a=l.from;if(N&&a){let g=!1,y=!1;if(a==="images")g=!0;else if(a==="files"||a==="file_content")y=!0;else{let c=a.indexOf(".");if(c!==-1){let f=a.substring(0,c),E=a.substring(c+1).split(".")[0],I=o.nodes.find(b=>b.id===f);if(I){let _=A(I).find(R=>R.name===E);(_==null?void 0:_.type)==="image"&&(g=!0),(_==null?void 0:_.type)==="file"&&(y=!0)}}}if(g||y)continue;let i=j(a,o);(i==null||i==="")&&(i=l.default??""),u[N]=i}}let d=/\{\{\s*([^}]+?)\s*\}\}/g,p=l=>r?JSON.stringify(l).slice(1,-1):l;s=s.replace(d,(l,N)=>{var g,y;let a=N.trim();if(a.startsWith("secrets.")){let i=a.slice(8);return o.secrets?Object.prototype.hasOwnProperty.call(o.secrets,i)?p(o.secrets[i]):((y=n==null?void 0:n.onError)==null||y.call(n,`Secret "${i}" is not defined for this tenant`),l):((g=n==null?void 0:n.onError)==null||g.call(n,`Secret reference {{ ${a} }} cannot be resolved (no secrets context)`),l)}if(Object.prototype.hasOwnProperty.call(u,a)){let i=u[a],c;return typeof i=="string"?c=p(i):typeof i=="object"&&i!==null?c=r?JSON.stringify(i):JSON.stringify(i,null,2):i!=null?c=r?JSON.stringify(i):String(i):c="",c}return l});let O=s.match(/\{\{\s*[^}]+\s*\}\}/g);return O&&((x=n==null?void 0:n.onError)==null||x.call(n,`Mismatch detected: Unmatched placeholders found: ${O}`)),s=s.split(w).join("{{").split(V).join("}}"),s}export{S as a,T as b,F as c,C as d,J as e,D as f,L as g,A as h,j as i,q as j};
|
package/dist/chunk-YHXUBVN2.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
async function s(o){let n=await fetch(`${o.HX_ORA_URL}/internal/tools`,{method:"GET",headers:{Authorization:`${o.HX_API_KEY}`},cache:"no-store"});if(!n.ok)throw new Error("Failed to fetch tool defs");return(await n.json()).tools??[]}async function i(o,n){let t=await fetch(`${n.HX_ORA_URL}/internal/models/${o}`,{method:"GET",headers:{Authorization:`${n.HX_API_KEY}`},cache:"no-store"});if(!t.ok)throw new Error(`Failed to fetch model ${o} from registry`);return(await t.json()).model}async function a(o,n,t){let e=await fetch(`${o.HX_ORA_URL}/internal/tools/${n}/refs/${encodeURIComponent(t)}`,{method:"GET",headers:{Authorization:`${o.HX_API_KEY}`},cache:"no-store"});if(!e.ok)throw e.status===404?new Error(`Reference "${t}" not found`):new Error(`Failed to fetch skill reference "${t}"`);let r=await e.json();if(!r.ref)throw new Error(`Reference "${t}" not found in response`);return r.ref}export{s as a,i as b,a as c};
|
|
@@ -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{a}from"./chunk-4WAWR4LB.js";import"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{a as loadComposioTools};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as a,e as b}from"./chunk-RRS7SUF3.js";import"./chunk-TGWG3SEO.js";import"./chunk-V6JSMX5A.js";import"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{a as customHttpTool,b as default};
|
package/dist/oraApi-YIJGMXX7.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";export{b as fetchOraModel,c as fetchSkillRef,a as fetchToolDefs};
|
|
File without changes
|