@hugex/ai 3.0.1 → 3.0.3
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 +4 -4
- package/dist/chunk-CDGUEX3J.js +5 -0
- package/dist/{chunk-UBNZUUTD.js → chunk-EZIUCT77.js} +1 -1
- package/dist/chunk-VLZKZDRV.js +3 -0
- package/dist/chunk-Y2NRJIHX.js +7 -0
- package/dist/client.js +1 -1
- package/dist/common/utils/agentMemory.d.ts +24 -0
- package/dist/common.d.ts +1 -0
- package/dist/common.js +1 -1
- package/dist/httpTool-5D2PQJKV.js +1 -0
- package/dist/index.js +17 -30
- package/dist/server/core/AgentDO.d.ts +18 -12
- package/dist/server/core/agentTurn.d.ts +1 -2
- package/dist/server/logic/FlowEngine.d.ts +0 -2
- package/dist/server/logic/memoryWriter.d.ts +44 -0
- package/dist/server/sql/agentSQL.d.ts +0 -16
- package/dist/server/utils/flowNodes.d.ts +2 -0
- package/dist/server/utils/flowRefresh.d.ts +1 -1
- package/dist/{skillTool-PLHCAODG.js → skillTool-AIOXPTAJ.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-57TCP6J4.js +0 -11
- package/dist/chunk-E7BCWUTG.js +0 -1
- package/dist/chunk-GRZ6ZRHM.js +0 -1
- package/dist/chunk-K4MP63XM.js +0 -3
- package/dist/chunk-W6DBEVOO.js +0 -5
- package/dist/common/types/memory-types.d.ts +0 -28
- package/dist/httpTool-LSNJKMPR.js +0 -1
- package/dist/recall-IABRCSHY.js +0 -1
- package/dist/server/tools/recall.d.ts +0 -7
- package/dist/server/utils/contextMemory.d.ts +0 -25
- package/dist/server/utils/sessionEnvMemory.d.ts +0 -12
package/README.md
CHANGED
|
@@ -64,7 +64,7 @@ Design-time node data (configured in Agent Design panels):
|
|
|
64
64
|
|
|
65
65
|
| Node | Key data |
|
|
66
66
|
|---|---|
|
|
67
|
-
| **Start** | `greeting`, `allow_images`, `allow_documents
|
|
67
|
+
| **Start** | `greeting`, `allow_images`, `allow_documents` |
|
|
68
68
|
| **LLM** | `template`, `model`, `tools`, `attachments`, `outVars` |
|
|
69
69
|
| **Memo** | `rag_id`, `query_key`, `topk` |
|
|
70
70
|
| **Classifier** | `input_variable`, `items[]` |
|
|
@@ -144,7 +144,7 @@ const { send, sendAuth, clearHistory } = useAgent({
|
|
|
144
144
|
const messages = useAgentStore((s) => s.messages);
|
|
145
145
|
```
|
|
146
146
|
|
|
147
|
-
Start-node flags (`allow_images`, `allow_documents
|
|
147
|
+
Start-node flags (`allow_images`, `allow_documents`) can be read from flow config (`flowConfig` in the store) or from your design metadata to drive the UI.
|
|
148
148
|
|
|
149
149
|
### Pattern 3 — multiple agents on one screen (`storeKey`)
|
|
150
150
|
|
|
@@ -207,7 +207,7 @@ Inbound frames use `TYPE::CONTENT`:
|
|
|
207
207
|
| Code | Meaning |
|
|
208
208
|
|---|---|
|
|
209
209
|
| `HIS` | Full history replay |
|
|
210
|
-
| `SE` | Server event (tools,
|
|
210
|
+
| `SE` | Server event (tools, external integrations, …) |
|
|
211
211
|
| `TS` / `TSC` | Assistant text stream / complete |
|
|
212
212
|
| `RS` / `RSC` | Reasoning stream / complete |
|
|
213
213
|
| `CFG` | Flow config (attachments, greeting) |
|
|
@@ -272,7 +272,7 @@ export { AgentDO } from '@hugex/ai';
|
|
|
272
272
|
|
|
273
273
|
Required env vars (typical): `HX_CORE_URL`, `HX_ORA_URL`, `HX_API_KEY`, tenant Vectorize binding `VDB_<tenant>_1024`, `AI` (Workers AI).
|
|
274
274
|
|
|
275
|
-
|
|
275
|
+
Secrets (`{{ secrets.NAME }}`), Vectorize memo, and tool execution run inside `AgentDO`; shared data is fetched from HX Core / hx-ora APIs.
|
|
276
276
|
|
|
277
277
|
## Bundler
|
|
278
278
|
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{d as m}from"./chunk-A2IRPAD4.js";import{tool as p}from"ai";import{z as s}from"zod";function y(t,c){if(c.length===0)return;let f=c.map(e=>`- "${e.name}"${e.description?` \u2014 applies when: ${e.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: "${t}", 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
|
+
|
|
3
|
+
References:
|
|
4
|
+
${f.join(`
|
|
5
|
+
`)}`}function x(t,c,f,e){if(t.kind!=="skill")throw new Error(`skillTool: unsupported kind '${t.kind}' for tool '${t.name}'`);let n=typeof t.execution=="string"?JSON.parse(t.execution):t.execution||{},i=n.instructions||"",o=Array.isArray(n.references)?n.references:[],d=y(t.name,o);return p({description:t.description||t.label||t.name,inputSchema:s.object({}),execute:async()=>(e==null||e({type:"info:skill:bodyServed",content:{skill:t.name,refCount:o.length,refs:o.map(l=>l.name)}}),{instructions:i,references:o,...d?{how_to_use_references:d}:{}})})}function T(t,c,f,e){return p({description:"Loads the full content of an in-depth reference document belonging to a skill that was already opened in this conversation. Pass the skill name and the reference name exactly as listed in the skill's reference menu.",inputSchema:s.object({skill:s.string().describe("The name of the skill/tool that owns the reference"),ref:s.string().describe("The name of the reference document to read")}),execute:async({skill:n,ref:i})=>{e==null||e({type:"info:skill:refRequested",content:{skill:n,ref:i}});let o=c.find(a=>a.name===n);if(!o){let a=c.map(r=>r.name).join(", ");return e==null||e({type:"warn:skill:skillMissing",content:{skill:n,availableSkills:a}}),{error:`Skill "${n}" not found or not attached to this LLM node.`,availableSkills:a}}let l=(typeof o.execution=="string"?JSON.parse(o.execution):o.execution||{}).references||[];if(!l.find(a=>a.name===i)){let a=l.map(r=>r.name).join(", ");return e==null||e({type:"warn:skill:refMissing",content:{skill:n,ref:i,availableRefs:a||"(none)"}}),{error:`Reference "${i}" not found in skill "${n}".`,availableRefs:a||"(none)"}}let u=`${o.id}:${i}`;if(t.skillRefCache&&t.skillRefCache.has(u))return e==null||e({type:"info:skill:refCacheHit",content:{skill:n,ref:i,tier:1}}),{name:i,content:t.skillRefCache.get(u)};if(!t.env)throw new Error("Cloudflare bindings / Env missing on sessionEnv");e==null||e({type:"info:skill:refFetching",content:{skill:n,ref:i,toolId:o.id}});let h=await m(t.env,o.id,i);return t.skillRefCache&&t.skillRefCache.set(u,h.content),e==null||e({type:"info:skill:refFetched",content:{skill:n,ref:i,bytes:h.content.length}}),{name:i,content:h.content}}})}export{x as a,T as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{q as N}from"./chunk-
|
|
1
|
+
import{q as N}from"./chunk-VLZKZDRV.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};
|
|
@@ -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"},{name:"memory",path:"memory",type:"string"}];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",f=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 f("UNSAFE_PATH",`Unsafe variable path segment "${t}"`)}function v(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,p;if(Object.prototype.hasOwnProperty.call(t.refOverrides??{},e))return{value:t.refOverrides[e]};let n=t.nodes.find(l=>l.type==="startNode");if(e==="user_input")return{value:(o=t.context)==null?void 0:o.user_input};if(e==="memory")return{value:((r=t.context)==null?void 0:r.memory)??""};if(e==="images"&&((s=n==null?void 0:n.data)==null?void 0:s.allow_images)===!0)return{value:(i=t.context)==null?void 0:i.user_images};if(e==="files"&&((a=n==null?void 0:n.data)==null?void 0:a.allow_documents)===!0)return{value:(c=t.context)==null?void 0:c.files};if(e==="classified_id")return{value:(u=t.context)==null?void 0:u.classified_id};if(n&&m(n.data).some(l=>l.name===e))return{value:(p=t.context)==null?void 0:p[e]}}function R(e,t){var h;let n=e.trim();if(!n)throw new f("INVALID_EXPRESSION","Variable reference is empty");let o=n.includes(".")?void 0:k(n,t);if(o)return o;if(!n.includes("."))throw new f("UNKNOWN_CONTEXT_REF",`Unknown run-context variable "${n}"`);let r=x(n,t);if(!r)throw new f("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 f("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 p=v(u,c.path??""),l=a.length>0?v(p,a.join(".")):p;return l==null?{value:void 0,missing:"path_not_found"}:{value:l}}function ce(e,t){return R(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 f("INVALID_EXPRESSION","Template defaults must be quoted string literals");if(e[0]==='"')try{return JSON.parse(e)}catch{throw new f("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 f("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 l=u.ref.slice(8);if(!Object.prototype.hasOwnProperty.call(n.secrets??{},l))throw new f("MISSING_SECRET",`Secret "${l}" is not defined for this tenant`);return _(n.secrets[l],r)}let p=R(u.ref,n);if(p.missing){if(u.defaultValue!==void 0)return _(u.defaultValue,r);let l=p.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 f(p.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",l)}return _(p.value,r)}catch(u){if(u instanceof f)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,f as p,v as q,R as r,ce as s,V as t,le as u,fe as v,pe as w};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
function j(e){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t}catch{}return{text:e}}var T=256;function H(e){if(typeof e!="string")return null;let t=e.trim();return t?t.slice(0,T):null}function Y(e){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.name=="string"&&typeof t.value=="string"){let n=t.name.trim();return/^[A-Z][A-Z0-9_]*$/.test(n)?{name:n,value:t.value}:null}}catch{}return null}var F={USER_MESSAGE:"M",USER_CLEAR_HISTORY:"CH",USER_AUTH:"AUT",USER_IDENTITY:"UID",SERVER_EVENT:"SE",SERVER_HISTORY:"HIS",SERVER_ERROR:"ERR",SERVER_STEP:"STEP",SERVER_TEXT_STREAM:"TS",SERVER_TEXT_STREAM_COMPLETE:"TSC",SERVER_REASONING_STREAM:"RS",SERVER_REASONING_STREAM_COMPLETE:"RSC",SERVER_CONFIG:"CFG"};var x=["temperature","topP","topK","frequencyPenalty","presencePenalty","maxOutputTokens","seed","stopSequences","maxRetries"],y=["temperature","topP","topK","frequencyPenalty","presencePenalty"],E={precise:{temperature:.3,topP:.9,topK:30},balanced:{temperature:.8,topP:1,topK:50},creative:{temperature:1.1,topP:.95,topK:80}},h=1e-6,g={temperature:{min:0,max:2,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:{min:-2,max:2,step:.1},presencePenalty:{min:-2,max:2,step:.1},maxOutputTokens:{max:128e3},seed:!0,stopSequences:{max:4}};function M(e){return/^gpt-5/i.test(e)}function c(e){let t=e.contextWindow??128e3;return e.provider==="openai"?M(e.providerModel)?{temperature:!1,topP:!1,topK:{min:1,max:500,step:1},frequencyPenalty:{min:-2,max:2,step:.1},presencePenalty:{min:-2,max:2,step:.1},maxOutputTokens:{max:t},seed:!0,stopSequences:{max:4}}:{...g,maxOutputTokens:{max:t}}:e.provider==="xai"?{...g,maxOutputTokens:{max:t},seed:!0}:e.provider==="anthropic"?{temperature:{min:0,max:1,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:!1,presencePenalty:!1,maxOutputTokens:{max:t},seed:!1,stopSequences:{max:4}}:e.provider==="openrouter"?{temperature:{min:0,max:2,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:{min:-2,max:2,step:.1},presencePenalty:{min:-2,max:2,step:.1},maxOutputTokens:{max:t},seed:!0,stopSequences:{max:4}}:e.provider==="workersai"||e.provider==="cloudflare"?{temperature:{min:0,max:2,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:!1,presencePenalty:!1,maxOutputTokens:{max:t},seed:!1,stopSequences:{max:4}}:{...g,maxOutputTokens:{max:t}}}function l(e,t){if(e==="maxRetries")return!0;let n=t[e];return n===!1?!1:e==="seed"?n===!0:n!==void 0}function v(e,t,n){return Math.min(n,Math.max(t,e))}function b(e,t){return e===void 0&&t===void 0?!0:e===void 0||t===void 0?!1:Math.abs(e-t)<h}function $(e,t){for(let n of["precise","balanced","creative"]){let o=E[n],s=!0;for(let r of y){if(t&&!l(r,t))continue;let a=o[r],i=e[r];if(a!==void 0){if(typeof a=="number"&&typeof i=="number"){if(!b(i,a)){s=!1;break}}else if(i!==a){s=!1;break}}}if(s)return n}return"custom"}function z(e,t){let n=E[e],o={};for(let s of y){if(t&&!l(s,t))continue;let r=n[s];r!==void 0&&(o[s]=r)}return o}function Z(e){if(!e)return{};let t={};for(let n of x){let o=e[n];o!==void 0&&(n==="stopSequences"?Array.isArray(o)&&(t.stopSequences=o.filter(s=>typeof s=="string")):n==="maxRetries"?typeof o=="number"&&(t.maxRetries=o):typeof o=="number"&&(t[n]=o))}return t}function B(e,t,n){var a;let o={...e,...t},s=[],r={};for(let i of x){let f=o[i];if(f===void 0)continue;if(i==="maxRetries"){r.maxRetries=f;continue}if(!l(i,n)){s.push({key:i,action:"stripped",detail:"unsupported by model"});continue}if(i==="stopSequences"){let u=f,p=((a=n.stopSequences)==null?void 0:a.max)??u.length;u.length>p?(r.stopSequences=u.slice(0,p),s.push({key:i,action:"clamped",detail:`truncated to ${p} sequences`})):r.stopSequences=u;continue}if(i==="seed"){r.seed=f;continue}let m=n[i];if(m&&typeof m=="object"&&"min"in m){let u=f,p=v(u,m.min,m.max);r[i]=p,p!==u&&s.push({key:i,action:"clamped",detail:`clamped from ${u} to ${p}`})}else if(i==="maxOutputTokens"){let u=f,p=n.maxOutputTokens.max,d=Math.min(u,p);r.maxOutputTokens=d,d!==u&&s.push({key:i,action:"clamped",detail:`clamped from ${u} to ${d}`})}}return{effectiveParams:r,adjustments:s}}function X(e){let t={};return e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.maxOutputTokens!==void 0&&(t.maxOutputTokens=e.maxOutputTokens),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.maxRetries!==void 0&&(t.maxRetries=e.maxRetries),t}function J(e=128e3){return c({provider:"openai",providerModel:"gpt-4.1",contextWindow:e})}function Q(e=2e6){return c({provider:"openai",providerModel:"gpt-5-nano",contextWindow:e})}function ee(e=256e3){return c({provider:"xai",providerModel:"grok-4-fast",contextWindow:e})}function te(e=128e3){return c({provider:"cloudflare",providerModel:"@cf/meta/llama-3.2-3b-instruct",contextWindow:e})}function ne(e,t){let n={...e};for(let o of x)o==="maxRetries"||n[o]===void 0||l(o,t)||delete n[o];return n}var k=["none","minimal","low","medium","high","xhigh"],_=e=>typeof e=="string"&&k.includes(e);function oe(e){var n;let t=(n=e.capabilities)==null?void 0:n.reasoning;return t&&typeof t=="object"?t:t?{kind:"effort"}:{kind:"none"}}function O(e){return e.kind!=="effort"?[]:e.levels??[]}var A=e=>e===!0||e==="true";function se(e){return e.kind==="tag"?!0:e.kind==="effort"?A(e.exposesReasoning):!1}function ie(e,t){if(e.kind!=="effort")return;let n=O(e);if(_(t)&&n.includes(t))return t;if(e.defaultLevel&&n.includes(e.defaultLevel))return e.defaultLevel}function ae(e,t){let{effort:n,exposeReasoning:o,maxTokens:s}=t;if(e==="openai"){let r={};return n&&(r.reasoningEffort=n),o&&(r.reasoningSummary="auto"),Object.keys(r).length?{openai:r}:void 0}if(e==="xai")return n?{xai:{reasoningEffort:n}}:void 0;if(e==="openrouter"){if(!s&&!n)return;let r={};return o!==void 0&&(r.exclude=!o),s?{openrouter:{reasoning:{...r,max_tokens:s}}}:{openrouter:{reasoning:{...r,effort:n}}}}if(e==="anthropic"){let r={};return(n||o)&&(r.thinking={type:"adaptive",...o?{display:"summarized"}:{}}),n&&(r.effort=n),Object.keys(r).length?{anthropic:r}:void 0}}var L=[{id:"convertTempMessure",label:"Convert Temperature",description:"Convert temperature between Celsius, Fahrenheit, and Kelvin with optional static parameters"},{id:"tempTool",label:"Temp Tool",description:"Temporary demo tool"},{id:"twitter",label:"Twitter",description:"Twitter API for user info, tweets, mentions, replies, advanced search, and trends"},{id:"vectorize",label:"Vectorize",description:"Perform a semantic vector search. Returns relevant matches with scores and metadata."}],pe=L.reduce((e,t)=>(e[t.id]=t,e),{});var me={};function ce(e){}var N={short:512,medium:1024,long:2048},R="medium",w="gpt_5_nano",P=4;function I(e){return e==="short"||e==="medium"||e==="long"?e:R}function C(e=R){return N[e]}function q(e){return e?Math.ceil(e.length/P):0}function G(e,t){if(!e)return{content:"",truncated:!1};if(q(e)<=t)return{content:e,truncated:!1};let n=Math.max(0,t*P);return{content:e.slice(0,n),truncated:!0}}function de(e){let t=e==null?void 0:e.memory_enabled;return t===!0||t==="true"||t===1}function ge(e){let t=e==null?void 0:e.memory_model;return typeof t=="string"&&t.trim()?t.trim():w}function xe(e){return I(e==null?void 0:e.memory_length)}function ye(e,t){let n=C(e);return t&&t!=="none"?Math.min(n+2048,8192):n}var S=/^(user|assistant|usuario|asistente)\s*:/i,K=/^(hola|hello|hi|hey|buenas|buen[oa]s?\s+d[ií]as?|qu[eé]\s+tal|qu[eé]\s+haces)[\s,.!¡¿?]*$/i;function U(e){let t=e.split(`
|
|
2
|
+
`).map(o=>o.replace(/^[-*]\s*/,"").trim()).filter(Boolean);if(t.length<2)return!1;let n=t.filter(o=>S.test(o));return n.length>=2&&n.length>=Math.ceil(t.length/2)}function W(e){let t=e.split(`
|
|
3
|
+
`).map(n=>n.trim()).filter(Boolean).filter(n=>n!=="(empty)"&&n!=="(none)").filter(n=>!S.test(n.replace(/^[-*]\s*/,"")));return U(t.join(`
|
|
4
|
+
`))?"":t.join(`
|
|
5
|
+
`)}function Ee(e){let t=e.trim();if(!t||K.test(t))return[];let n=[],o=t.match(/(?:me llamo|soy|i['’]m|i am|my name is)\s+([A-Za-zÁÉÍÓÚÜáéíóúüñÑ][\wÁÉÍÓÚÜáéíóúüñÑ'-]{1,40})/i);o&&n.push(`Name: ${o[1]}`);let s=t.match(/me gusta[n]?\s+([^,.!?]+)/i);if(s&&n.push(`Likes: ${s[1].trim()}`),/[?¿]/.test(t)||/^(pregunt|dime\b|cu[eé]nt)/i.test(t))return n;let a=t.replace(/^(hola|hey|hi)[,\s]+/i,"").replace(/(?:me llamo|soy)\s+[A-Za-zÁÉÍÓÚÜáéíóúüñÑ][\wÁÉÍÓÚÜáéíóúüñÑ'-]*/gi,"").replace(/me gusta[n]?\s+[^,.!?]+/gi,"").replace(/[,.\s]+/g," ").trim();return a.length>=16&&n.push(a.slice(0,140)),n}function Re(e,t,n){let s=[...W(e).split(`
|
|
6
|
+
`).map(r=>r.replace(/^[-*]\s*/,"").trim()).filter(Boolean)];for(let r of t){let a=r.replace(/^[-*]\s*/,"").trim();a&&(s.some(i=>i.toLowerCase()===a.toLowerCase())||s.push(a))}return s.length===0?"":G(s.map(r=>`- ${r}`).join(`
|
|
7
|
+
`),n).content}export{F as a,j as b,T as c,H as d,Y as e,N as f,R as g,w as h,I as i,C as j,q as k,G as l,de as m,ge as n,xe as o,ye as p,U as q,W as r,Ee as s,Re as t,x as u,y as v,E as w,c as x,$ as y,z,Z as A,B,X as C,J as D,Q as E,ee as F,te as G,ne as H,k as I,oe as J,O as K,se as L,ie as M,ae as N,pe as O,me as P,ce as Q};
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{A as De,B as He,C as je,D as Ue,E as Pe,F as Je,G as Ge,H as $e,I as Le,J as Ye,K as ke,L as Ke,M as Qe,N as Xe,O as ze,P as Be,Q as We,a as u,b as Q,c as T,d as X,e as z,f as B,g as W,h as Z,i as ee,j as te,k as ne,l as se,m as oe,n as re,o as ae,p as ie,q as ge,r as le,s as pe,t as ce,u as be,v as Ne,w as Oe,x as qe,y as Ve,z as Fe}from"./chunk-Y2NRJIHX.js";import{a as $,b as L,c as Y,d as k,e as K,f as ue,g as de,h as ve,i as ye,j as me,k as Se,l as fe,m as Ae,n as Re,o as Me,p as Ee,q as Te,r as Ie,s as Ce,t as he,u as xe,v as we,w as _e}from"./chunk-VLZKZDRV.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 it(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{W as DEFAULT_MEMORY_LENGTH,Z as DEFAULT_MEMORY_MODEL,L as FLOW_INPUT_NAME_RE,be as GENERATION_PARAM_KEYS,Oe as GENERATION_PRESETS,T as MAX_USER_IDENTITY_LENGTH,B as MEMORY_LENGTH_TOKENS,Be as MODEL_REGISTRY_SNAPSHOT,$ as NodeType,ue as OUT_VAR_NAME_RE,Ne as PRESET_PARAM_KEYS,Le as REASONING_EFFORT_LEVELS,ze as TOOL_REGISTRY_SNAPSHOT,Ee as VariableResolutionError,Fe as applyPresetToOverrides,Xe as buildReasoningProviderOptions,fe as buildScope,K as buildTriggerMessageText,se as capMemoryContent,qe as deriveParamSupport,ne as estimateTokens,xe as extractTemplateReferences,pe as extractUserKeypoints,Ae as findScopedSourceNode,h as getAgentStore,me as getAncestorNodeIds,de as getDefaultOutVars,ye as getEffectiveOutVars,Y as getFlowInputDefs,We as getModelEntry,Re as getRefTail,Se as getUpstreamOutVars,Me as isBinaryOutVar,oe as isStartMemoryEnabled,G as logc,ge as looksLikeTranscript,ie as memoryGenerationMaxTokens,te as memoryTokenLimit,ce as mergeKeypointMemory,u as messageTypes,He as normalizeEffectiveParams,k as normalizeFlowInputs,Ye as normalizeReasoning,Pe as openAiReasoningParamSupport,Ue as openAiStandardParamSupport,ee as parseMemoryLength,he as parseTemplateExpression,z as parseUserAuth,Q as parseUserMessage,De as pickNodeOverrides,ke as reasoningEffortLevels,Ke as reasoningExposable,Ce as resolveOutVarRef,Ve as resolvePreset,Qe as resolveReasoningEffort,Ie as resolveReference,_e as resolveTemplate,we as rewriteTemplateNodeRefs,le as sanitizeMemoryDocument,X as sanitizeUserIdentity,ae as startMemoryLength,re as startMemoryModel,$e as stripUnsupportedFromNodeData,je as toStreamTextSettings,it as useAgent,j as useAgentStore,ve as validateOutVars,Te as walkPath,Ge as workersAiParamSupport,Je as xaiParamSupport};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export type MemoryLength = 'short' | 'medium' | 'long';
|
|
2
|
+
export declare const MEMORY_LENGTH_TOKENS: {
|
|
3
|
+
readonly short: 512;
|
|
4
|
+
readonly medium: 1024;
|
|
5
|
+
readonly long: 2048;
|
|
6
|
+
};
|
|
7
|
+
export declare const DEFAULT_MEMORY_LENGTH: MemoryLength;
|
|
8
|
+
export declare const DEFAULT_MEMORY_MODEL = "gpt_5_nano";
|
|
9
|
+
export declare function parseMemoryLength(value: unknown): MemoryLength;
|
|
10
|
+
export declare function memoryTokenLimit(length?: MemoryLength): number;
|
|
11
|
+
export declare function estimateTokens(text: string): number;
|
|
12
|
+
export declare function capMemoryContent(content: string, maxTokens: number): {
|
|
13
|
+
content: string;
|
|
14
|
+
truncated: boolean;
|
|
15
|
+
};
|
|
16
|
+
export declare function isStartMemoryEnabled(data: Record<string, unknown> | undefined | null): boolean;
|
|
17
|
+
export declare function startMemoryModel(data: Record<string, unknown> | undefined | null): string;
|
|
18
|
+
export declare function startMemoryLength(data: Record<string, unknown> | undefined | null): MemoryLength;
|
|
19
|
+
/** Reasoning models spend output budget on thinking; request extra tokens then cap the document. */
|
|
20
|
+
export declare function memoryGenerationMaxTokens(length: MemoryLength, reasoningKind?: string): number;
|
|
21
|
+
export declare function looksLikeTranscript(content: string): boolean;
|
|
22
|
+
export declare function sanitizeMemoryDocument(content: string): string;
|
|
23
|
+
export declare function extractUserKeypoints(userText: string): string[];
|
|
24
|
+
export declare function mergeKeypointMemory(previous: string, additions: string[], maxTokens: number): string;
|
package/dist/common.d.ts
CHANGED
package/dist/common.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{A as Y,B as Z,C as _,D as $,E as aa,F as ba,G as ca,H as da,I as ea,J as fa,K as ga,L as ha,M as ia,N as ja,O as ka,P as la,Q as ma,a as b,b as h,c as i,d as j,e as k,f as l,g as m,h as n,i as o,j as p,k as q,l as r,m as s,n as t,o as u,p as v,q as w,r as x,s as y,t as z,u as S,v as T,w as U,x as V,y as W,z as X}from"./chunk-Y2NRJIHX.js";import{a as c,b as d,c as e,d as f,e as g,f as A,g as B,h as C,i as D,j as E,k as F,l as G,m as H,n as I,o as J,p as K,q as L,r as M,s as N,t as O,u as P,v as Q,w as R}from"./chunk-VLZKZDRV.js";import{a}from"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{m as DEFAULT_MEMORY_LENGTH,n as DEFAULT_MEMORY_MODEL,d as FLOW_INPUT_NAME_RE,S as GENERATION_PARAM_KEYS,U as GENERATION_PRESETS,i as MAX_USER_IDENTITY_LENGTH,l as MEMORY_LENGTH_TOKENS,la as MODEL_REGISTRY_SNAPSHOT,c as NodeType,A as OUT_VAR_NAME_RE,T as PRESET_PARAM_KEYS,ea as REASONING_EFFORT_LEVELS,ka as TOOL_REGISTRY_SNAPSHOT,K as VariableResolutionError,X as applyPresetToOverrides,ja as buildReasoningProviderOptions,G as buildScope,g as buildTriggerMessageText,r as capMemoryContent,V as deriveParamSupport,q as estimateTokens,P as extractTemplateReferences,y as extractUserKeypoints,H as findScopedSourceNode,E as getAncestorNodeIds,B as getDefaultOutVars,D as getEffectiveOutVars,e as getFlowInputDefs,ma as getModelEntry,I as getRefTail,F as getUpstreamOutVars,J as isBinaryOutVar,s as isStartMemoryEnabled,a as logc,w as looksLikeTranscript,v as memoryGenerationMaxTokens,p as memoryTokenLimit,z as mergeKeypointMemory,b as messageTypes,Z as normalizeEffectiveParams,f as normalizeFlowInputs,fa as normalizeReasoning,aa as openAiReasoningParamSupport,$ as openAiStandardParamSupport,o as parseMemoryLength,O as parseTemplateExpression,k as parseUserAuth,h as parseUserMessage,Y as pickNodeOverrides,ga as reasoningEffortLevels,ha as reasoningExposable,N as resolveOutVarRef,W as resolvePreset,ia as resolveReasoningEffort,M as resolveReference,R as resolveTemplate,Q as rewriteTemplateNodeRefs,x as sanitizeMemoryDocument,j as sanitizeUserIdentity,u as startMemoryLength,t as startMemoryModel,da as stripUnsupportedFromNodeData,_ as toStreamTextSettings,C as validateOutVars,L as walkPath,ca as workersAiParamSupport,ba as xaiParamSupport};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as a,e as b}from"./chunk-EZIUCT77.js";import"./chunk-VLZKZDRV.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,42 +1,29 @@
|
|
|
1
|
-
import{a as ue}from"./chunk-ELMOSEQ7.js";import{a as B,b as st,c as pe,d as yt}from"./chunk-UBNZUUTD.js";import{a as me}from"./chunk-OF6G42DM.js";import"./chunk-MOYYZBTC.js";import{a as ge,b as ye}from"./chunk-W6DBEVOO.js";import{a as Pn,b as ut,c as Dn,d as pt,e as _t,f as oe,g as ne,h as se,i as re,j as ie,k as $t,l as ae}from"./chunk-57TCP6J4.js";import{a as E,b as dt,c as gn,d as nt,e as Bt,f as fe,g as Kn,h as Jn}from"./chunk-E7BCWUTG.js";import{a as v,b as mn,c as tt,d as Wt,e as Yt,f as Un,g as Mn,h as ce,i as ft,j as bn,k as et,l as En,m as jn,n as Ln,o as Hn,p as V,q as mt,r as K,s as Vn,t as qn,u as Sn,v as Xn,w as le}from"./chunk-K4MP63XM.js";import{a as yn,b as wn,c as hn,d as Rn,e as xn,f as In,g as Qt,h as Tn,i as Zt,j as Nn,k as An,l as Cn,m as On,n as _n,o as $n,p as kn,q as Fn,r as vt,s as te,t as ee}from"./chunk-GRZ6ZRHM.js";import{a as an}from"./chunk-RYHQGPX5.js";import{a as cn}from"./chunk-R6EKV3WR.js";import{a as un}from"./chunk-6HY7QUMP.js";import{a as ln,b as dn}from"./chunk-V6JSMX5A.js";import{a as W,b as Z,c as pn,d as Gt,e as fn}from"./chunk-G3SGJ7XJ.js";import{a as ot}from"./chunk-U56YWPSI.js";import{a as gt,b as de}from"./chunk-A2IRPAD4.js";import{a as lt}from"./chunk-3TXHFKDN.js";import{Agent as Jo}from"agents";import{nanoid as zo}from"nanoid";var H=(o,t,n)=>{o.send(t+"::"+n)};async function io(o){o.sql`CREATE TABLE IF NOT EXISTS messages (id TEXT PRIMARY KEY, role TEXT NOT NULL, type TEXT NOT NULL, content TEXT NOT NULL, ts INTEGER NOT NULL)`}async function we(o,t){o.sql`INSERT INTO messages (id, role, type, content, ts) VALUES (${t.id}, ${t.role}, ${t.type}, ${t.content}, ${t.ts})`}async function z(o){return o.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function wt(o){o.sql`DELETE FROM messages`}async function ao(o){o.sql`CREATE TABLE IF NOT EXISTS context (
|
|
2
|
-
ref TEXT PRIMARY KEY,
|
|
3
|
-
domain TEXT NOT NULL,
|
|
4
|
-
description TEXT NOT NULL,
|
|
5
|
-
data TEXT,
|
|
6
|
-
cycle INTEGER NOT NULL,
|
|
7
|
-
meta TEXT,
|
|
8
|
-
ts INTEGER NOT NULL
|
|
9
|
-
)`}async function he(o,t){let n=t.data??null,e=n!=null?se(n):{data:null,truncated:!1},s=e.truncated?ae(t.meta,{truncated:!0}):t.meta??null,r=t.ts??Date.now();o.sql`INSERT INTO context (ref, domain, description, data, cycle, meta, ts)
|
|
10
|
-
VALUES (${t.ref}, ${t.domain}, ${t.description}, ${e.data}, ${t.cycle}, ${s}, ${r})
|
|
11
|
-
ON CONFLICT(ref) DO UPDATE SET
|
|
12
|
-
domain = excluded.domain,
|
|
13
|
-
description = excluded.description,
|
|
14
|
-
data = excluded.data,
|
|
15
|
-
cycle = excluded.cycle,
|
|
16
|
-
meta = excluded.meta,
|
|
17
|
-
ts = excluded.ts`}async function ht(o){return o.sql`SELECT ref, domain, description, cycle, meta, ts FROM context ORDER BY ts ASC`}async function Re(o){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context ORDER BY ts ASC`}async function Rt(o,t){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${t} LIMIT 1`[0]??null}async function xe(o,t){var e;return((e=o.sql`SELECT data FROM context WHERE ref = ${t} LIMIT 1`[0])==null?void 0:e.data)??null}async function Ie(o,t){let n=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${t} LIMIT 1`;if(n[0])return n[0];let e=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref LIKE ${t+"%"} LIMIT 2`;return e.length===1?e[0]:null}async function Te(o,t){o.sql`DELETE FROM context WHERE domain = 'tool' AND cycle <= ${t}`}async function Ne(o){var n;return((n=o.sql`SELECT COALESCE(MAX(cycle), 0) AS maxCycle FROM context`[0])==null?void 0:n.maxCycle)??0}async function xt(o){o.sql`DELETE FROM context`}async function Ae(o){await io(o),await ao(o)}function kt(o){return{"Content-Type":"application/json",Authorization:o.HX_API_KEY}}function It(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}var co="anonymous:";function Ce(o,t){return(o==null?void 0:o.trim())||`${co}${t}`}async function Ft(o,t){if(!It(o))return null;let n=await fetch(`${o.HX_ORA_URL}/internal/runs`,{method:"POST",headers:kt(o),body:JSON.stringify(t)});return n.ok?await n.json():(console.error("[oraTriggers] createRun failed",n.status,await n.text().catch(()=>"")),null)}async function rt(o,t){if(!It(o))return{claimed:!0};let n=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(t)}/claim`,{method:"POST",headers:kt(o)});if(!n.ok){let e=await n.text().catch(()=>"");throw new Error(`claimRun ${t} failed with ${n.status}: ${e}`)}return await n.json()}async function Tt(o,t,n,e=3){if(!It(o))return!0;for(let s=1;s<=e;s++){try{let r=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(t)}/complete`,{method:"POST",headers:kt(o),body:JSON.stringify(n)});if(r.ok||r.status===409)return!0;if(r.status===404)return console.error(`[oraTriggers] completeRun ${t} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${t} attempt ${s} failed with ${r.status}`)}catch(r){console.warn(`[oraTriggers] completeRun ${t} attempt ${s} threw`,r)}s<e&&await new Promise(r=>setTimeout(r,250*s))}return console.error(`[oraTriggers] completeRun ${t} exhausted ${e} attempts; hx-ora will time the run out`),!1}async function Oe(o,t){if(!It(o))return Promise.resolve();try{return await Ft(o,t)}catch(n){return console.error("[oraTriggers] recordRun failed",n),null}}var Pt=Object.freeze({}),lo="__SYSTEM_";function _e(o){return o.startsWith(lo)}function uo(o){let t={};for(let[n,e]of Object.entries(o))_e(n)||(t[n]=e);return Object.freeze(t)}async function Nt(o,t){if(!t)return Pt;if(o.HX_ORA_URL&&o.HX_API_KEY)try{let s=await fetch(`${o.HX_ORA_URL}/internal/secrets`,{headers:{Authorization:o.HX_API_KEY}});if(s.ok){let r=await s.json();if(r.secrets)return uo(r.secrets)}else console.warn(`[secrets] API failed with status ${s.status}, falling back to KV`)}catch(s){console.error("[secrets] API request failed, falling back to KV",s)}let n=o.ORA_SECRETS;if(!n)return Pt;let e=`${t}:`;try{let s=await n.list({prefix:e,limit:1e3});s.list_complete===!1&&console.warn(`[secrets] tenant=${t} exceeded list page; truncating to first 1000 keys`);let r=s.keys.filter(d=>!_e(d.name.slice(e.length))),i=await Promise.all(r.map(async d=>{let u=await n.get(d.name);return u!==null?[d.name.slice(e.length),u]:null})),c={};for(let d of i){if(!d)continue;let[u,p]=d;u&&(c[u]=p)}return Object.freeze(c)}catch(s){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:t,err:s}),Pt}}import{nanoid as Zn}from"nanoid";function it(o){var s,r;let t=(s=o==null?void 0:o.flowData)==null?void 0:s.state,e=((t==null?void 0:t.nodes)??((r=o==null?void 0:o.flowData)==null?void 0:r.nodes)??[]).find(i=>i.type==="startNode");return e==null?void 0:e.data}async function $e(o,t){return typeof t.cycle=="number"&&Number.isFinite(t.cycle)?t.cycle+1:await Ne(o)+1}function ke(o,t,n,e,s){let r=pt(it(n));return{...t,memoryConfig:r,cycle:e,setContext:async c=>{await he(o,c),await(s==null?void 0:s(c.ref))},getContextIndex:async()=>ht(o),getContextData:async c=>xe(o,c),getContext:async c=>Rt(o,c),resolveContext:async c=>Ie(o,c),pruneContext:async c=>Te(o,c)}}import{nanoid as So}from"nanoid";async function Fe(o,t){return o.length?!t||!t.HX_ORA_URL||!t.HX_API_KEY?(console.error("extractDocuments: missing HX_ORA_URL or HX_API_KEY"),o.map(e=>({name:e.name,text:""}))):await Promise.all(o.map(async e=>{try{let s=await fetch(`${t.HX_ORA_URL}/internal/files/extract`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t.HX_API_KEY},body:JSON.stringify(e)});if(!s.ok)return console.error(`extractDocuments: ${e.name} failed ${s.status}`),{name:e.name,text:""};let r=await s.json();return{name:e.name,text:r.text||""}}catch(s){return console.error(`extractDocuments: ${e.name} threw`,s),{name:e.name,text:""}}})):[]}function po(o,t,n){var e,s,r,i;return et(((s=(e=n.flowData)==null?void 0:e.state)==null?void 0:s.nodes)??[],((i=(r=n.flowData)==null?void 0:r.state)==null?void 0:i.edges)??[],t.id).some(c=>c.ref===o&&(c.type==="image"||c.type==="file"))}function fo(o,t){var i,c,d,u,p,g,l;let n=Array.isArray((i=o.data)==null?void 0:i.outputMapping)?o.data.outputMapping:[];if(n.length===0)return null;let e=((d=(c=t.flowData)==null?void 0:c.state)==null?void 0:d.nodes)||[],s={},r=new Set;for(let f of n){let a=(u=f.key)==null?void 0:u.trim(),m=(p=f.from)==null?void 0:p.trim();if(!a||!m)throw new Error(`Answer node ${o.id} has an incomplete variable mapping`);if(r.has(a))throw new Error(`Answer node ${o.id} has duplicate output key "${a}"`);if(po(m,o,t))throw new Error(`Answer node ${o.id} cannot persist binary source "${m}"`);let y=K(m,{context:t.context||{},results:t.results||{},nodes:e,edges:((l=(g=t.flowData)==null?void 0:g.state)==null?void 0:l.edges)??[],currentNodeId:o.id}),w=y.value;if(y.missing||w===void 0||w===null){if(f.default===void 0)throw new V(y.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Answer node ${o.id} could not resolve output "${m}"`);w=f.default}s[a]=w,r.add(a)}try{JSON.stringify(s)}catch{throw new Error(`Answer node ${o.id} produced a value that is not JSON serializable`)}return s}async function Dt(o,t,n,e,s,r,i){var d,u,p;e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c;try{c=fo(t,n)}catch(g){throw e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(g)}}),g}c&&o.outputCollector&&o.outputCollector.add(t.id,c);try{let g=await((d=o.getMessages)==null?void 0:d.call(o))??[],l=((u=g[g.length-1])==null?void 0:u.type)==="text"?g[g.length-1].content:"NO-TEXT";i==null||i({type:"answer_node",payload:{userMessage:(p=n==null?void 0:n.context)==null?void 0:p.user_input,answer:l}})}catch(g){console.error("answerNodeRunner: failed to emit answer telemetry:",g),e==null||e({type:"debug",content:"Warning: failed to emit answer telemetry"})}s==null||s(t.id,{type:"answerNode",message:"Answer response for: "+t.data.response,saved:!0,persistenceRequested:!!c&&!!o.outputCollector,persisted:!1,...o.runId?{runId:o.runId}:{}}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"success"}})}function G(o,t,n,e,s){var c,d,u,p,g;let r=(s==null?void 0:s.callerTag)??"llmNodeRunner",i=(s==null?void 0:s.serializeNonStrings)??!1;return le(o,t,{context:n.context??{},results:n.results??{},nodes:((d=(c=n.flowData)==null?void 0:c.state)==null?void 0:d.nodes)??[],edges:((p=(u=n.flowData)==null?void 0:u.state)==null?void 0:p.edges)??[],currentNodeId:t.id,secrets:(g=s==null?void 0:s.sessionEnv)==null?void 0:g.secrets},{callerTag:r,serializeNonStrings:i,onError:l=>{e==null||e({type:`error:${r}`,content:l})}})}var Ut="[redacted]",Pe=8*1024;function mo(o){if(o==null)return{value:o,truncated:!1};let t=typeof o=="string"?o:JSON.stringify(o),n=new TextEncoder().encode(t);if(n.byteLength<=Pe){if(typeof o=="string")return{value:o,truncated:!1};try{return{value:JSON.parse(t),truncated:!1}}catch{return{value:t,truncated:!1}}}let e=n.slice(0,Pe);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(e),truncated:!0}}function go(o,t){let n={};for(let e of ft(o))n[e.name]=mt(t,e.path??"");return n}var Mt=(o,t,n,e,s)=>G(o,t,n,s,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:e});async function bt(o,t,n,e,s,r,i){var u,p,g,l,f,a;`${t.id}`,e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c=null,d=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(n.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(n.results||{}));let m=((u=t.data)==null?void 0:u.url)||"",y=Mt(m,t,n,o,e);if(console.log("[apiNodeRunner] resolved url:",B(m)?st(y):y),!y){e==null||e({type:"error:apiNodeRunner",content:"Missing url"}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:"Missing url"}}),s==null||s(t.id,c);return}let w=(((p=t.data)==null?void 0:p.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",w);let h=((g=t.data)==null?void 0:g.headers)||{},I={},R={};for(let M in h)if(Object.prototype.hasOwnProperty.call(h,M)){let X=String(h[M]??"");R[M]=B(X),I[M]=Mt(X,t,n,o,e)}let x,O=!1;if(w!=="GET"&&w!=="HEAD"&&((l=t.data)==null?void 0:l.body)!==void 0){let M=typeof t.data.body=="string"?t.data.body:JSON.stringify(t.data.body);O=B(M),x=Mt(M,t,n,o,e),!I["Content-Type"]&&!I["content-type"]&&(I["Content-Type"]="application/json")}let C={};for(let M in I)C[M]=R[M]?Ut:I[M];console.log("[apiNodeRunner] headers:",JSON.stringify(C)),console.log("[apiNodeRunner] body:",O?Ut:x),e==null||e({type:"info:apiNodeRunner:request",content:{nodeId:t.id,method:w,url:B(m)?st(y):y,headers:C,body:O?Ut:x}});let D=Number((f=t.data)==null?void 0:f.timeoutMs),j=new AbortController,k=Number.isFinite(D)&&D>0?setTimeout(()=>j.abort(),D):null,_;try{console.log("[apiNodeRunner] fetching..."),_=await fetch(y,{method:w,headers:I,body:x,signal:j.signal}),console.log("[apiNodeRunner] fetch returned status:",_.status)}finally{k&&clearTimeout(k)}let L=_.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",L);let N;L.includes("application/json")?N=await _.json():N=await _.text(),console.log("[apiNodeRunner] payload preview:",typeof N=="string"?N.slice(0,200):JSON.stringify(N).slice(0,200)),c={ok:_.ok,status:_.status,data:N};let T=Date.now()-d;i==null||i({type:"api_call",payload:{nodeId:t.id,url:y,method:w,status:_.status,latencyMs:T}});let{value:F,truncated:U}=mo(N);e==null||e({type:"info:apiNodeRunner:response",content:{nodeId:t.id,ok:_.ok,status:_.status,latencyMs:T,data:F,truncated:U,outVars:go(t,c)}}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"success"}})}catch(m){console.error("Error processing ApiNode:",m),e==null||e({type:"error:apiNodeRunner",content:`API node execution failed: ${m}`}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(m)}})}finally{console.log("[apiNodeRunner] final result:",(a=JSON.stringify(c))==null?void 0:a.slice(0,300)),s==null||s(t.id,c)}}var yo="[redacted]",De=8*1024;function Et(o,t){if(typeof o=="string")return B(o)?typeof t=="string"&&/^https?:\/\//i.test(t)?st(t):yo:t;if(o&&typeof o=="object"&&!Array.isArray(o)){let n={},e=t&&typeof t=="object"&&!Array.isArray(t)?t:{};for(let[s,r]of Object.entries(o))n[s]=Et(r,e[s]);return n}if(Array.isArray(o)){let n=Array.isArray(t)?t:[];return o.map((e,s)=>Et(e,n[s]))}return t}function wo(o){if(o==null)return{value:o,truncated:!1};let t=typeof o=="string"?o:JSON.stringify(o),n=new TextEncoder().encode(t);if(n.byteLength<=De){if(typeof o=="string")return{value:o,truncated:!1};try{return{value:JSON.parse(t),truncated:!1}}catch{return{value:t,truncated:!1}}}let e=n.slice(0,De);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(e),truncated:!0}}function ho(o,t){let n={};for(let e of ft(o))n[e.name]=mt(t,e.path??"");return n}var Ro=(o,t,n,e,s)=>G(o,t,n,s,{callerTag:"toolNodeRunner",serializeNonStrings:!0,sessionEnv:e});function At(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:{}}function xo(o){let t=At(o);if(Array.isArray(t.enum)&&t.enum.length>0)return t.enum.every(s=>typeof s=="string"||typeof s=="number")?"enum":"unsupported";switch(Array.isArray(t.type)?t.type.find(e=>typeof e=="string"&&e!=="null"):t.type){case"string":return"string";case"number":return"number";case"integer":return"integer";case"boolean":return"boolean";case"object":return"object";case"array":return"array";default:return"unsupported"}}function Io(o,t){var i,c;let n={},e={},s=((i=o.data)==null?void 0:i.inputSchema)??t;if(s&&typeof s=="object"&&!Array.isArray(s)){e=At(At(s).properties);for(let[d,u]of Object.entries(e))n[d]=xo(u);return{types:n,properties:e}}let r=(c=o.data)==null?void 0:c.argTypes;if(r&&typeof r=="object"&&!Array.isArray(r))for(let[d,u]of Object.entries(r))typeof u=="string"&&(n[d]=u);return{types:n,properties:e}}function To(o,t,n){if(o.trim()!==""){if(o==="null"&&t&&t!=="string"&&t!=="enum")return null;switch(t){case"string":return o;case"enum":{let e=At(n).enum;if(Array.isArray(e)){let s=e.find(r=>String(r)===o);if(s!==void 0)return s}return o}case"number":{let e=Number(o);return Number.isFinite(e)?e:o}case"integer":{let e=Number.parseInt(o,10);return Number.isFinite(e)?e:o}case"boolean":return o==="true"?!0:o==="false"?!1:o;case"object":case"array":case"unsupported":try{return JSON.parse(o)}catch{return o}default:return o}}}function No(o){return o===void 0||typeof o=="string"&&o.trim()===""}function jt(o,t,n,e,s,r,i){if(typeof o=="string"){let c=o.includes("{{")?Ro(o,t,n,e,s):o;return To(c,r,i)}if(o&&typeof o=="object"&&!Array.isArray(o)){let c={};for(let[d,u]of Object.entries(o))c[d]=jt(u,t,n,e,s);return c}return Array.isArray(o)?o.map(c=>jt(c,t,n,e,s)):o}function Ao(o,t,n,e,s,r){let i={};for(let[c,d]of Object.entries(o)){let u=jt(d,t,n,e,s,r.types[c],r.properties[c]);No(u)||(i[c]=u)}return i}async function Co(o){if(o.toolCatalog)return o.toolCatalog;if(!o.env)return o.toolCatalog={},o.toolCatalog;let t=await de(o.env),n={};for(let e of t)e!=null&&e.id&&(n[e.id]=e);return o.toolCatalog=n,n}async function Oo(o){if(o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs={},o.toolDefs;let t=await gt(o.env),n={};for(let e of t)e!=null&&e.id&&(n[e.id]=e);return o.toolDefs=n,n}async function Lt(o,t,n,e,s,r,i){var p,g,l,f,a,m,y,w,h,I,R,x;`${t.id}`,e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c={ok:!1,data:null,error:null},d=Date.now(),u=((p=t.data)==null?void 0:p.source)==="http"?"http":"catalog";try{let O=(g=t.data)!=null&&g.args&&typeof t.data.args=="object"&&!Array.isArray(t.data.args)?t.data.args:{},C,D;if(u==="http"){let T=typeof((l=t.data)==null?void 0:l.toolId)=="string"?t.data.toolId.trim():"";if(!T)throw new Error("HTTP tool nodes require toolId");if(D=(await Oo(o))[T],!D)throw new Error(`Tool ${T} not found`);C=D.inputSchema}let j=Io(t,C),k=Ao(O,t,n,o,e,j);if(e==null||e({type:"info:toolNodeRunner:request",content:{nodeId:t.id,source:u,catalogId:(f=t.data)==null?void 0:f.catalogId,toolSlug:(a=t.data)==null?void 0:a.toolSlug,toolId:(m=t.data)==null?void 0:m.toolId,args:Et(O,k)}}),u==="catalog"){let T=typeof((y=t.data)==null?void 0:y.catalogId)=="string"?t.data.catalogId.trim():"",F=typeof((w=t.data)==null?void 0:w.toolSlug)=="string"?t.data.toolSlug.trim():"";if(!T||!F)throw new Error("Catalog tool nodes require catalogId and toolSlug");let M=(await Co(o))[T];if(!M)throw new Error(`Tool catalog entry ${T} not found or disabled`);let X=typeof((h=t.data)==null?void 0:h.toolVersion)=="string"?t.data.toolVersion.trim():"",b=await ue(o,{toolSlug:F,connectionScope:M.connectionScope,toolVersion:X||null,toolkitVersion:M.toolkitVersion,arguments:k});c={ok:b.ok,data:b.ok?b.data:null,error:b.ok?null:b.error??"Tool execution failed"}}else{let T=yt(D,o,n,e);if(!T.execute)throw new Error(`Tool ${(I=t.data)==null?void 0:I.toolId} is missing an execute handler`);let F=await T.execute(k,{}),U=F&&typeof F=="object"&&"error"in F&&F.error?String(F.error):null;c={ok:!U,data:F,error:U}}let _=Date.now()-d;i==null||i({type:"tool_call",payload:{nodeId:t.id,url:u==="catalog"?`composio:${((R=t.data)==null?void 0:R.toolSlug)??""}`:`tool:${((x=t.data)==null?void 0:x.toolId)??""}`,method:"EXECUTE",status:c.ok?200:502,latencyMs:_}});let{value:L,truncated:N}=wo(c.data);e==null||e({type:"info:toolNodeRunner:response",content:{nodeId:t.id,ok:c.ok,latencyMs:_,data:L,truncated:N,error:c.error,outVars:ho(t,c)}}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:c.ok?"success":"error",error:c.error??void 0}})}catch(O){let C=O instanceof Error?O.message:String(O);c={ok:!1,data:null,error:C},e==null||e({type:"error:toolNodeRunner",content:`Tool node execution failed: ${C}`}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:C}})}finally{s==null||s(t.id,c)}}import{generateObject as _o}from"ai";import{z as Ue}from"zod";async function Ht(o,t,n,e,s,r,i){var a,m,y,w,h,I,R;e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c=String(((a=t==null?void 0:t.data)==null?void 0:a.input_variable)||"user_input").trim(),d;try{let x=K(c,{context:n.context??{},results:n.results??{},nodes:((y=(m=n.flowData)==null?void 0:m.state)==null?void 0:y.nodes)??[],edges:((h=(w=n.flowData)==null?void 0:w.state)==null?void 0:h.edges)??[],currentNodeId:t.id});if(x.missing)throw new Error(`Classifier input "${c}" did not produce a value`);d=x.value}catch(x){throw e==null||e({type:"error:classifier",content:String(x)}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(x)}}),x}let u=Array.isArray((I=t==null?void 0:t.data)==null?void 0:I.items)?t.data.items:[];if(u.length===0){e==null||e({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let p=String((R=u[u.length-1])==null?void 0:R.id);if(!d||String(d).trim().length===0){e==null||e({type:"warning:classifier",content:"No input for classification \u2014 falling back to last item."}),s==null||s(t.id,{classification:p}),n.context=n.context||{},n.context.classified_id=p,r==null||r(n);return}let l=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
|
|
1
|
+
import{a as ae}from"./chunk-ELMOSEQ7.js";import{a as Z,b as st,c as ce,d as wt}from"./chunk-EZIUCT77.js";import{a as ge}from"./chunk-OF6G42DM.js";import"./chunk-MOYYZBTC.js";import{a as ye,b as we}from"./chunk-CDGUEX3J.js";import{A as de,B as ue,C as ht,D as zn,E as Wn,F as Gn,G as Yn,H as Bn,I as Zn,J as pe,K as Qn,L as fe,M as Rt,N as xt,O as me,P as vn,Q as ts,a as j,b as lt,c as An,d as nt,e as Qt,f as kn,g as On,h as _n,i as $n,j as dt,k as Mn,l as ut,m as pt,n as vt,o as ft,p as te,q as ee,r as Mt,s as oe,t as ne,u as Vn,v as Kn,w as Xn,x as le,y as qn,z as Jn}from"./chunk-Y2NRJIHX.js";import{a as B,b as Nn,c as v,d as Bt,e as Zt,f as Pn,g as bn,h as se,i as mt,j as Fn,k as tt,l as Dn,m as Cn,n as Un,o as En,p as V,q as gt,r as q,s as jn,t as Ln,u as Hn,v as Sn,w as re}from"./chunk-VLZKZDRV.js";import{a as yn}from"./chunk-RYHQGPX5.js";import{a as wn}from"./chunk-R6EKV3WR.js";import{a as xn}from"./chunk-6HY7QUMP.js";import{a as hn,b as Rn}from"./chunk-V6JSMX5A.js";import{a as G,b as Q,c as Tn,d as Yt,e as In}from"./chunk-G3SGJ7XJ.js";import{a as ot}from"./chunk-U56YWPSI.js";import{a as yt,b as ie}from"./chunk-A2IRPAD4.js";import{a as ct}from"./chunk-3TXHFKDN.js";import{Agent as tn}from"agents";import{nanoid as en}from"nanoid";var S=(o,t,n)=>{o.send(t+"::"+n)};async function to(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 he(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 Tt(o){o.sql`DELETE FROM messages`}async function Re(o){await to(o)}function Pt(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 eo="anonymous:";function xe(o,t){return(o==null?void 0:o.trim())||`${eo}${t}`}async function bt(o,t){if(!It(o))return null;let n=await fetch(`${o.HX_ORA_URL}/internal/runs`,{method:"POST",headers:Pt(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:Pt(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 Nt(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:Pt(o),body:JSON.stringify(n)});if(r.ok||r.status===409)return!0;if(r.status===404)return console.error(`[oraTriggers] completeRun ${t} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${t} attempt ${s} failed with ${r.status}`)}catch(r){console.warn(`[oraTriggers] completeRun ${t} attempt ${s} threw`,r)}s<e&&await new Promise(r=>setTimeout(r,250*s))}return console.error(`[oraTriggers] completeRun ${t} exhausted ${e} attempts; hx-ora will time the run out`),!1}async function Te(o,t){if(!It(o))return Promise.resolve();try{return await bt(o,t)}catch(n){return console.error("[oraTriggers] recordRun failed",n),null}}var Ft=Object.freeze({}),oo="__SYSTEM_";function Ie(o){return o.startsWith(oo)}function no(o){let t={};for(let[n,e]of Object.entries(o))Ie(n)||(t[n]=e);return Object.freeze(t)}async function At(o,t){if(!t)return Ft;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 no(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 Ft;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(c=>!Ie(c.name.slice(e.length))),i=await Promise.all(r.map(async c=>{let u=await n.get(c.name);return u!==null?[c.name.slice(e.length),u]:null})),a={};for(let c of i){if(!c)continue;let[u,p]=c;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}),Ft}}function kt(o){var s;let t=((s=o==null?void 0:o.flowData)==null?void 0:s.state)??(o==null?void 0:o.flowData),e=((t==null?void 0:t.nodes)??[]).find(r=>r.type==="startNode");return e==null?void 0:e.data}import{nanoid as Zo}from"nanoid";async function Ne(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 so(o,t,n){var e,s,r,i;return tt(((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 ro(o,t){var i,a,c,u,p,g,d;let n=Array.isArray((i=o.data)==null?void 0:i.outputMapping)?o.data.outputMapping:[];if(n.length===0)return null;let e=((c=(a=t.flowData)==null?void 0:a.state)==null?void 0:c.nodes)||[],s={},r=new Set;for(let m of n){let l=(u=m.key)==null?void 0:u.trim(),f=(p=m.from)==null?void 0:p.trim();if(!l||!f)throw new Error(`Answer node ${o.id} has an incomplete variable mapping`);if(r.has(l))throw new Error(`Answer node ${o.id} has duplicate output key "${l}"`);if(so(f,o,t))throw new Error(`Answer node ${o.id} cannot persist binary source "${f}"`);let y=q(f,{context:t.context||{},results:t.results||{},nodes:e,edges:((d=(g=t.flowData)==null?void 0:g.state)==null?void 0:d.edges)??[],currentNodeId:o.id}),h=y.value;if(y.missing||h===void 0||h===null){if(m.default===void 0)throw new V(y.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Answer node ${o.id} could not resolve output "${f}"`);h=m.default}s[l]=h,r.add(l)}try{JSON.stringify(s)}catch{throw new Error(`Answer node ${o.id} produced a value that is not JSON serializable`)}return s}async function Dt(o,t,n,e,s,r,i){var c,u,p;e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let a;try{a=ro(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((c=o.getMessages)==null?void 0:c.call(o))??[],d=((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:d}})}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 W(o,t,n,e,s){var a,c,u,p,g;let r=(s==null?void 0:s.callerTag)??"llmNodeRunner",i=(s==null?void 0:s.serializeNonStrings)??!1;return re(o,t,{context:n.context??{},results:n.results??{},nodes:((c=(a=n.flowData)==null?void 0:a.state)==null?void 0:c.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:d=>{e==null||e({type:`error:${r}`,content:d})}})}var Ct="[redacted]",Ae=8*1024;function io(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<=Ae){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,Ae);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(e),truncated:!0}}function ao(o,t){let n={};for(let e of mt(o))n[e.name]=gt(t,e.path??"");return n}var Ut=(o,t,n,e,s)=>W(o,t,n,s,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:e});async function Et(o,t,n,e,s,r,i){var u,p,g,d,m,l;`${t.id}`,e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let a=null,c=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(n.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(n.results||{}));let f=((u=t.data)==null?void 0:u.url)||"",y=Ut(f,t,n,o,e);if(console.log("[apiNodeRunner] resolved url:",Z(f)?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 h=(((p=t.data)==null?void 0:p.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",h);let w=((g=t.data)==null?void 0:g.headers)||{},R={},x={};for(let k in w)if(Object.prototype.hasOwnProperty.call(w,k)){let b=String(w[k]??"");x[k]=Z(b),R[k]=Ut(b,t,n,o,e)}let I,$=!1;if(h!=="GET"&&h!=="HEAD"&&((d=t.data)==null?void 0:d.body)!==void 0){let k=typeof t.data.body=="string"?t.data.body:JSON.stringify(t.data.body);$=Z(k),I=Ut(k,t,n,o,e),!R["Content-Type"]&&!R["content-type"]&&(R["Content-Type"]="application/json")}let O={};for(let k in R)O[k]=x[k]?Ct:R[k];console.log("[apiNodeRunner] headers:",JSON.stringify(O)),console.log("[apiNodeRunner] body:",$?Ct:I),e==null||e({type:"info:apiNodeRunner:request",content:{nodeId:t.id,method:h,url:Z(f)?st(y):y,headers:O,body:$?Ct:I}});let F=Number((m=t.data)==null?void 0:m.timeoutMs),H=new AbortController,M=Number.isFinite(F)&&F>0?setTimeout(()=>H.abort(),F):null,N;try{console.log("[apiNodeRunner] fetching..."),N=await fetch(y,{method:h,headers:R,body:I,signal:H.signal}),console.log("[apiNodeRunner] fetch returned status:",N.status)}finally{M&&clearTimeout(M)}let U=N.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",U);let D;U.includes("application/json")?D=await N.json():D=await N.text(),console.log("[apiNodeRunner] payload preview:",typeof D=="string"?D.slice(0,200):JSON.stringify(D).slice(0,200)),a={ok:N.ok,status:N.status,data:D};let C=Date.now()-c;i==null||i({type:"api_call",payload:{nodeId:t.id,url:y,method:h,status:N.status,latencyMs:C}});let{value:L,truncated:T}=io(D);e==null||e({type:"info:apiNodeRunner:response",content:{nodeId:t.id,ok:N.ok,status:N.status,latencyMs:C,data:L,truncated:T,outVars:ao(t,a)}}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"success"}})}catch(f){console.error("Error processing ApiNode:",f),e==null||e({type:"error:apiNodeRunner",content:`API node execution failed: ${f}`}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(f)}})}finally{console.log("[apiNodeRunner] final result:",(l=JSON.stringify(a))==null?void 0:l.slice(0,300)),s==null||s(t.id,a)}}var co="[redacted]",ke=8*1024;function jt(o,t){if(typeof o=="string")return Z(o)?typeof t=="string"&&/^https?:\/\//i.test(t)?st(t):co: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 lo(o){if(o==null)return{value:o,truncated:!1};let t=typeof o=="string"?o:JSON.stringify(o),n=new TextEncoder().encode(t);if(n.byteLength<=ke){if(typeof o=="string")return{value:o,truncated:!1};try{return{value:JSON.parse(t),truncated:!1}}catch{return{value:t,truncated:!1}}}let e=n.slice(0,ke);return{value:new TextDecoder("utf-8",{fatal:!1}).decode(e),truncated:!0}}function uo(o,t){let n={};for(let e of mt(o))n[e.name]=gt(t,e.path??"");return n}var po=(o,t,n,e,s)=>W(o,t,n,s,{callerTag:"toolNodeRunner",serializeNonStrings:!0,sessionEnv:e});function Ot(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:{}}function fo(o){let t=Ot(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 mo(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=Ot(Ot(s).properties);for(let[c,u]of Object.entries(e))n[c]=fo(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[c,u]of Object.entries(r))typeof u=="string"&&(n[c]=u);return{types:n,properties:e}}function go(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=Ot(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 yo(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("{{")?po(o,t,n,e,s):o;return go(a,r,i)}if(o&&typeof o=="object"&&!Array.isArray(o)){let a={};for(let[c,u]of Object.entries(o))a[c]=Lt(u,t,n,e,s);return a}return Array.isArray(o)?o.map(a=>Lt(a,t,n,e,s)):o}function wo(o,t,n,e,s,r){let i={};for(let[a,c]of Object.entries(o)){let u=Lt(c,t,n,e,s,r.types[a],r.properties[a]);yo(u)||(i[a]=u)}return i}async function ho(o){if(o.toolCatalog)return o.toolCatalog;if(!o.env)return o.toolCatalog={},o.toolCatalog;let t=await ie(o.env),n={};for(let e of t)e!=null&&e.id&&(n[e.id]=e);return o.toolCatalog=n,n}async function Ro(o){if(o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs={},o.toolDefs;let t=await yt(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,d,m,l,f,y,h,w,R,x,I;`${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},c=Date.now(),u=((p=t.data)==null?void 0:p.source)==="http"?"http":"catalog";try{let $=(g=t.data)!=null&&g.args&&typeof t.data.args=="object"&&!Array.isArray(t.data.args)?t.data.args:{},O,F;if(u==="http"){let C=typeof((d=t.data)==null?void 0:d.toolId)=="string"?t.data.toolId.trim():"";if(!C)throw new Error("HTTP tool nodes require toolId");if(F=(await Ro(o))[C],!F)throw new Error(`Tool ${C} not found`);O=F.inputSchema}let H=mo(t,O),M=wo($,t,n,o,e,H);if(e==null||e({type:"info:toolNodeRunner:request",content:{nodeId:t.id,source:u,catalogId:(m=t.data)==null?void 0:m.catalogId,toolSlug:(l=t.data)==null?void 0:l.toolSlug,toolId:(f=t.data)==null?void 0:f.toolId,args:jt($,M)}}),u==="catalog"){let C=typeof((y=t.data)==null?void 0:y.catalogId)=="string"?t.data.catalogId.trim():"",L=typeof((h=t.data)==null?void 0:h.toolSlug)=="string"?t.data.toolSlug.trim():"";if(!C||!L)throw new Error("Catalog tool nodes require catalogId and toolSlug");let k=(await ho(o))[C];if(!k)throw new Error(`Tool catalog entry ${C} not found or disabled`);let b=typeof((w=t.data)==null?void 0:w.toolVersion)=="string"?t.data.toolVersion.trim():"",E=await ae(o,{toolSlug:L,connectionScope:k.connectionScope,toolVersion:b||null,toolkitVersion:k.toolkitVersion,arguments:M});a={ok:E.ok,data:E.ok?E.data:null,error:E.ok?null:E.error??"Tool execution failed"}}else{let C=wt(F,o,n,e);if(!C.execute)throw new Error(`Tool ${(R=t.data)==null?void 0:R.toolId} is missing an execute handler`);let L=await C.execute(M,{}),T=L&&typeof L=="object"&&"error"in L&&L.error?String(L.error):null;a={ok:!T,data:L,error:T}}let N=Date.now()-c;i==null||i({type:"tool_call",payload:{nodeId:t.id,url:u==="catalog"?`composio:${((x=t.data)==null?void 0:x.toolSlug)??""}`:`tool:${((I=t.data)==null?void 0:I.toolId)??""}`,method:"EXECUTE",status:a.ok?200:502,latencyMs:N}});let{value:U,truncated:D}=lo(a.data);e==null||e({type:"info:toolNodeRunner:response",content:{nodeId:t.id,ok:a.ok,latencyMs:N,data:U,truncated:D,error:a.error,outVars:uo(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($){let O=$ instanceof Error?$.message:String($);a={ok:!1,data:null,error:O},e==null||e({type:"error:toolNodeRunner",content:`Tool node execution failed: ${O}`}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:O}})}finally{s==null||s(t.id,a)}}import{generateObject as $o}from"ai";import{z as Oe}from"zod";import{openai as xo}from"@ai-sdk/openai";import{extractReasoningMiddleware as To,wrapLanguageModel as Io}from"ai";import{createWorkersAI as No}from"workers-ai-provider";import{xai as Ao}from"@ai-sdk/xai";import{anthropic as ko}from"@ai-sdk/anthropic";import{createOpenRouter as Oo}from"@openrouter/ai-sdk-provider";var Vt={};function St(o){if(o!=null){if(typeof o!="string")return o;try{return JSON.parse(o)}catch{return}}}function _o(o){return{...o,defaultParams:St(o.defaultParams)??o.defaultParams,capabilities:St(o.capabilities)??o.capabilities,price:St(o.price)??o.price}}async function et(o,t,n){var p,g;if(!(t!=null&&t.getOraModel))throw new Error("resolveModelById requires a sessionEnv with getOraModel capable of fetching models dynamically.");let e=await t.getOraModel(o);if(!e)return;let s=_o(e),r=((p=s.capabilities)==null?void 0:p.params)??le(s),{effectiveParams:i,adjustments:a}=ue(s.defaultParams,n,r),c;if(Vt[s.provider])c=await Vt[s.provider](s,t,n);else if(s.provider==="openai")c=xo(s.providerModel);else if(s.provider==="xai")c=Ao(s.providerModel);else if(s.provider==="anthropic")c=ko(s.providerModel);else if(s.provider==="openrouter")c=Oo()(s.providerModel);else if(s.provider==="workersai"||s.provider==="cloudflare"){if(!((g=t==null?void 0:t.env)!=null&&g.AI))throw new Error("Workers AI provider requires sessionEnv.env.AI binding");c=No({binding:t.env.AI})(s.providerModel)}else c={provider:s.provider,providerModel:s.providerModel};let u=pe(s);return u.kind==="tag"&&c&&typeof c=="object"&&"specificationVersion"in c&&(c=Io({model:c,middleware:To({tagName:u.tagName??"think",startWithReasoning:u.startWithReasoning??!1})})),{provider:s.provider,modelHandle:c,entry:s,effectiveParams:i,paramAdjustments:a.length>0?a:void 0,reasoning:u}}function Us(o,t){Vt[o]=t}async function Kt(o,t,n,e,s,r,i){var l,f,y,h,w,R,x;e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let a=String(((l=t==null?void 0:t.data)==null?void 0:l.input_variable)||"user_input").trim(),c;try{let I=q(a,{context:n.context??{},results:n.results??{},nodes:((y=(f=n.flowData)==null?void 0:f.state)==null?void 0:y.nodes)??[],edges:((w=(h=n.flowData)==null?void 0:h.state)==null?void 0:w.edges)??[],currentNodeId:t.id});if(I.missing)throw new Error(`Classifier input "${a}" did not produce a value`);c=I.value}catch(I){throw e==null||e({type:"error:classifier",content:String(I)}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(I)}}),I}let u=Array.isArray((R=t==null?void 0:t.data)==null?void 0:R.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((x=u[u.length-1])==null?void 0:x.id);if(!c||String(c).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 d=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
|
|
18
2
|
If the message is ambiguous or none clearly matches, choose the LAST category in the list.
|
|
19
3
|
|
|
20
4
|
Categories:
|
|
21
|
-
${u.map(
|
|
22
|
-
label: ${
|
|
23
|
-
keywords/topics: ${
|
|
5
|
+
${u.map(I=>{let $=I.keywords??I["keywords/topics"]??"",O=Array.isArray($)?$.join(", "):String($||"");return`- id: ${I.id}
|
|
6
|
+
label: ${I.label}
|
|
7
|
+
keywords/topics: ${O}`}).join(`
|
|
24
8
|
`)}
|
|
25
|
-
`,
|
|
26
|
-
"""${String(
|
|
9
|
+
`,m=`User message:
|
|
10
|
+
"""${String(c).trim()}"""
|
|
27
11
|
|
|
28
|
-
Select the best matching category id.`;try{let
|
|
12
|
+
Select the best matching category id.`;try{let I=Date.now(),$=u.map(C=>String(C.id)),O="gpt_4_1_mini",F=await et(O,o);if(!F)throw new Error(`Model '${O}' not found in registry`);let{modelHandle:H,effectiveParams:M}=F,N=await $o({model:H,messages:[{role:"system",content:d},{role:"user",content:m}],schema:Oe.object({classification:Oe.enum($).describe("The id of the best matching category")}),temperature:M.temperature??0}),U=Date.now()-I,D=N.object.classification;i==null||i({type:"class_telemetry",payload:{nodeId:t.id,totalLatency:U,model:N.response.modelId,usage:N.usage,options:$}}),i==null||i({type:"class_result",payload:{result:N}}),s==null||s(t.id,{classification:D}),n.context=n.context||{},n.context.classified_id=D,r==null||r(n),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"success"}})}catch(I){throw e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(I)}}),I}}import{stepCountIs as Fo,streamText as Do}from"ai";import{nanoid as Co}from"nanoid";import"zod";function _e(o,t){var a,c,u,p,g;let n=((a=o.data)==null?void 0:a.attachments)??[];if(!Array.isArray(n))throw new V("INVALID_EXPRESSION",`Node ${o.id} attachments must be an array`);let e=((u=(c=t.flowData)==null?void 0:c.state)==null?void 0:u.nodes)??[],s=((g=(p=t.flowData)==null?void 0:p.state)==null?void 0:g.edges)??[],r=tt(e,s,o.id),i="";for(let d of n){if(typeof d!="string")throw new V("INVALID_EXPRESSION",`Node ${o.id} has an invalid attachment reference`);let m=r.find(f=>f.ref===d);if(!m)throw new V("OUT_OF_SCOPE",`Attachment "${d}" is not in this node's connection scope`);if(m.type!=="file"&&m.type!=="image")throw new V("UNKNOWN_OUTPUT",`Attachment "${d}" is not an image or file output`);if(m.type!=="file")continue;let l=q(d,{context:t.context??{},results:t.results??{},nodes:e,edges:s,currentNodeId:o.id});if(l.missing)throw new V(l.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${d}" did not produce a value`);if(typeof l.value!="string")throw new V("PATH_NOT_FOUND",`Attachment "${d}" must resolve to file text`);l.value.trim()&&(i+=(i?`
|
|
29
13
|
|
|
30
|
-
`:"")+a.value)}return i}function $o(o,t){var s,r,i,c,d;let n=((s=o.data)==null?void 0:s.attachments)??[];if(!Array.isArray(n))throw new V("INVALID_EXPRESSION",`Node ${o.id} attachments must be an array`);let e=et(((i=(r=t.flowData)==null?void 0:r.state)==null?void 0:i.nodes)??[],((d=(c=t.flowData)==null?void 0:c.state)==null?void 0:d.edges)??[],o.id);return n.map(u=>{if(typeof u!="string")throw new V("INVALID_EXPRESSION",`Node ${o.id} has an invalid attachment reference`);let p=e.find(g=>g.ref===u);if(!p)throw new V("OUT_OF_SCOPE",`Attachment "${u}" is not in this node's connection scope`);if(p.type!=="image"&&p.type!=="file")throw new V("UNKNOWN_OUTPUT",`Attachment "${u}" is not a binary output`);return p.type==="image"?u:null}).filter(u=>u!==null)}function be(o,t){var s,r,i,c;let n=[],e={context:t.context??{},results:t.results??{},nodes:((r=(s=t.flowData)==null?void 0:s.state)==null?void 0:r.nodes)??[],edges:((c=(i=t.flowData)==null?void 0:i.state)==null?void 0:c.edges)??[],currentNodeId:o.id};for(let d of $o(o,t)){let u=K(d,e);if(u.missing)throw new V(u.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${d}" did not produce a value`);if(!Array.isArray(u.value))throw new V("PATH_NOT_FOUND",`Attachment "${d}" must resolve to an image array`);n.push(...u.value)}return n}var ko=lt({"../tools/composioDirectTool.ts":()=>import("./composioDirectTool-H3GSCIPY.js"),"../tools/composioTool.ts":()=>import("./composioTool-5LFWUQ7F.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-LSNJKMPR.js"),"../tools/recall.ts":()=>import("./recall-IABRCSHY.js"),"../tools/skillTool.ts":()=>import("./skillTool-PLHCAODG.js"),"../tools/tempTool.ts":()=>import("./tempTool-2RXAF56M.js"),"../tools/twitter.ts":()=>import("./twitter-OMDEG7T2.js"),"../tools/vectorize.ts":()=>import("./vectorize-UJXIDL2E.js")});var Fo=lt({});function Vt(o,t,n,e,s){var i;if(!((i=e.memoryConfig)!=null&&i.enabled)||!e.memoryConfig.toolCache||!n.cacheable||!t||typeof t.execute!="function")return t;let r=t.execute.bind(t);return t.execute=async(c,...d)=>{var l;if(!e.getContextIndex)return r(c,...d);let u=await _t(c),g=(await e.getContextIndex()).find(f=>{if(f.domain!=="tool")return!1;let a=$t(f.meta);return a.toolName===o&&a.paramsHash===u});if(g){let f=await((l=e.getContext)==null?void 0:l.call(e,g.ref));if((f==null?void 0:f.data)!=null&&$t(f.meta).truncated!==!0){s==null||s({type:"info:memory:cacheHit",content:{ref:f.ref,toolName:o}});try{return JSON.parse(f.data)}catch{return f.data}}}return r(c,...d)},t}async function Mo(o,t,n,e){var p,g;if(!((p=n.memoryConfig)!=null&&p.enabled)||!n.setContext||n.cycle==null)return;let s=o.toolCalls??[],r=o.toolResults??[];if(!s.length||!r.length)return;let i=new Map;for(let l of r)l!=null&&l.toolCallId&&i.set(l.toolCallId,l);let c=Array.isArray((g=t==null?void 0:t.data)==null?void 0:g.tools)?t.data.tools:[],d=new Map;for(let l of c)l&&typeof l.id=="string"&&d.set(l.id,l);let u=new Map;for(let l of Object.values(n.toolDefs??{}))l&&l.name&&u.set(l.name,l);for(let l of s){let f=l.toolCallId,a=l.toolName,m=i.get(f);if(!a||!m||a==="readSkillRef")continue;let y=l.args??l.input,w=m.result??m.output,h=!1,I="",R="tool",x="",O=u.get(a);O&&O.kind==="skill"&&(h=!0,I=`skill:${a}`,R="skill",x=`Skill instructions for ${a}`),I||(I=await ne(a,y),x=oe(y,w));let C=d.get(a)??c.find(k=>k.id===a),D=await _t(y),j=typeof w=="string"?w:JSON.stringify(w??null);await n.setContext({ref:I,domain:R,description:x,data:j,cycle:n.cycle,meta:JSON.stringify({toolName:a,paramsHash:D,cacheable:(C==null?void 0:C.cacheable)===!0})}),e==null||e({type:"info:memory:updated",content:{ref:I}})}}async function bo(o,t,n,e){var g;let s=Array.isArray((g=n==null?void 0:n.data)==null?void 0:g.tools)?n.data.tools:[];if(s.length===0)return{};let r={},i=l=>{var I,R;let f=typeof(l==null?void 0:l.description)=="string"?l.description:"",a=l==null?void 0:l.inputSchema,m;try{let x=(a==null?void 0:a.shape)??(typeof((I=a==null?void 0:a._def)==null?void 0:I.shape)=="function"?a._def.shape():(R=a==null?void 0:a._def)==null?void 0:R.shape);x&&typeof x=="object"&&(m=x)}catch{}let y=m?Object.keys(m):[],w=f?`description="${f.length>120?f.slice(0,120)+"\u2026":f}"`:"description=(none)",h=y.length?`inputSchema={${y.join(", ")}}`:"inputSchema=(none)";return`${w} ${h}`},c=(()=>{let l=[],f=[],a=[],m=[];for(let w=0;w<s.length;w++){let h=s[w];!h||typeof h!="object"||typeof h.id!="string"?m.push(w):h.kind==="builtin"?l.push(h.id):h.kind==="skill"?a.push(h.id):h.kind==="http"||h.kind==="mcp"||h.kind==="composio"?f.push(h.id):m.push(w)}let y=[];return l.length&&y.push(`builtin[${l.join(", ")}]`),f.length&&y.push(`custom[${f.join(", ")}]`),a.length&&y.push(`skill[${a.join(", ")}]`),m.length&&y.push(`invalid@[${m.join(", ")}]`),y.join(" ")||"(none)"})();console.log(`[tools] node ${n.id} requested (${s.length}): ${c}`);let d=!1,u=async()=>{if(d&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},d=!0,o.toolDefs;try{let l=await gt(o.env),f={};for(let a of l)a&&a.id&&(f[a.id]=a);o.toolDefs=f}catch(l){e==null||e({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(l)}`}),o.toolDefs=o.toolDefs||{}}return d=!0,o.toolDefs},p=[];for(let l=0;l<s.length;l++){let f=s[l];if(!f||typeof f!="object"||typeof f.id!="string"||f.kind!=="builtin"&&f.kind!=="http"&&f.kind!=="mcp"&&f.kind!=="composio"&&f.kind!=="skill"){e==null||e({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${l}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let a=f;if(a.kind!=="builtin"){let y=(await u())[a.id];if(!y){console.error(`[tools] \u2717 custom '${a.id}': not found for tenant`),e==null||e({type:"error:llmNodeRunner",content:`custom tool '${a.id}' not found for this tenant`});continue}if(a.kind==="composio"){try{let h=await me(y,o,t,e),I=Object.keys(h);for(let[R,x]of Object.entries(h))r[R]=Vt(R,x,a,o,e);console.log(`[tools] \u2713 composio '${a.id}' \u2192 ${I.length} tool(s)`)}catch(h){console.error(`[tools] \u2717 composio '${a.id}': ${String(h)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading composio tool '${a.id}': ${String(h)}`})}continue}if(a.kind==="skill"){if(y.kind!=="skill"){console.error(`[tools] \u2717 skill '${a.id}': row is of kind '${y.kind}', not 'skill'`),e==null||e({type:"error:llmNodeRunner",content:`tool '${a.id}' is not a skill`});continue}let h=y.name;if(r[h]){e==null||e({type:"warn:llmNodeRunner",content:`tool name collision on '${h}' \u2014 builtin/other already registered, skipping skill '${a.id}'`});continue}try{r[h]=ge(y,o,t,e),p.push(y);let I=typeof y.execution=="string"?JSON.parse(y.execution):y.execution||{},R=Array.isArray(I.references)?I.references.map(x=>x==null?void 0:x.name):[];console.log(`[tools] \u2713 skill '${a.id}' \u2192 '${h}' (refs: ${R.join(", ")||"none"})`),e==null||e({type:"info:skill:registered",content:{skill:h,refCount:R.length,refs:R}})}catch(I){console.error(`[tools] \u2717 skill '${a.id}': ${String(I)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading skill tool '${a.id}': ${String(I)}`})}continue}let w=y.name;if(r[w]){e==null||e({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin already registered, skipping custom tool '${a.id}'`});continue}try{let h=yt(y,o,t,e);r[w]=Vt(w,h,a,o,e),console.log(`[tools] \u2713 custom '${a.id}' \u2192 '${w}'`),console.log(`[tools] ${i(r[w])}`)}catch(h){console.error(`[tools] \u2717 custom '${a.id}': ${String(h)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading custom tool '${a.id}': ${String(h)}`})}continue}if(!fe[a.id]){console.error(`[tools] \u2717 builtin '${a.id}': not in registry`),e==null||e({type:"error:llmNodeRunner",content:`Tool '${a.id}' not found in registry`});continue}try{let m;try{m=await ko(`../tools/${a.id}.ts`)}catch{m=await Fo(`../tools/${a.id}.js`)}let y;if(m[a.id])y=m[a.id];else if(m.default)y=m.default;else if(m.create)y=m.create;else{let C=Object.values(m);C.length>0&&(y=C[0])}if(!y){e==null||e({type:"error:llmNodeRunner",content:`No factory export found for tool '${a.id}'`});continue}let w,h,I={};if(a.params&&typeof a.params=="object"){if(typeof a.params.description=="string"?w=a.params.description:a.params.description!==void 0&&(e==null||e({type:"error:llmNodeRunner",content:`Invalid description for tool '${a.id}' \u2014 must be a string`})),a.params.inputSchema!==void 0){let C=a.params.inputSchema;typeof C=="object"&&(typeof C.safeParse=="function"||C._def)?h=C:typeof C=="object"&&C!==null&&C.type==="object"&&C.properties?(h=pe(C),h||e==null||e({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${a.id}' \u2014 must be a Zod schema or JSON Schema object`})):e==null||e({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${a.id}' \u2014 must be a Zod schema or JSON Schema object`})}a.params.defaults!==void 0?typeof a.params.defaults=="object"&&a.params.defaults!==null&&!Array.isArray(a.params.defaults)?I=a.params.defaults:(e==null||e({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${a.id}' \u2014 must be an object`}),I={}):a.params.source!==void 0||a.params.target!==void 0?(e==null||e({type:"error:llmNodeRunner",content:`Invalid params for tool '${a.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),I={}):I={}}let R=y(o,t,I,e);w&&R&&typeof R=="object"&&(R.description=w),h&&R&&typeof R=="object"&&(R.inputSchema=h),r[a.id]=Vt(a.id,R,a,o,e);let x=[];w&&x.push("description"),h&&x.push("inputSchema"),Object.keys(I).length&&x.push(`defaults(${Object.keys(I).join(",")})`);let O=x.length?` [overrides: ${x.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${a.id}'${O}`),console.log(`[tools] ${i(R)}`)}catch(m){console.error(`[tools] \u2717 builtin '${a.id}': ${String(m)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading tool '${a.id}': ${String(m)}`});continue}}if(p.length>0)if(r.readSkillRef)e==null||e({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{r.readSkillRef=ye(o,p,t,e),console.log(`[tools] \u2713 registered readSkillRef tool for ${p.length} skill(s)`),e==null||e({type:"info:skill:readSkillRefRegistered",content:{skills:p.map(l=>l.name)}})}catch(l){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(l)}`)}return r}async function qt(o,t,n,e,s,r,i){var D,j,k,_,L,N;`${t.id}`,e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let c=!1;try{let T=(D=n.flowData)==null?void 0:D.state;if(T&&T.edges&&T.nodes){let F=T.edges.filter(U=>U.source===t.id);if(F.length>0){let U=T.nodes.find(M=>M.id===F[0].target);U&&U.type==="answerNode"&&(c=!0)}}}catch(T){console.error("Error determining next node for streaming:",T)}let d=G(t.data.template,t,n,e,{sessionEnv:o});(!d||!d.trim())&&(d="Answer straight forward to the user, dont offer any other option to continue");let u=d,p="";if((j=o.memoryConfig)!=null&&j.enabled){let T=await((k=o.getContextIndex)==null?void 0:k.call(o))??[];p=re(T),d+=p}let g=G(t.data.user_template||"",t,n,e,{sessionEnv:o}),l=T=>T&&Object.fromEntries(Object.keys(T).map(F=>[F,"[redacted]"])),f=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:l(o.secrets),userAuth:l(o.userAuth)}:o,a=G(t.data.template,t,n,void 0,{sessionEnv:f})||u;a+=p;let m=G(t.data.user_template||"",t,n,void 0,{sessionEnv:f});e==null||e({type:`info:llmNodeRunner:${t.id}`,content:a}),e==null||e({type:`info:llmNodeRunner:${t.id}`,content:m});let y=(_=t==null?void 0:t.data)==null?void 0:_.window_size,w=Number(y);(!Number.isInteger(w)||w<=0)&&(w=5);let h=be(t,n),I=Me(t,n);e==null||e({type:"info:llmNodeRunner:attachments",content:{nodeId:t.id,refs:Array.isArray((L=t.data)==null?void 0:L.attachments)?t.data.attachments:[],images:h.length,documents:I?1:0}});let x=(await((N=o.getMessages)==null?void 0:N.call(o))??[]).slice(-w),O=x.filter(T=>T&&typeof T.role=="string"&&typeof T.content=="string");O.length!==x.length&&console.warn(`Filtered ${x.length-O.length} invalid messages from history`);let C=jo(O,g,h,I);await Eo(d,C,o.conn,e,t,c,s,n,r,o,i)}async function Eo(o,t,n,e,s,r,i,c,d,u,p){var l;let g=Date.now();if(!((l=u.env)!=null&&l.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(f,a)=>{var L,N,T,F,U,M,X;let m,y={},w,h="none",I=!1,R,x=!1,O=!1,C=0,D=0,j=(L=s==null?void 0:s.data)==null?void 0:L.sendReasoning,k=j!==!1;try{let b=(N=s==null?void 0:s.data)==null?void 0:N.model,Q=Array.isArray(b)?b[0]:b||"gpt_5_nano",A=Qt(s==null?void 0:s.data),P=await ut(Q,u,A);if(!P)throw new Error(`Model '${Q}' not found in registry`);m=P.modelHandle,y=P.effectiveParams||{},h=P.reasoning.kind;let $=te(P.reasoning,(T=s==null?void 0:s.data)==null?void 0:T.reasoningEffort);I=k&&vt(P.reasoning);let S=typeof((F=s==null?void 0:s.data)==null?void 0:F.reasoningMaxTokens)=="number"?s.data.reasoningMaxTokens:void 0;w=ee(P.provider,{effort:$,exposeReasoning:I,maxTokens:S}),$&&(e==null||e({type:"info:llmNodeRunner:reasoningEffort",content:$})),console.log(`[reasoning] ${JSON.stringify({model:Q,provider:P.provider,capability:P.reasoning,requestedEffort:((U=s==null?void 0:s.data)==null?void 0:U.reasoningEffort)??null,resolvedEffort:$??null,sendReasoning:k,exposeReasoning:I,providerOptions:w??null},null,2)}`);for(let q of P.paramAdjustments??[])e==null||e({type:"warn:llmNodeRunner",content:q});e==null||e({type:"info:llmNodeRunner:model",content:Q}),e==null||e({type:"info:llmNodeRunner:generationParams",content:{...(M=s==null?void 0:s.data)!=null&&M.generationPreset?{preset:s.data.generationPreset}:{},...y,...h!=="none"?{reasoning:h,configuredSendReasoning:j,sendReasoning:k,exposeReasoning:I,...$?{effort:$}:{}}:{}}})}catch(b){throw e==null||e({type:"error:llmNodeRunner",content:`Model error: ${String(b)}`}),b}let _=await bo(u,c,s,e);if((X=u.memoryConfig)!=null&&X.enabled){let{recall:b}=await import("./recall-IABRCSHY.js");_.recall=b(u,c,void 0,e)}console.log(`[tools] node ${s.id} loaded ${Object.keys(_).length}: ${Object.keys(_).join(", ")||"(none)"}`),e==null||e({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:s.id,tools:Object.keys(_)}});try{let b=Do({model:m,system:o,messages:t,stopWhen:(()=>{var q;let P=!!_.readSkillRef?10:5,$=Number(((q=s.data)==null?void 0:q.max_steps)??P),S=Number.isFinite($)?Math.max(1,Math.min(30,$)):P;return Po(S)})(),...Zt(y),...w?{providerOptions:w}:{},tools:_,onFinish:async A=>{var Jt,zt;let P=A.text||"",$=A.reasoningText??((Jt=A.reasoning)==null?void 0:Jt.text)??"";if(console.log(`[reasoning] done: deltas=${C} chars=${D} result.reasoningText=${$.length} finishReason=${A.finishReason??"n/a"} reasoningTokens=${((zt=A.usage)==null?void 0:zt.reasoningTokens)??"n/a"}`),k&&I&&!x&&$&&n){x=!0;try{H(n,E.SERVER_REASONING_STREAM,$)}catch(ro){console.warn("Failed to send finished reasoning over connection",ro)}}let S={id:Uo(),role:"assistant",type:"text",content:P,ts:Date.now()};r&&(u.setMessages?await u.setMessages(S):e==null||e({type:"error:llmNodeRunner",content:"setMessages callback missing"})),n&&k&&x&&!O&&(O=!0,H(n,E.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),r&&n&&H(n,E.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),i==null||i((s==null?void 0:s.id)||"llm_result",P),e==null||e({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(A)});let q=Date.now()-g,so=R?R-g:void 0;p==null||p({type:"llm_telemetry",payload:{nodeId:s.id,totalLatency:q,timeToFirstToken:so,model:A.response.modelId,usage:A.usage}}),p==null||p({type:"llm_result",payload:{result:A}})},onStepFinish:async A=>{let P=($,S=200)=>{let q=typeof $=="string"?$:JSON.stringify($);return q?q.length>S?`${q.slice(0,S)}\u2026(+${q.length-S})`:q:""};if(A.toolCalls&&A.toolCalls.length>0){for(let $ of A.toolCalls)console.log(`[tools] \u2192 ${$.toolName}(${P($.args??$.input)})`);e==null||e({type:`info:llmNodeRunner:toolCalls:${s.id}`,content:JSON.stringify(A.toolCalls)})}if(A.toolResults&&A.toolResults.length>0){for(let $ of A.toolResults)console.log(`[tools] \u2190 ${$.toolName} \u2192 ${P($.result??$.output)}`);e==null||e({type:`info:llmNodeRunner:toolResults:${s.id}`,content:JSON.stringify(A.toolResults)})}await Mo(A,s,u,e)},experimental_onToolCallStart:A=>{var P;e==null||e({type:"tool:execution",content:{nodeId:s.id,toolName:(P=A==null?void 0:A.toolCall)==null?void 0:P.toolName,status:"start"}})},experimental_onToolCallFinish:A=>{var P,$;e==null||e({type:"tool:execution",content:{nodeId:s.id,toolName:(P=A==null?void 0:A.toolCall)==null?void 0:P.toolName,status:(($=A==null?void 0:A.toolOutput)==null?void 0:$.type)==="tool-error"?"error":"success"}})},onError:A=>{e==null||e({type:"error:llmNodeRunner",content:"Execution error"}),a(A)},onChunk:A=>{if(A.chunk.type==="reasoning-delta"){let $=A.chunk.text??A.chunk.delta??"";if($&&(x=!0,C+=1,D+=$.length,C===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),k&&n&&$)try{H(n,E.SERVER_REASONING_STREAM,$)}catch(S){console.warn("Failed to send reasoning chunk over connection",S)}return}if(A.chunk.type==="text-delta"){if(R||(R=Date.now()),n&&k&&x&&!O){O=!0;try{H(n,E.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch($){console.warn("Failed to send reasoning complete over connection",$)}}return}p==null||p({type:A.chunk.type,payload:{nodeId:s.id,chunk:A.chunk}});let P=`llm_chunk:${A.chunk.type}`;e==null||e({type:P,content:{...A}})}}),Q=async()=>{let A="";for await(let P of b.fullStream)if(P.type==="text-delta"){if(A+=P.text,r&&n)try{H(n,E.SERVER_TEXT_STREAM,P.text)}catch($){console.warn("Failed to send chunk over connection",$)}}else if(P.type==="finish-step"&&P.finishReason==="tool-calls"){if(r&&n&&A.trim())try{H(n,E.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch($){console.warn("Failed to flush text segment over connection",$)}A=""}};await Promise.all([b,Q()]),f(),e==null||e({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"success"}})}catch(b){e==null||e({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"error",error:String(b)}}),a(b)}})}function jo(o,t,n,e){let s=!!(n&&n.length>0),r=!!e,i=s||r,d=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,u=p=>{let g=[],l="";if(r&&(l+=`[Attached files]
|
|
14
|
+
`:"")+l.value)}return i}function Mo(o,t){var s,r,i,a,c;let n=((s=o.data)==null?void 0:s.attachments)??[];if(!Array.isArray(n))throw new V("INVALID_EXPRESSION",`Node ${o.id} attachments must be an array`);let e=tt(((i=(r=t.flowData)==null?void 0:r.state)==null?void 0:i.nodes)??[],((c=(a=t.flowData)==null?void 0:a.state)==null?void 0:c.edges)??[],o.id);return n.map(u=>{if(typeof u!="string")throw new V("INVALID_EXPRESSION",`Node ${o.id} has an invalid attachment reference`);let p=e.find(g=>g.ref===u);if(!p)throw new V("OUT_OF_SCOPE",`Attachment "${u}" is not in this node's connection scope`);if(p.type!=="image"&&p.type!=="file")throw new V("UNKNOWN_OUTPUT",`Attachment "${u}" is not a binary output`);return p.type==="image"?u:null}).filter(u=>u!==null)}function $e(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 c of Mo(o,t)){let u=q(c,e);if(u.missing)throw new V(u.missing==="ancestor_not_executed"?"ANCESTOR_NOT_EXECUTED":"PATH_NOT_FOUND",`Attachment "${c}" did not produce a value`);if(!Array.isArray(u.value))throw new V("PATH_NOT_FOUND",`Attachment "${c}" must resolve to an image array`);n.push(...u.value)}return n}var Po=ct({"../tools/composioDirectTool.ts":()=>import("./composioDirectTool-H3GSCIPY.js"),"../tools/composioTool.ts":()=>import("./composioTool-5LFWUQ7F.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-5D2PQJKV.js"),"../tools/skillTool.ts":()=>import("./skillTool-AIOXPTAJ.js"),"../tools/tempTool.ts":()=>import("./tempTool-2RXAF56M.js"),"../tools/twitter.ts":()=>import("./twitter-OMDEG7T2.js"),"../tools/vectorize.ts":()=>import("./vectorize-UJXIDL2E.js")});var bo=ct({});async function Uo(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=d=>{var R,x;let m=typeof(d==null?void 0:d.description)=="string"?d.description:"",l=d==null?void 0:d.inputSchema,f;try{let I=(l==null?void 0:l.shape)??(typeof((R=l==null?void 0:l._def)==null?void 0:R.shape)=="function"?l._def.shape():(x=l==null?void 0:l._def)==null?void 0:x.shape);I&&typeof I=="object"&&(f=I)}catch{}let y=f?Object.keys(f):[],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}`},a=(()=>{let d=[],m=[],l=[],f=[];for(let h=0;h<s.length;h++){let w=s[h];!w||typeof w!="object"||typeof w.id!="string"?f.push(h):w.kind==="builtin"?d.push(w.id):w.kind==="skill"?l.push(w.id):w.kind==="http"||w.kind==="mcp"||w.kind==="composio"?m.push(w.id):f.push(h)}let y=[];return d.length&&y.push(`builtin[${d.join(", ")}]`),m.length&&y.push(`custom[${m.join(", ")}]`),l.length&&y.push(`skill[${l.join(", ")}]`),f.length&&y.push(`invalid@[${f.join(", ")}]`),y.join(" ")||"(none)"})();console.log(`[tools] node ${n.id} requested (${s.length}): ${a}`);let c=!1,u=async()=>{if(c&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},c=!0,o.toolDefs;try{let d=await yt(o.env),m={};for(let l of d)l&&l.id&&(m[l.id]=l);o.toolDefs=m}catch(d){e==null||e({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(d)}`}),o.toolDefs=o.toolDefs||{}}return c=!0,o.toolDefs},p=[];for(let d=0;d<s.length;d++){let m=s[d];if(!m||typeof m!="object"||typeof m.id!="string"||m.kind!=="builtin"&&m.kind!=="http"&&m.kind!=="mcp"&&m.kind!=="composio"&&m.kind!=="skill"){e==null||e({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${d}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let l=m;if(l.kind!=="builtin"){let y=(await u())[l.id];if(!y){console.error(`[tools] \u2717 custom '${l.id}': not found for tenant`),e==null||e({type:"error:llmNodeRunner",content:`custom tool '${l.id}' not found for this tenant`});continue}if(l.kind==="composio"){try{let w=await ge(y,o,t,e),R=Object.keys(w);for(let[x,I]of Object.entries(w))r[x]=I;console.log(`[tools] \u2713 composio '${l.id}' \u2192 ${R.length} tool(s)`)}catch(w){console.error(`[tools] \u2717 composio '${l.id}': ${String(w)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading composio tool '${l.id}': ${String(w)}`})}continue}if(l.kind==="skill"){if(y.kind!=="skill"){console.error(`[tools] \u2717 skill '${l.id}': row is of kind '${y.kind}', not 'skill'`),e==null||e({type:"error:llmNodeRunner",content:`tool '${l.id}' is not a skill`});continue}let w=y.name;if(r[w]){e==null||e({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin/other already registered, skipping skill '${l.id}'`});continue}try{r[w]=ye(y,o,t,e),p.push(y);let R=typeof y.execution=="string"?JSON.parse(y.execution):y.execution||{},x=Array.isArray(R.references)?R.references.map(I=>I==null?void 0:I.name):[];console.log(`[tools] \u2713 skill '${l.id}' \u2192 '${w}' (refs: ${x.join(", ")||"none"})`),e==null||e({type:"info:skill:registered",content:{skill:w,refCount:x.length,refs:x}})}catch(R){console.error(`[tools] \u2717 skill '${l.id}': ${String(R)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading skill tool '${l.id}': ${String(R)}`})}continue}let h=y.name;if(r[h]){e==null||e({type:"warn:llmNodeRunner",content:`tool name collision on '${h}' \u2014 builtin already registered, skipping custom tool '${l.id}'`});continue}try{let w=wt(y,o,t,e);r[h]=w,console.log(`[tools] \u2713 custom '${l.id}' \u2192 '${h}'`),console.log(`[tools] ${i(r[h])}`)}catch(w){console.error(`[tools] \u2717 custom '${l.id}': ${String(w)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading custom tool '${l.id}': ${String(w)}`})}continue}if(!me[l.id]){console.error(`[tools] \u2717 builtin '${l.id}': not in registry`),e==null||e({type:"error:llmNodeRunner",content:`Tool '${l.id}' not found in registry`});continue}try{let f;try{f=await Po(`../tools/${l.id}.ts`)}catch{f=await bo(`../tools/${l.id}.js`)}let y;if(f[l.id])y=f[l.id];else if(f.default)y=f.default;else if(f.create)y=f.create;else{let O=Object.values(f);O.length>0&&(y=O[0])}if(!y){e==null||e({type:"error:llmNodeRunner",content:`No factory export found for tool '${l.id}'`});continue}let h,w,R={};if(l.params&&typeof l.params=="object"){if(typeof l.params.description=="string"?h=l.params.description:l.params.description!==void 0&&(e==null||e({type:"error:llmNodeRunner",content:`Invalid description for tool '${l.id}' \u2014 must be a string`})),l.params.inputSchema!==void 0){let O=l.params.inputSchema;typeof O=="object"&&(typeof O.safeParse=="function"||O._def)?w=O:typeof O=="object"&&O!==null&&O.type==="object"&&O.properties?(w=ce(O),w||e==null||e({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${l.id}' \u2014 must be a Zod schema or JSON Schema object`})):e==null||e({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${l.id}' \u2014 must be a Zod schema or JSON Schema object`})}l.params.defaults!==void 0?typeof l.params.defaults=="object"&&l.params.defaults!==null&&!Array.isArray(l.params.defaults)?R=l.params.defaults:(e==null||e({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${l.id}' \u2014 must be an object`}),R={}):l.params.source!==void 0||l.params.target!==void 0?(e==null||e({type:"error:llmNodeRunner",content:`Invalid params for tool '${l.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),R={}):R={}}let x=y(o,t,R,e);h&&x&&typeof x=="object"&&(x.description=h),w&&x&&typeof x=="object"&&(x.inputSchema=w),r[l.id]=x;let I=[];h&&I.push("description"),w&&I.push("inputSchema"),Object.keys(R).length&&I.push(`defaults(${Object.keys(R).join(",")})`);let $=I.length?` [overrides: ${I.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${l.id}'${$}`),console.log(`[tools] ${i(x)}`)}catch(f){console.error(`[tools] \u2717 builtin '${l.id}': ${String(f)}`),e==null||e({type:"error:llmNodeRunner",content:`Error loading tool '${l.id}': ${String(f)}`});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=we(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(d=>d.name)}})}catch(d){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(d)}`)}return r}async function Xt(o,t,n,e,s,r,i){var O,F,H,M;`${t.id}`,e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"start"}});let a=!1;try{let N=(O=n.flowData)==null?void 0:O.state;if(N&&N.edges&&N.nodes){let U=N.edges.filter(D=>D.source===t.id);if(U.length>0){let D=N.nodes.find(C=>C.id===U[0].target);D&&D.type==="answerNode"&&(a=!0)}}}catch(N){console.error("Error determining next node for streaming:",N)}let c=W(t.data.template,t,n,e,{sessionEnv:o});(!c||!c.trim())&&(c="Answer straight forward to the user, dont offer any other option to continue");let u=c,p=W(t.data.user_template||"",t,n,e,{sessionEnv:o}),g=N=>N&&Object.fromEntries(Object.keys(N).map(U=>[U,"[redacted]"])),d=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:g(o.secrets),userAuth:g(o.userAuth)}:o,m=W(t.data.template,t,n,void 0,{sessionEnv:d})||u,l=W(t.data.user_template||"",t,n,void 0,{sessionEnv:d});e==null||e({type:`info:llmNodeRunner:${t.id}`,content:m}),e==null||e({type:`info:llmNodeRunner:${t.id}`,content:l});let f=(F=t==null?void 0:t.data)==null?void 0:F.window_size,y=Number(f);(!Number.isInteger(y)||y<=0)&&(y=5);let h=$e(t,n),w=_e(t,n);e==null||e({type:"info:llmNodeRunner:attachments",content:{nodeId:t.id,refs:Array.isArray((H=t.data)==null?void 0:H.attachments)?t.data.attachments:[],images:h.length,documents:w?1:0}});let x=(await((M=o.getMessages)==null?void 0:M.call(o))??[]).slice(-y),I=x.filter(N=>N&&typeof N.role=="string"&&typeof N.content=="string");I.length!==x.length&&console.warn(`Filtered ${x.length-I.length} invalid messages from history`);let $=jo(I,p,h,w);await Eo(c,$,o.conn,e,t,a,s,n,r,o,i)}async function Eo(o,t,n,e,s,r,i,a,c,u,p){var d;let g=Date.now();if(!((d=u.env)!=null&&d.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(m,l)=>{var U,D,C,L,T,k;let f,y={},h,w="none",R=!1,x,I=!1,$=!1,O=0,F=0,H=(U=s==null?void 0:s.data)==null?void 0:U.sendReasoning,M=H!==!1;try{let b=(D=s==null?void 0:s.data)==null?void 0:D.model,E=Array.isArray(b)?b[0]:b||"gpt_5_nano",A=de(s==null?void 0:s.data),P=await et(E,u,A);if(!P)throw new Error(`Model '${E}' not found in registry`);f=P.modelHandle,y=P.effectiveParams||{},w=P.reasoning.kind;let _=Rt(P.reasoning,(C=s==null?void 0:s.data)==null?void 0:C.reasoningEffort);R=M&&fe(P.reasoning);let X=typeof((L=s==null?void 0:s.data)==null?void 0:L.reasoningMaxTokens)=="number"?s.data.reasoningMaxTokens:void 0;h=xt(P.provider,{effort:_,exposeReasoning:R,maxTokens:X}),_&&(e==null||e({type:"info:llmNodeRunner:reasoningEffort",content:_})),console.log(`[reasoning] ${JSON.stringify({model:E,provider:P.provider,capability:P.reasoning,requestedEffort:((T=s==null?void 0:s.data)==null?void 0:T.reasoningEffort)??null,resolvedEffort:_??null,sendReasoning:M,exposeReasoning:R,providerOptions:h??null},null,2)}`);for(let K of P.paramAdjustments??[])e==null||e({type:"warn:llmNodeRunner",content:K});e==null||e({type:"info:llmNodeRunner:model",content:E}),e==null||e({type:"info:llmNodeRunner:generationParams",content:{...(k=s==null?void 0:s.data)!=null&&k.generationPreset?{preset:s.data.generationPreset}:{},...y,...w!=="none"?{reasoning:w,configuredSendReasoning:H,sendReasoning:M,exposeReasoning:R,..._?{effort:_}:{}}:{}}})}catch(b){throw e==null||e({type:"error:llmNodeRunner",content:`Model error: ${String(b)}`}),b}let N=await Uo(u,a,s,e);console.log(`[tools] node ${s.id} loaded ${Object.keys(N).length}: ${Object.keys(N).join(", ")||"(none)"}`),e==null||e({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:s.id,tools:Object.keys(N)}});try{let b=Do({model:f,system:o,messages:t,stopWhen:(()=>{var K;let P=!!N.readSkillRef?10:5,_=Number(((K=s.data)==null?void 0:K.max_steps)??P),X=Number.isFinite(_)?Math.max(1,Math.min(30,_)):P;return Fo(X)})(),...ht(y),...h?{providerOptions:h}:{},tools:N,onFinish:async A=>{var Wt,Gt;let P=A.text||"",_=A.reasoningText??((Wt=A.reasoning)==null?void 0:Wt.text)??"";if(console.log(`[reasoning] done: deltas=${O} chars=${F} result.reasoningText=${_.length} finishReason=${A.finishReason??"n/a"} reasoningTokens=${((Gt=A.usage)==null?void 0:Gt.reasoningTokens)??"n/a"}`),M&&R&&!I&&_&&n){I=!0;try{S(n,j.SERVER_REASONING_STREAM,_)}catch(ve){console.warn("Failed to send finished reasoning over connection",ve)}}let X={id:Co(),role:"assistant",type:"text",content:P,ts:Date.now()};r&&(u.setMessages?await u.setMessages(X):e==null||e({type:"error:llmNodeRunner",content:"setMessages callback missing"})),n&&M&&I&&!$&&($=!0,S(n,j.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),r&&n&&S(n,j.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),i==null||i((s==null?void 0:s.id)||"llm_result",P),e==null||e({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(A)});let K=Date.now()-g,Qe=x?x-g:void 0;p==null||p({type:"llm_telemetry",payload:{nodeId:s.id,totalLatency:K,timeToFirstToken:Qe,model:A.response.modelId,usage:A.usage}}),p==null||p({type:"llm_result",payload:{result:A}})},onStepFinish:async A=>{let P=(_,X=200)=>{let K=typeof _=="string"?_:JSON.stringify(_);return K?K.length>X?`${K.slice(0,X)}\u2026(+${K.length-X})`:K:""};if(A.toolCalls&&A.toolCalls.length>0){for(let _ of A.toolCalls)console.log(`[tools] \u2192 ${_.toolName}(${P(_.args??_.input)})`);e==null||e({type:`info:llmNodeRunner:toolCalls:${s.id}`,content:JSON.stringify(A.toolCalls)})}if(A.toolResults&&A.toolResults.length>0){for(let _ of A.toolResults)console.log(`[tools] \u2190 ${_.toolName} \u2192 ${P(_.result??_.output)}`);e==null||e({type:`info:llmNodeRunner:toolResults:${s.id}`,content:JSON.stringify(A.toolResults)})}},experimental_onToolCallStart:A=>{var P;e==null||e({type:"tool:execution",content:{nodeId:s.id,toolName:(P=A==null?void 0:A.toolCall)==null?void 0:P.toolName,status:"start"}})},experimental_onToolCallFinish:A=>{var P,_;e==null||e({type:"tool:execution",content:{nodeId:s.id,toolName:(P=A==null?void 0:A.toolCall)==null?void 0:P.toolName,status:((_=A==null?void 0:A.toolOutput)==null?void 0:_.type)==="tool-error"?"error":"success"}})},onError:A=>{e==null||e({type:"error:llmNodeRunner",content:"Execution error"}),l(A)},onChunk:A=>{if(A.chunk.type==="reasoning-delta"){let _=A.chunk.text??A.chunk.delta??"";if(_&&(I=!0,O+=1,F+=_.length,O===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),M&&n&&_)try{S(n,j.SERVER_REASONING_STREAM,_)}catch(X){console.warn("Failed to send reasoning chunk over connection",X)}return}if(A.chunk.type==="text-delta"){if(x||(x=Date.now()),n&&M&&I&&!$){$=!0;try{S(n,j.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(_){console.warn("Failed to send reasoning complete over connection",_)}}return}p==null||p({type:A.chunk.type,payload:{nodeId:s.id,chunk:A.chunk}});let P=`llm_chunk:${A.chunk.type}`;e==null||e({type:P,content:{...A}})}}),E=async()=>{let A="";for await(let P of b.fullStream)if(P.type==="text-delta"){if(A+=P.text,r&&n)try{S(n,j.SERVER_TEXT_STREAM,P.text)}catch(_){console.warn("Failed to send chunk over connection",_)}}else if(P.type==="finish-step"&&P.finishReason==="tool-calls"){if(r&&n&&A.trim())try{S(n,j.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(_){console.warn("Failed to flush text segment over connection",_)}A=""}};await Promise.all([b,E()]),m(),e==null||e({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"success"}})}catch(b){e==null||e({type:"node:execution",content:{nodeId:s.id,nodeType:s.type,status:"error",error:String(b)}}),l(b)}})}function jo(o,t,n,e){let s=!!(n&&n.length>0),r=!!e,i=s||r,c=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,u=p=>{let g=[],d="";if(r&&(d+=`[Attached files]
|
|
31
15
|
${e}
|
|
32
16
|
[End of attached files]
|
|
33
17
|
|
|
34
|
-
`),p&&(
|
|
18
|
+
`),p&&(d+=p),d&&g.push({type:"text",text:d}),s)for(let m of n)g.push({type:"image",image:m.data,mimeType:m.mimeType});return g};return t&&c&&c.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&&c?[...o.slice(0,-1).map(g=>({role:g.role,content:g.content})),{role:"user",content:u(c.content)}]:o.map(p=>({role:p.role,content:p.content}))}async function qt(o,t,n,e,s,r,i){var p,g,d,m,l,f,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="",c=!1,u=Date.now();try{e==null||e({type:"info:memoNodeRunner",content:"Starting memo node execution"});let h=String(((p=t.data)==null?void 0:p.query_key)||"user_input"),w=q(h,{context:n.context??{},results:n.results??{},nodes:((d=(g=n.flowData)==null?void 0:g.state)==null?void 0:d.nodes)??[],edges:((l=(m=n.flowData)==null?void 0:m.state)==null?void 0:l.edges)??[],currentNodeId:t.id});if(w.missing)throw new Error(`Memo query "${h}" 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 R=String(w.value??"");e==null||e({type:"info:memoNodeRunner",content:`Query text: ${R}`}),e==null||e({type:"info:memoNodeRunner",content:"Generating embedding for query"});let x=await Yt(o,R,!0);e==null||e({type:"info:memoNodeRunner",content:`Embedding generated successfully, length: ${x.data[0].length}`});let I=Array.isArray(t.data.rag_id)?t.data.rag_id:[t.data.rag_id],$=[];for(let M of I){e==null||e({type:"info:memoNodeRunner",content:`Executing RAG query with namespace: ${M}`});let N=await o.env[`VDB_${(f=n.flowData)==null?void 0:f.tenant}_1024`].query(x.data[0],{namespace:M,topK:t.data.topk,returnMetadata:"all"});e==null||e({type:"info:memoNodeRunner",content:`RAG query completed for namespace ${M}, matches: ${((y=N.matches)==null?void 0:y.length)||0}`}),Array.isArray(N.matches)&&$.push(...N.matches)}let O=Date.now()-u;a=$.map(M=>{var N;return(N=M.metadata)==null?void 0:N.value}).filter(M=>typeof M=="string").join(`
|
|
35
19
|
|
|
36
|
-
`),i==null||i({type:"memo_search",payload:{nodeId:t.id,searchLatencyMs:
|
|
37
|
-
${
|
|
20
|
+
`),i==null||i({type:"memo_search",payload:{nodeId:t.id,searchLatencyMs:O,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"}),c=!0}catch(h){throw console.error("Error processing MemoNode:",h),e==null||e({type:"error:memoNodeRunner",content:`Memo node execution failed: ${h}`}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"error",error:String(h)}}),h}finally{c&&(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 Jt(o,t,n,e,s,r,i){var p,g,d,m,l,f,y,h;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,c=((d=t.data)==null?void 0:d.allow_documents)!==!1;!a&&(n!=null&&n.context)&&(n.context.user_images=[],r==null||r({...n})),!c&&(n!=null&&n.context)&&(n.context.files="",r==null||r({...n}));let u={};for(let w of v(t.data))u[w.name]=(m=n==null?void 0:n.context)==null?void 0:m[w.name];s==null||s(t.id,{...u,user_input:(l=n==null?void 0:n.context)==null?void 0:l.user_input,images:a?(f=n==null?void 0:n.context)==null?void 0:f.user_images:[],files:c?(y=n==null?void 0:n.context)==null?void 0:y.files:"",memory:((h=n==null?void 0:n.context)==null?void 0:h.memory)??""}),e==null||e({type:"node:execution",content:{nodeId:t.id,nodeType:t.type,status:"success"}})}function Pe(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 _t}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=So(p,e.flowData,e)}async function i(u){var l;let p=c[u.type];if(!p){(l=n==null?void 0:n.onError)==null||l.call(n,`Unknown node type: ${u.type}`);return}let g=f=>{var y;return(y=n==null?void 0:n.onServerEvent)==null?void 0:y.call(n,{...f,ts:Date.now()})},d=f=>{var y,h;if((y=n==null?void 0:n.onTelemetry)==null||y.call(n,f),f.type==="llm_telemetry"||f.type==="class_telemetry"||f.type==="memory_update"){let w=(h=f.payload)==null?void 0:h.usage;w&&(e.tokenUsage=e.tokenUsage||{promptTokens:0,completionTokens:0,totalTokens:0},e.tokenUsage.promptTokens+=w.promptTokens||0,e.tokenUsage.completionTokens+=w.completionTokens||0,e.tokenUsage.totalTokens+=w.totalTokens||0)}};return await p(o,u,e,g,(f,y)=>{e.results[f]=y},n==null?void 0:n.onChangeState,d)}let a=async u=>{var m,l,f,y,h,w,R;let p=Date.now(),g="completed",d;try{await s();let x=typeof u=="string"?lt(u):u,I=(x==null?void 0:x.text)||"",$=(x==null?void 0:x.images)||[],O=(x==null?void 0:x.documents)||[],F=await Ne(O,o.env),H=F.length>0?F.map(U=>`--- file: ${U.name} ---
|
|
21
|
+
${U.text}`).join(`
|
|
38
22
|
|
|
39
|
-
`):"";e.context={user_input:x,user_images:O,files:j},e.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},(f=n==null?void 0:n.onServerEvent)==null||f.call(n,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:k,error:_}=Lo(e.flowData);if(!k)g="failed",l=_||"Flow Format Error",(a=n==null?void 0:n.onError)==null||a.call(n,l);else{let L=tt(k.data),{values:N,errors:T}=Wt(L,R==null?void 0:R.inputs);if(T.length>0)return g="failed",l=`Invalid flow inputs: ${T.join("; ")}`,(m=n==null?void 0:n.onError)==null||m.call(n,l),{status:g,error:l};e.context={...e.context,inputs:N,...N},e.context.user_input||(e.context.user_input=x),await r(k),(y=n==null?void 0:n.onServerEvent)==null||y.call(n,{type:"agent:telemetry",content:{durationMs:Date.now()-p,tokenUsage:e.tokenUsage},timestamp:Date.now()})}}catch(R){R instanceof Ct?(g="stopped",l=R.message,(w=n==null?void 0:n.onServerEvent)==null||w.call(n,{type:"agent:stopped",content:l,timestamp:Date.now()})):(g="failed",l=R instanceof Error?R.message:"Agent execution failed",(h=n==null?void 0:n.onError)==null||h.call(n,l))}finally{(I=n==null?void 0:n.onServerEvent)==null||I.call(n,{type:"agent:complete",content:{status:g,durationMs:Date.now()-p},timestamp:Date.now()})}return{status:g,error:l}},d={startNode:Xt,classifierNode:Ht,llmNode:qt,memoNode:St,answerNode:Dt,apiNode:bt,toolNode:Lt};return c}var Ct=class extends Error{constructor(){super("Stopped by user"),this.name="FlowExecutionStoppedError"}};function Lo(o){var p,g;let t=(o==null?void 0:o.state)??o;if(!t||!t.nodes||!t.edges||t.edges.length===0)return{error:"Flow is missing state, nodes, or edges."};if(t.schemaVersion!==3)return{error:"Flow uses an unsupported variable schema. Recreate it in Agent Design 3.0."};for(let l of t.nodes){if(((p=l.data)==null?void 0:p.varMapping)!==void 0)return{error:`Flow uses removed varMapping on node ${l.id}.`};let f=ce(l);if(f.length>0)return{error:f[0]}}let n=t.nodes.filter(l=>l.type==="startNode");if(n.length!==1)return{error:`Flow must include exactly one START node, found ${n.length}.`};let e=n[0],s=t.nodes.filter(l=>l.type==="answerNode");if(s.length===0)return{error:"Flow must include at least one ANSWER node."};let r=new Map;for(let l of t.edges)r.has(l.source)||r.set(l.source,[]),r.get(l.source).push(l.target);let i=new Map;for(let l of t.edges)i.has(l.target)||i.set(l.target,[]),i.get(l.target).push(l.source);let c=Ee(e.id,r),d=new Set;for(let l of s){let f=Ee(l.id,i);for(let a of f)d.add(a)}let u=[];for(let l of c)if(!d.has(l)){let f=t.nodes.find(a=>a.id===l);if(f){let a=((g=f.data)==null?void 0:g.label)||"";u.push(`${l}(${a},${f.type})`)}}return u.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${u.join(", ")}`}:{startNode:e}}function Ee(o,t){let n=new Set,e=[o];for(n.add(o);e.length>0;){let s=e.shift(),r=t.get(s)||[];for(let i of r)n.has(i)||(n.add(i),e.push(i))}return n}function Ho(o,t){var n;return((n=o.state)==null?void 0:n.nodes.find(e=>e.id===t))||null}function Vo(o,t,n){var c;let e=t==null?void 0:t.state;if(!e)return null;let s=e.edges.filter(d=>d.source===o.id);if(s.length===0)return null;let r=s[0].target;if(o.type==="classifierNode"&&((c=n==null?void 0:n.context)!=null&&c.classified_id)){let d=n.context.classified_id,u=s.find(p=>p.sourceHandle===`source-${d}`);u?r=u.target:console.log(`No matching edge, falling back to first: ${r}`)}return Ho(t,r)}async function Le(o,t){var e,s;let n=(e=t==null?void 0:t.flowData)==null?void 0:e.flowId;if(!(o!=null&&o.HX_CORE_URL)||!n)return{engineState:t,refreshed:!1};try{let r=await Z(n,o),i={...t,flowData:{...r,tenant:t.flowData.tenant,flowId:n,chatId:t.flowData.chatId}},c=r==null?void 0:r.stateVersion,d=typeof c=="number"&&c!==((s=t.flowData)==null?void 0:s.stateVersion);return{engineState:i,refreshed:d}}catch(r){return console.error(`[flowRefresh] fetch failed for flow ${n}:`,r),{engineState:t,refreshed:!1}}}function He(o,t){return!o||!o.HX_ORA_URL||!o.HX_API_KEY?Promise.resolve():fetch(`${o.HX_ORA_URL}/internal/sessions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:o.HX_API_KEY},body:JSON.stringify(t)}).catch(n=>{console.error("[sessionIndex] failed to index session",n)})}function Ve(){let o={};return{add(t,n){o[t]=n},hasOutputs(){return Object.keys(o).length>0},answerNodeIds(){return Object.keys(o)},snapshotData(){let t=Object.entries(o);return t.length===1?t[0][1]:Object.fromEntries(t)}}}function qo(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function qe(o,t){if(!qo(o))throw new Error("Structured outputs require HX_ORA_URL and HX_API_KEY");let n=await fetch(`${o.HX_ORA_URL}/internal/outputs/${encodeURIComponent(t.flowId)}/${encodeURIComponent(t.sessionId)}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:o.HX_API_KEY},body:JSON.stringify({runId:t.runId,createdAt:t.createdAt,data:t.data,answerNodeIds:t.answerNodeIds})});if(!n.ok){let e=await n.text().catch(()=>"");throw new Error(`Structured output persistence failed with ${n.status}${e?`: ${e}`:""}`)}}var Se=async(o,t)=>{fetch(`${t.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),`${JSON.stringify(o)}`};async function at(o,t){var r,i;let n=o.id||o.name||"",[e,s]=String(n).split("::");if(!e||!s)return null;try{let d=(r=(await W(e,t)).metadata)==null?void 0:r.tenant,u=await Z(e,t),p=(i=o.state)==null?void 0:i.user,g={flowData:{...u,tenant:d,flowId:e,chatId:s},executedNodes:[],context:p?{user:p}:{}};return o.setState({...o.state,engineState:g}),g}catch(c){return console.error("Failed to initialize engine state:",c),null}}async function ct(o){var D,j,k,_,L;let{agent:t,env:n,ctx:e,payload:s,connection:r}=o,i=Date.now(),c=[],d=o.runId?Ve():void 0,u=async()=>await z(t),p=async N=>{await we(t,N)},g=async N=>{if(t.state.modelsCache&&t.state.modelsCache[N])return t.state.modelsCache[N];try{let{fetchOraModel:T}=await import("./oraApi-4O3W5LXD.js"),F=await T(N,n);return t.setState({...t.state,modelsCache:{...t.state.modelsCache||{},[N]:F}}),F}catch(T){throw console.error(`Error fetching model ${N}:`,T),T}},l={id:So(),role:"user",type:"text",content:s.text,images:s.images,ts:Date.now()};await p(l);let f={onChangeState:N=>{t.setState({...t.state,engineState:N})},onServerEvent:async N=>{var T;await((T=o.onServerEvent)==null?void 0:T.call(o,N)),c.push(N)},onTelemetry:async N=>{var T,F,U,M,X,b;await Se({...N,userId:o.resolveUserId(),tenant:((F=(T=t.state.engineState)==null?void 0:T.flowData)==null?void 0:F.tenant)||"",flowId:((M=(U=t.state.engineState)==null?void 0:U.flowData)==null?void 0:M.flowId)||"",sessionId:((b=(X=t.state.engineState)==null?void 0:X.flowData)==null?void 0:b.chatId)||""},n)},onError:N=>{var T;(T=o.onError)==null||T.call(o,N),t.setState({...t.state,error:N})},shouldStop:o.shouldStop},a=t.state.engineState?{...t.state.engineState}:null;if(a){let{engineState:N,refreshed:T}=await Le(n,a);a=N,T&&t.setState({...t.state,engineState:a,modelsCache:{}})}else if(a=await at(t,n),!a){let N="Failed to initialize agent";return f.onError(N),{status:"failed",error:N}}let m=o.secrets;if(!m||Object.keys(m).length===0){let N=(D=a.flowData)==null?void 0:D.tenant;m=N?await Nt(n,N):{},(j=o.onSecretsLoaded)==null||j.call(o,m)}let y=o.user??t.state.user??void 0;y&&!((k=a.context)!=null&&k.user)&&(a.context={...a.context||{},user:y});let w=pt(it(a)),h=typeof a.cycle=="number"?a.cycle:0;w.enabled&&(h=await $e(t,a),a.cycle=h,t.setState({...t.state,engineState:a}));let I=ke(t,{env:n,ctx:e,conn:r,getMessages:u,setMessages:p,getOraModel:g,secrets:m,userAuth:o.userAuth,user:y,composioSessions:o.composioSessions,publicOrigin:o.publicOrigin,skillRefCache:o.skillRefCache,runId:o.runId,outputCollector:d},a,h,o.onMemoryRef),R=await je(I,a,f)(s);if(R.status==="completed"&&o.runId&&(d!=null&&d.hasOutputs())){let{flowId:N,chatId:T}=a.flowData??{};if(!N||!T)R={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await qe(n,{flowId:N,sessionId:T,runId:o.runId,createdAt:new Date(i).toISOString(),data:d.snapshotData(),answerNodeIds:d.answerNodeIds()});let F={...a.results||{}};for(let U of d.answerNodeIds())F[U]={...F[U]||{},persisted:!0,runId:o.runId};a={...a,results:F},t.setState({...t.state,engineState:a})}catch(F){let U=F instanceof Error?F.message:"Structured output persistence failed";f.onError(U),await f.onServerEvent({type:"error:answer-output",content:{runId:o.runId,error:U},timestamp:Date.now()}),R={status:"failed",error:U}}}let{tenant:x,flowId:O,chatId:C}=a.flowData??{};return x&&O&&C&&e.waitUntil(He(n,{id:`${O}::${C}`,tenant:x,flowId:O,sessionId:C,userId:o.resolveUserId(),title:(_=s.text)==null?void 0:_.slice(0,120),turnTs:i,events:c})),R.status==="completed"&&((L=I.memoryConfig)!=null&&L.enabled)&&I.memoryConfig.mode==="summarize"&&e&&e.waitUntil(ie(t,I,h)),t.setState({...t.state,lastUpdated:new Date}),{status:R.status,error:R.error,engineState:a}}import{nanoid as Xo}from"nanoid";function Ko(o){let t=o.headers.get("X-User-Payload");if(!t)return null;try{let n=JSON.parse(t),e=typeof(n==null?void 0:n.email)=="string"?nt(n.email):null;return e?{...n,email:e}:null}catch{return null}}async function Xe(o,t,n,e){var s;try{let r=await t.json(),i=r.message;if(!i||typeof i!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let c=typeof r.userId=="string"?nt(r.userId):null,d=Ko(t),u=d==null?void 0:d.email;d?o.setState({...o.state,user:d,injectedUserId:u}):c&&!((s=o.state.user)!=null&&s.email)&&o.setState({...o.state,injectedUserId:c});let p=()=>u??c??o.state.injectedUserId??void 0;o.skillRefCache||(o.skillRefCache=new Map);let g=r.inputs&&typeof r.inputs=="object"?r.inputs:void 0;if(!o.state.engineState&&!await at(o,n))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let l=`run-${Xo(12)}`;await o.registerManualRun(l,i,p()),await rt(n,l).catch(y=>{console.warn(`[AgentHTTP] could not mark manual run ${l} as running`,y)});let f;try{f=await ct({agent:o,env:n,ctx:e,payload:{text:i,inputs:g},skillRefCache:o.skillRefCache,user:d??void 0,resolveUserId:p,runId:l,shouldStop:()=>o.isRunStopRequested(l)}),e.waitUntil(o.completeManualRun(l,f.status==="completed"?"succeeded":f.status==="stopped"?"skipped":"failed",f.error))}finally{await o.clearRunStopRequest(l)}if(f.status==="failed")return new Response(JSON.stringify({error:f.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});if(f.status==="stopped")return new Response(JSON.stringify({error:f.error||"Stopped by user"}),{status:409,headers:{"content-type":"application/json"}});let m=(await z(o)).reverse().find(y=>y.role==="assistant");return new Response(JSON.stringify({answer:(m==null?void 0:m.content)||""}),{headers:{"content-type":"application/json"}})}catch(r){return new Response(JSON.stringify({error:r.message}),{status:500,headers:{"content-type":"application/json"}})}}async function Ke(o){try{return await wt(o),await xt(o),o.skillRefCache&&o.skillRefCache.clear(),o.setState({...o.state,error:"",engineState:void 0,modelsCache:{},lastUpdated:new Date}),new Response(JSON.stringify({success:!0,messages:[]}),{headers:{"content-type":"application/json"}})}catch(t){return new Response(JSON.stringify({error:t.message}),{status:500,headers:{"content-type":"application/json"}})}}var Je="trigger:nonce:",Go=900*1e3,Kt="run:stop:",ze=class extends Jo{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{}};resolveSessionUserId(){var t;return((t=this.state.user)==null?void 0:t.email)??this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async inspectPersistedSession(t){return t==="state"?{state:this.state}:t==="messages"?{messages:await z(this)}:{context:await Re(this)}}async requestRunStop(t){return t!=null&&t.trim()?(await this.ctx.storage.put(`${Kt}${t}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(t){return!!await this.ctx.storage.get(`${Kt}${t}`)}async clearRunStopRequest(t){await this.ctx.storage.delete(`${Kt}${t}`)}async onRequest(t){let n=new URL(t.url);if(n.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(n.pathname.endsWith("/history")){let e=await z(this);return new Response(JSON.stringify(e),{headers:{"content-type":"application/json"}})}if(n.pathname.endsWith("/context")){let e={"content-type":"application/json","access-control-allow-origin":"*"};if(!t.headers.get("X-User-Payload"))return new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:e});let s=n.searchParams.get("ref");if(s){let i=await Rt(this,s);return i?new Response(JSON.stringify({entry:i}),{headers:e}):new Response(JSON.stringify({error:"Not found"}),{status:404,headers:e})}let r=await ht(this);return new Response(JSON.stringify({entries:r}),{headers:e})}return t.method==="POST"&&n.pathname.endsWith("/message")?Xe(this,t,this.env,this.ctx):t.method==="DELETE"&&n.pathname.endsWith("/clear")?Ke(this):new Response("Ready to assist.")}async onConnect(t,n){var l,f,a,m,y;let[e,s]=t.server.split("::"),i=(l=(await W(e,this.env)).metadata)==null?void 0:l.tenant;this.secrets=await Nt(this.env,i),this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let c=null;if(n.request){try{this.publicOrigin=new URL(n.request.url).origin}catch{}let w=n.request.headers.get("X-User-Payload");if(w)try{c=JSON.parse(w)}catch(h){console.warn("Failed to parse X-User-Payload",h)}}let d=await Z(e,this.env);this.setState({...this.state,user:c||null,sessionId:s,engineState:{flowData:{...d,tenant:i,flowId:e,chatId:s},executedNodes:[],context:c?{user:c}:{}}}),c||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let u=await z(this);H(t,E.SERVER_HISTORY,JSON.stringify({messages:u}));let g=(((f=d==null?void 0:d.state)==null?void 0:f.nodes)??(d==null?void 0:d.nodes)??[]).find(w=>w.type==="startNode");if(g){let w={allow_images:((a=g.data)==null?void 0:a.allow_images)??!1,allow_documents:((m=g.data)==null?void 0:m.allow_documents)??!1,greeting:(y=g.data)==null?void 0:y.greeting};H(t,E.SERVER_CONFIG,JSON.stringify(w))}}async onMessage(t,n){if(typeof n!="string")return;let e=n.indexOf(":");if(e===-1)return;let s=n.substring(0,e),r=n.substring(e+1);if(!s||!r)return;let c={[E.USER_MESSAGE]:d=>this.onUserMessage(t,d),[E.USER_CLEAR_HISTORY]:()=>this.onClearHistory(t),[E.USER_AUTH]:d=>this.onUserAuth(t,d),[E.USER_IDENTITY]:d=>this.onUserIdentity(t,d)}[s];c&&await c(r)}async onUserMessage(t,n){let e=dt(n),s=`run-${zo(12)}`;await this.registerManualRun(s,e.text),await rt(this.env,s).catch(r=>{console.warn(`[AgentDO] could not mark manual run ${s} as running`,r)});try{let r=await ct({agent:this,env:this.env,ctx:this.ctx,payload:e,connection:t,secrets:this.secrets,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:this.state.user,resolveUserId:()=>this.resolveSessionUserId(),runId:s,shouldStop:()=>this.isRunStopRequested(s),onServerEvent:i=>{H(t,E.SERVER_EVENT,JSON.stringify(i))},onError:i=>{H(t,E.SERVER_ERROR,i)},onMemoryRef:i=>{H(t,E.SERVER_EVENT,JSON.stringify({type:"info:memory:updated",content:{ref:i}}))},onSecretsLoaded:i=>{this.secrets=i}});this.ctx.waitUntil(this.completeManualRun(s,r.status==="completed"?"succeeded":r.status==="stopped"?"skipped":"failed",r.error))}finally{await this.clearRunStopRequest(s)}}registerManualRun(t,n,e){var d;let{tenant:s,flowId:r,chatId:i}=((d=this.state.engineState)==null?void 0:d.flowData)??{};if(!s||!r||!i)return Promise.resolve();let c=Ce(e||this.resolveSessionUserId(),i);return Oe(this.env,{id:t,tenant:s,flowId:r,userId:c,sessionId:i,label:n==null?void 0:n.slice(0,120)})}completeManualRun(t,n,e){return Tt(this.env,t,{status:n,error:e})}async enqueueTrigger(t){var s;if(!(t!=null&&t.runId)||!(t!=null&&t.flowId))return{queued:!1};if(t.nonce&&!await this.claimTriggerNonce(t.nonce))return console.warn(`[AgentDO] rejected replayed trigger nonce ${t.nonce}`),{queued:!1,duplicate:!0};let n=t.runAsUserId;return n&&!((s=this.state.user)!=null&&s.email)&&this.state.injectedUserId!==n&&this.setState({...this.state,injectedUserId:n}),{queued:!0,taskId:await this.queue("processTrigger",t)}}async claimTriggerNonce(t){let n=`${Je}${t}`;if(await this.ctx.storage.get(n))return!1;let e=Date.now();await this.ctx.storage.put(n,e);let r=[...(await this.ctx.storage.list({prefix:Je})).entries()].filter(([,i])=>e-i>Go).map(([i])=>i);return r.length>0&&await this.ctx.storage.delete(r),!0}async processTrigger(t){if(!(await rt(this.env,t.runId)).claimed){console.warn(`[AgentDO] activation ${t.activationId} skipped \u2014 run ${t.runId} already claimed`);return}try{this.state.engineState||await at(this,this.env);let e=tt(it(this.state.engineState)),s=Yt(e,t.inputs||{},t.label),r=await ct({agent:this,env:this.env,ctx:this.ctx,payload:{text:s,inputs:t.inputs||{}},secrets:this.secrets,composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>t.runAsUserId||this.resolveSessionUserId(),runId:t.runId,shouldStop:()=>this.isRunStopRequested(t.runId),onSecretsLoaded:i=>{this.secrets=i}});await Tt(this.env,t.runId,{status:r.status==="completed"?"succeeded":r.status==="stopped"?"skipped":"failed",error:r.error})}catch(e){let s=e instanceof Error?e.message:"Trigger execution failed";throw await Tt(this.env,t.runId,{status:"failed",error:s}),e}finally{await this.clearRunStopRequest(t.runId)}}async onUserIdentity(t,n){let e=nt(n);if(!e){H(t,E.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:e}),H(t,E.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(t,n){let e=Bt(n);if(!e){H(t,E.SERVER_ERROR,"Invalid auth payload");return}let s=e.value.trim();s===""?delete this.userAuth[e.name]:this.userAuth[e.name]=e.value,H(t,E.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:e.name,set:s!==""}}))}async onClearHistory(t){await wt(this),await xt(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear();let n=this.state.engineState?{...this.state.engineState,cycle:void 0}:void 0;this.setState({...this.state,error:"",engineState:n,modelsCache:{},lastUpdated:new Date}),t&&H(t,E.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await Ae(this);let t=await z(this);`${JSON.stringify(t)}`}async onClose(t,n,e,s){console.log(`Session closed: ${this.state.sessionId} ${n} - ${e}`)}async onError(t){console.error("AgentDO encountered an error:",t)}};function fi(o){let t=o.state;if(!t)return null;let n=["startNode","answerNode"];for(let e of n)if(!t.nodes.some(r=>r.type===e))return!1;return t.nodes.find(e=>e.type==="startNode")}import{importSPKI as Wo,jwtVerify as Yo}from"jose";function Ge(o){let t={};if(!o)return t;let n=o.split(";");for(let e of n){let s=e.indexOf("=");if(s>-1){let r=e.slice(0,s).trim(),i=e.slice(s+1).trim();r&&(t[r]=decodeURIComponent(i))}}return t}function Bo(o){return(typeof o.email=="string"?o.email.trim():"")||null}async function Y(o,t,n){let e=Ge(o.headers.get("cookie")),s=new URL(o.url),r=e.access_token||s.searchParams.get("access_token"),i=await Qo(t,r);if(i.ok){let c=i.payload,d=Bo(c);return d?{id:c.sub,email:d,name:c.name,first_name:c.given_name,last_name:c.family_name,tenant:c.tenant,roles:c["ora-roles"],db_name:c.db_name||null,user_id:c.user_id||null}:null}return null}async function Qo(o,t){if(!t||typeof t!="string")return{ok:!1,payload:null,protectedHeader:null};if(!o.KC_RS256_PK)throw new Error("PK is not defined");let n=`-----BEGIN PUBLIC KEY-----
|
|
23
|
+
`):"";e.context={user_input:I,user_images:$,files:H},e.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},(m=n==null?void 0:n.onServerEvent)==null||m.call(n,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:M,error:N}=Lo(e.flowData);if(!M)g="failed",d=N||"Flow Format Error",(l=n==null?void 0:n.onError)==null||l.call(n,d);else{let U=v(M.data),{values:D,errors:C}=Bt(U,x==null?void 0:x.inputs);if(C.length>0)return g="failed",d=`Invalid flow inputs: ${C.join("; ")}`,(f=n==null?void 0:n.onError)==null||f.call(n,d),{status:g,error:d};if(e.context={...e.context,inputs:D,...D},e.context.user_input||(e.context.user_input=I),pt(M.data)){let L=dt(ft(M.data));e.context.memory=ut(o.agentMemory||"",L).content}else e.context.memory="";await r(M),(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(x){x instanceof _t?(g="stopped",d=x.message,(h=n==null?void 0:n.onServerEvent)==null||h.call(n,{type:"agent:stopped",content:d,timestamp:Date.now()})):(g="failed",d=x instanceof Error?x.message:"Agent execution failed",(w=n==null?void 0:n.onError)==null||w.call(n,d))}finally{(R=n==null?void 0:n.onServerEvent)==null||R.call(n,{type:"agent:complete",content:{status:g,durationMs:Date.now()-p},timestamp:Date.now()})}return{status:g,error:d}},c={startNode:Jt,classifierNode:Kt,llmNode:Xt,memoNode:qt,answerNode:Dt,apiNode:Et,toolNode:Ht};return a}var _t=class extends Error{constructor(){super("Stopped by user"),this.name="FlowExecutionStoppedError"}};function Lo(o){var p,g;let t=(o==null?void 0:o.state)??o;if(!t||!t.nodes||!t.edges||t.edges.length===0)return{error:"Flow is missing state, nodes, or edges."};if(t.schemaVersion!==3)return{error:"Flow uses an unsupported variable schema. Recreate it in Agent Design 3.0."};for(let d of t.nodes){if(((p=d.data)==null?void 0:p.varMapping)!==void 0)return{error:`Flow uses removed varMapping on node ${d.id}.`};let m=se(d);if(m.length>0)return{error:m[0]}}let n=t.nodes.filter(d=>d.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(d=>d.type==="answerNode");if(s.length===0)return{error:"Flow must include at least one ANSWER node."};let r=new Map;for(let d of t.edges)r.has(d.source)||r.set(d.source,[]),r.get(d.source).push(d.target);let i=new Map;for(let d of t.edges)i.has(d.target)||i.set(d.target,[]),i.get(d.target).push(d.source);let a=Me(e.id,r),c=new Set;for(let d of s){let m=Me(d.id,i);for(let l of m)c.add(l)}let u=[];for(let d of a)if(!c.has(d)){let m=t.nodes.find(l=>l.id===d);if(m){let l=((g=m.data)==null?void 0:g.label)||"";u.push(`${d}(${l},${m.type})`)}}return u.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${u.join(", ")}`}:{startNode:e}}function Me(o,t){let n=new Set,e=[o];for(n.add(o);e.length>0;){let s=e.shift(),r=t.get(s)||[];for(let i of r)n.has(i)||(n.add(i),e.push(i))}return n}function Ho(o,t){var n;return((n=o.state)==null?void 0:n.nodes.find(e=>e.id===t))||null}function So(o,t,n){var a;let e=t==null?void 0:t.state;if(!e)return null;let s=e.edges.filter(c=>c.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 c=n.context.classified_id,u=s.find(p=>p.sourceHandle===`source-${c}`);u?r=u.target:console.log(`No matching edge, falling back to first: ${r}`)}return Ho(t,r)}import{streamText as Vo}from"ai";var Ko={short:"At most 8 bullets. Only identifiers, preferences, and decisions.",medium:"Dense bullets grouped by identity, preferences, decisions, and open tasks.",long:"Short bullets plus one-line context when a decision needs it."};function Xo(o){let t=o??{},n=t.promptTokens??t.inputTokens??0,e=t.completionTokens??t.outputTokens??0,s=t.totalTokens??n+e;return{promptTokens:n,completionTokens:e,totalTokens:s}}function qo(o){var t;for(let n=o.length-1;n>=0;n--)if(((t=o[n])==null?void 0:t.role)==="assistant"&&typeof o[n].content=="string")return o[n].content;return""}function Jo(o){var s,r;let t=((s=o.flowData)==null?void 0:s.state)??o.flowData,n=(t==null?void 0:t.nodes)??[],e=[];for(let i of n){if(i.type!=="answerNode")continue;let a=(r=o.results)==null?void 0:r[i.id];a!=null&&e.push(typeof a=="string"?a:JSON.stringify(a))}return e.join(`
|
|
24
|
+
`)}function zo(o){let t=["You maintain a KEYPOINT memory for one agent session.",`Hard limit: ${o.maxTokens} tokens.`,Ko[o.length],"Write a bullet list of durable facts only: names, identity, preferences, constraints, decisions, entities, open tasks.","Never copy the conversation. Never write User: or Assistant: lines. Never quote greetings, jokes, or the assistant\u2019s questions.","Merge with the current memory: update, dedupe, drop stale items.","If this turn added nothing durable, return the current memory unchanged.","If memory is empty and nothing durable happened, return exactly: (none)","Use the same language as the user. Return only the bullet list \u2014 no preamble."].join(" "),n=["Current keypoint memory:",'"""',o.previous.trim()||"(empty)",'"""',"","This turn (extract facts; do not transcribe):",`User said: ${o.userText.trim()||"(empty)"}`,o.assistantText.trim()?`Assistant context (do not store unless it records a user decision): ${o.assistantText.trim()}`:"",o.answers.trim()?`Answer outputs:
|
|
25
|
+
${o.answers.trim()}`:""].filter(Boolean).join(`
|
|
26
|
+
`);return{system:t,user:n}}function Wo(o){return ne(o.previous,oe(o.userText),o.maxTokens)}async function Go(o){let t="",n;for await(let e of o.fullStream)e.type==="text-delta"&&(t+=e.text??e.delta??""),e.type==="error"&&(n=e.error instanceof Error?e.error.message:String(e.error??"stream error"));return{text:t.trim(),error:n}}async function Yo(o){if(o.fullStream&&typeof o.fullStream[Symbol.asyncIterator]=="function")return Go({fullStream:o.fullStream});try{return{text:((typeof o.text=="string"?o.text:await o.text)||"").trim()}}catch(t){return{text:"",error:t instanceof Error?t.message:String(t)}}}async function be(o){var u;let t=kt(o.engineState);if(!t)return{status:"skipped",reason:"start_node_missing"};if(!pt(t))return{status:"skipped",reason:"memory_disabled"};let n=ft(t),e=dt(n),s=vt(t),r=Mt(o.previousContent||""),i=qo(o.messages),a=Jo(o.engineState),c=p=>{let g=Wo({previous:r,userText:o.userText,maxTokens:e});return{status:"written",content:g,truncated:!1,modelId:s,fallback:!0,error:g?void 0:p}};try{let p=await et(s,o.sessionEnv,{maxOutputTokens:e});if(!p)throw new Error(`Memory model '${s}' not found in registry`);let g=te(n,(u=p.reasoning)==null?void 0:u.kind),{system:d,user:m}=zo({previous:r,userText:o.userText,assistantText:i,answers:a,length:n,maxTokens:e}),l=Rt(p.reasoning),f=xt(p.provider,{effort:l,exposeReasoning:!1,maxTokens:g}),y=Vo({model:p.modelHandle,system:d,messages:[{role:"user",content:m}],...ht({...p.effectiveParams??{},maxOutputTokens:g}),...f?{providerOptions:f}:{}}),h=await Yo(y),w=Xo(await y.usage),R=Mt(h.text);if(ee(R)&&(R=""),!R)return{...c(h.error||"Memory model returned empty text"),usage:w};let x=ut(R,e);return{status:"written",content:x.content,truncated:x.truncated,usage:w,modelId:s}}catch(p){let g=p instanceof Error?p.message:"Memory update failed";return console.error("Memory update failed:",p),c(g)}}async function Fe(o,t){var e,s;let n=(e=t==null?void 0:t.flowData)==null?void 0:e.flowId;if(!(o!=null&&o.HX_CORE_URL)||!n)return{engineState:t,refreshed:!1};try{let r=await Q(n,o),i={...t,flowData:{...r,tenant:t.flowData.tenant,flowId:n,chatId:t.flowData.chatId}},a=r==null?void 0:r.stateVersion,c=typeof a=="number"&&a!==((s=t.flowData)==null?void 0:s.stateVersion);return{engineState:i,refreshed:c}}catch(r){return console.error(`[flowRefresh] fetch failed for flow ${n}:`,r),{engineState:t,refreshed:!1}}}function De(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 Ce(){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 Bo(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function Ue(o,t){if(!Bo(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 Ee=async(o,t)=>{fetch(`${t.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),`${JSON.stringify(o)}`};async function it(o,t){var r,i;let n=o.id||o.name||"",[e,s]=String(n).split("::");if(!e||!s)return null;try{let c=(r=(await G(e,t)).metadata)==null?void 0:r.tenant,u=await Q(e,t),p=(i=o.state)==null?void 0:i.user,g={flowData:{...u,tenant:c,flowId:e,chatId:s},executedNodes:[],context:p?{user:p}:{}};return o.setState({...o.state,engineState:g}),g}catch(a){return console.error("Failed to initialize engine state:",a),null}}async function at(o){var O,F,H,M,N,U,D,C,L;let{agent:t,env:n,ctx:e,payload:s,connection:r}=o,i=Date.now(),a=[],c=o.runId?Ce():void 0,u=async()=>await z(t),p=async T=>{await he(t,T)},g=async T=>{if(t.state.modelsCache&&t.state.modelsCache[T])return t.state.modelsCache[T];try{let{fetchOraModel:k}=await import("./oraApi-4O3W5LXD.js"),b=await k(T,n);return t.setState({...t.state,modelsCache:{...t.state.modelsCache||{},[T]:b}}),b}catch(k){throw console.error(`Error fetching model ${T}:`,k),k}},d={id:Zo(),role:"user",type:"text",content:s.text,images:s.images,ts:Date.now()};await p(d);let m={onChangeState:T=>{t.setState({...t.state,engineState:T})},onServerEvent:async T=>{var k;await((k=o.onServerEvent)==null?void 0:k.call(o,T)),a.push(T)},onTelemetry:async T=>{var k,b,E,A,P,_;await Ee({...T,userId:o.resolveUserId(),tenant:((b=(k=t.state.engineState)==null?void 0:k.flowData)==null?void 0:b.tenant)||"",flowId:((A=(E=t.state.engineState)==null?void 0:E.flowData)==null?void 0:A.flowId)||"",sessionId:((_=(P=t.state.engineState)==null?void 0:P.flowData)==null?void 0:_.chatId)||""},n)},onError:T=>{var k;(k=o.onError)==null||k.call(o,T),t.setState({...t.state,error:T})},shouldStop:o.shouldStop},l=t.state.engineState?{...t.state.engineState}:null;if(l){let{engineState:T,refreshed:k}=await Fe(n,l);l=T,k&&t.setState({...t.state,engineState:l,modelsCache:{}})}else if(l=await it(t,n),!l){let T="Failed to initialize agent";return m.onError(T),{status:"failed",error:T}}let f=o.secrets;if(!f||Object.keys(f).length===0){let T=(O=l.flowData)==null?void 0:O.tenant;f=T?await At(n,T):{},(F=o.onSecretsLoaded)==null||F.call(o,f)}let y=o.user??t.state.user??void 0;y&&!((H=l.context)!=null&&H.user)&&(l.context={...l.context||{},user:y});let h={env:n,ctx:e,conn:r,getMessages:u,setMessages:p,getOraModel:g,secrets:f,userAuth:o.userAuth,user:y,composioSessions:o.composioSessions,publicOrigin:o.publicOrigin,skillRefCache:o.skillRefCache,runId:o.runId,outputCollector:c,agentMemory:typeof((M=t.state.memory)==null?void 0:M.content)=="string"?t.state.memory.content:""},w=await Pe(h,l,m)(s),R=t.state.engineState??l;if(w.status==="completed")try{let T=await be({sessionEnv:h,engineState:R,previousContent:typeof((N=t.state.memory)==null?void 0:N.content)=="string"?t.state.memory.content:"",userText:s.text||"",messages:await u()});if(T.status==="skipped")await m.onServerEvent({type:"agent:memory",content:{skipped:!0,reason:T.reason},timestamp:Date.now()});else if(!T.content.trim())await m.onServerEvent({type:"agent:memory",content:{updated:!1,empty:!0,error:T.error,fallback:T.fallback},timestamp:Date.now()});else{let k={promptTokens:((U=R.tokenUsage)==null?void 0:U.promptTokens)??0,completionTokens:((D=R.tokenUsage)==null?void 0:D.completionTokens)??0,totalTokens:((C=R.tokenUsage)==null?void 0:C.totalTokens)??0};T.usage&&(k.promptTokens+=T.usage.promptTokens,k.completionTokens+=T.usage.completionTokens,k.totalTokens+=T.usage.totalTokens),R={...R,tokenUsage:k},t.setState({...t.state,engineState:R,memory:{content:T.content,updatedTs:Date.now(),...T.error?{lastError:T.error}:{},...T.fallback?{fallback:!0}:{}}}),await m.onTelemetry({type:"memory_update",payload:{model:T.modelId,truncated:T.truncated,usage:T.usage,fallback:T.fallback,error:T.error}}),await m.onServerEvent({type:"agent:memory",content:{updated:!0,truncated:T.truncated,fallback:T.fallback,error:T.error},timestamp:Date.now()})}}catch(T){let k=T instanceof Error?T.message:"Memory update failed";console.error("Memory update failed:",T),await m.onServerEvent({type:"agent:memory",content:{error:k},timestamp:Date.now()})}if(w.status==="completed"&&o.runId&&(c!=null&&c.hasOutputs())){let{flowId:T,chatId:k}=R.flowData??{};if(!T||!k)w={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await Ue(n,{flowId:T,sessionId:k,runId:o.runId,createdAt:new Date(i).toISOString(),data:c.snapshotData(),answerNodeIds:c.answerNodeIds()});let b={...R.results||{}};for(let E of c.answerNodeIds())b[E]={...b[E]||{},persisted:!0,runId:o.runId};R={...R,results:b},t.setState({...t.state,engineState:R})}catch(b){let E=b instanceof Error?b.message:"Structured output persistence failed";m.onError(E),await m.onServerEvent({type:"error:answer-output",content:{runId:o.runId,error:E},timestamp:Date.now()}),w={status:"failed",error:E}}}let{tenant:x,flowId:I,chatId:$}=R.flowData??{};return x&&I&&$&&e.waitUntil(De(n,{id:`${I}::${$}`,tenant:x,flowId:I,sessionId:$,userId:o.resolveUserId(),title:(L=s.text)==null?void 0:L.slice(0,120),turnTs:i,events:a})),t.setState({...t.state,lastUpdated:new Date}),{status:w.status,error:w.error,engineState:R}}import{nanoid as Qo}from"nanoid";function vo(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,c=vo(t),u=c==null?void 0:c.email;c?o.setState({...o.state,user:c,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 it(o,n))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let d=`run-${Qo(12)}`;await o.registerManualRun(d,i,p()),await rt(n,d).catch(y=>{console.warn(`[AgentHTTP] could not mark manual run ${d} as running`,y)});let m;try{m=await at({agent:o,env:n,ctx:e,payload:{text:i,inputs:g},skillRefCache:o.skillRefCache,user:c??void 0,resolveUserId:p,runId:d,shouldStop:()=>o.isRunStopRequested(d)}),e.waitUntil(o.completeManualRun(d,m.status==="completed"?"succeeded":m.status==="stopped"?"skipped":"failed",m.error))}finally{await o.clearRunStopRequest(d)}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 f=(await z(o)).reverse().find(y=>y.role==="assistant");return new Response(JSON.stringify({answer:(f==null?void 0:f.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 Le(o){try{return await Tt(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 He="trigger:nonce:",on=900*1e3,zt="run:stop:",Se=class extends tn{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{},memory:void 0};resolveSessionUserId(){var t;return((t=this.state.user)==null?void 0:t.email)??this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async inspectPersistedSession(t){return t==="state"?{state:this.state}:t==="memory"?{memory:this.state.memory??null}:{messages:await z(this)}}async requestRunStop(t){return t!=null&&t.trim()?(await this.ctx.storage.put(`${zt}${t}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(t){return!!await this.ctx.storage.get(`${zt}${t}`)}async clearRunStopRequest(t){await this.ctx.storage.delete(`${zt}${t}`)}async onRequest(t){let n=new URL(t.url);if(n.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(n.pathname.endsWith("/history")){let e=await z(this);return new Response(JSON.stringify(e),{headers:{"content-type":"application/json"}})}return t.method==="POST"&&n.pathname.endsWith("/message")?je(this,t,this.env,this.ctx):t.method==="DELETE"&&n.pathname.endsWith("/clear")?Le(this):new Response("Ready to assist.")}async onConnect(t,n){var d,m,l,f,y;let[e,s]=t.server.split("::"),i=(d=(await G(e,this.env)).metadata)==null?void 0:d.tenant;this.secrets=await At(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 h=n.request.headers.get("X-User-Payload");if(h)try{a=JSON.parse(h)}catch(w){console.warn("Failed to parse X-User-Payload",w)}}let c=await Q(e,this.env);this.setState({...this.state,user:a||null,sessionId:s,engineState:{flowData:{...c,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);S(t,j.SERVER_HISTORY,JSON.stringify({messages:u}));let g=(((m=c==null?void 0:c.state)==null?void 0:m.nodes)??(c==null?void 0:c.nodes)??[]).find(h=>h.type==="startNode");if(g){let h={allow_images:((l=g.data)==null?void 0:l.allow_images)??!1,allow_documents:((f=g.data)==null?void 0:f.allow_documents)??!1,greeting:(y=g.data)==null?void 0:y.greeting};S(t,j.SERVER_CONFIG,JSON.stringify(h))}}async onMessage(t,n){if(typeof n!="string")return;let e=n.indexOf(":");if(e===-1)return;let s=n.substring(0,e),r=n.substring(e+1);if(!s||!r)return;let a={[j.USER_MESSAGE]:c=>this.onUserMessage(t,c),[j.USER_CLEAR_HISTORY]:()=>this.onClearHistory(t),[j.USER_AUTH]:c=>this.onUserAuth(t,c),[j.USER_IDENTITY]:c=>this.onUserIdentity(t,c)}[s];a&&await a(r)}async onUserMessage(t,n){let e=lt(n),s=`run-${en(12)}`;await this.registerManualRun(s,e.text),await rt(this.env,s).catch(r=>{console.warn(`[AgentDO] could not mark manual run ${s} as running`,r)});try{let r=await at({agent:this,env:this.env,ctx:this.ctx,payload:e,connection:t,secrets:this.secrets,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:this.state.user,resolveUserId:()=>this.resolveSessionUserId(),runId:s,shouldStop:()=>this.isRunStopRequested(s),onServerEvent:i=>{S(t,j.SERVER_EVENT,JSON.stringify(i))},onError:i=>{S(t,j.SERVER_ERROR,i)},onSecretsLoaded:i=>{this.secrets=i}});this.ctx.waitUntil(this.completeManualRun(s,r.status==="completed"?"succeeded":r.status==="stopped"?"skipped":"failed",r.error))}finally{await this.clearRunStopRequest(s)}}registerManualRun(t,n,e){var c;let{tenant:s,flowId:r,chatId:i}=((c=this.state.engineState)==null?void 0:c.flowData)??{};if(!s||!r||!i)return Promise.resolve();let a=xe(e||this.resolveSessionUserId(),i);return Te(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 Nt(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=`${He}${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:He})).entries()].filter(([,i])=>e-i>on).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 it(this,this.env);let e=v(kt(this.state.engineState)),s=Zt(e,t.inputs||{},t.label),r=await at({agent:this,env:this.env,ctx:this.ctx,payload:{text:s,inputs:t.inputs||{}},secrets:this.secrets,composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>t.runAsUserId||this.resolveSessionUserId(),runId:t.runId,shouldStop:()=>this.isRunStopRequested(t.runId),onSecretsLoaded:i=>{this.secrets=i}});await Nt(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 Nt(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){S(t,j.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:e}),S(t,j.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(t,n){let e=Qt(n);if(!e){S(t,j.SERVER_ERROR,"Invalid auth payload");return}let s=e.value.trim();s===""?delete this.userAuth[e.name]:this.userAuth[e.name]=e.value,S(t,j.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:e.name,set:s!==""}}))}async onClearHistory(t){await Tt(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear(),this.setState({...this.state,error:"",engineState:this.state.engineState,memory:this.state.memory,modelsCache:{},lastUpdated:new Date}),t&&S(t,j.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await Re(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 Ci(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 nn,jwtVerify as sn}from"jose";function Ve(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 rn(o){return(typeof o.email=="string"?o.email.trim():"")||null}async function Y(o,t,n){let e=Ve(o.headers.get("cookie")),s=new URL(o.url),r=e.access_token||s.searchParams.get("access_token"),i=await an(t,r);if(i.ok){let a=i.payload,c=rn(a);return c?{id:a.sub,email:c,name:a.name,first_name:a.given_name,last_name:a.family_name,tenant:a.tenant,roles:a["ora-roles"],db_name:a.db_name||null,user_id:a.user_id||null}:null}return null}async function an(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
27
|
${o.KC_RS256_PK}
|
|
41
|
-
-----END PUBLIC KEY-----`,e=await
|
|
42
|
-
`)}async function eo(o,t){let n=await crypto.subtle.importKey("raw",Ye.encode(o),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return vo(await crypto.subtle.sign("HMAC",n,Ye.encode(t)))}function en(o,t){if(o.length!==t.length)return!1;let n=0;for(let e=0;e<o.length;e++)n|=o.charCodeAt(e)^t.charCodeAt(e);return n===0}async function Ci(o){let t=String(o.timestamp??Math.floor(Date.now()/1e3)),n=await eo(o.secret,to({timestamp:t,nonce:o.nonce,tenant:o.tenant,destination:o.destination,body:o.body}));return{"content-type":"application/json",[ve]:o.tenant,[Qe]:t,[Ze]:o.nonce,[Be]:`v1=${n}`}}async function oo(o){var u,p,g,l,f;if(!((u=o.secret)!=null&&u.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let t=(p=o.headers.get(ve))==null?void 0:p.trim(),n=(g=o.headers.get(Qe))==null?void 0:g.trim(),e=(l=o.headers.get(Ze))==null?void 0:l.trim(),s=(f=o.headers.get(Be))==null?void 0:f.trim();if(!t||!n||!e||!s)return{ok:!1,error:"missing signature headers"};if(!s.startsWith("v1="))return{ok:!1,error:"unsupported signature version"};let r=Number(n);if(!Number.isFinite(r))return{ok:!1,error:"invalid timestamp"};let i=Math.floor((o.now??Date.now())/1e3),c=o.toleranceSeconds??300;if(Math.abs(i-r)>c)return{ok:!1,error:"stale timestamp"};let d=await eo(o.secret.trim(),to({timestamp:n,nonce:e,tenant:t,destination:o.url,body:o.body}));return en(s.slice(3),d)?{ok:!0,tenant:t,nonce:e,timestamp:r}:{ok:!1,error:"signature mismatch"}}var J=(o,t=200)=>new Response(JSON.stringify(o),{status:t,headers:{"content-type":"application/json"}});async function no(o,t,n){var u;if(new URL(o.url).pathname!=="/api/triggers/dispatch")return;if(o.method!=="POST")return J({error:"Method not allowed"},405);let s=await o.text(),r=await oo({secret:t.HX_API_KEY,body:s,url:o.url,headers:o.headers});if(!r.ok)return console.warn(`[triggers] rejected dispatch: ${r.error}`),J({error:"Invalid signature"},401);let i;try{i=JSON.parse(s)}catch{return J({error:"Invalid payload"},400)}if(!(i!=null&&i.runId)||!(i!=null&&i.flowId)||!(i!=null&&i.runAsUserId)||!(i!=null&&i.tenant)||!(i!=null&&i.activationId)||!(i!=null&&i.triggerId)||!(i!=null&&i.triggerKind)||!(i!=null&&i.invocationMode))return J({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(i.tenant!==r.tenant)return J({error:"Tenant mismatch"},403);let c;try{c=await W(i.flowId,t)}catch{return J({error:"Flow not found"},404)}if(!((u=c==null?void 0:c.metadata)!=null&&u.tenant)||c.metadata.tenant!==i.tenant)return console.warn(`[triggers] flow ${i.flowId} does not belong to tenant ${i.tenant}`),J({error:"Tenant mismatch"},403);let d=await We(t,{...i,sessionId:i.sessionId||i.runAsUserId,nonce:r.nonce});return d.status==="error"?J({error:d.error},502):d.status==="deduped"?J({deduped:!0,runId:d.runId},200):J({accepted:!0,runId:d.runId,taskId:d.taskId},202)}var on=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,nn=new Set(["state","messages","context"]);async function sn(o,t){let n=new URL(o.url);if(!n.pathname.startsWith("/api/internal/sessions/"))return;let e=n.pathname.split("/");if(e[6]!=="runs"||e[8]!=="stop"||e.length!==9)return;if(o.method!=="POST")return new Response("Method not allowed",{status:405});if(!t.HX_API_KEY||o.headers.get("Authorization")!==t.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=decodeURIComponent(e[4]||""),r=decodeURIComponent(e[5]||""),i=decodeURIComponent(e[7]||"");if(!s||!r||!i)return new Response("Not found",{status:404});try{let c=await Ot(t.AGENT,`${s}::${r}`);return Response.json(await c.requestRunStop(i))}catch(c){return console.error("[agents] failed to request run stop",c),Response.json({error:"Failed to stop run"},{status:502})}}async function rn(o,t){let n=new URL(o.url);if(!n.pathname.startsWith("/api/internal/sessions/"))return;if(o.method!=="GET")return new Response("Method not allowed",{status:405});let e=o.headers.get("Authorization")||"";if(!t.HX_API_KEY||e!==t.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=n.pathname.split("/"),r=decodeURIComponent(s[4]||""),i=decodeURIComponent(s[5]||""),c=s[6];if(!r||!i||!c||!nn.has(c))return new Response("Not found",{status:404});try{let u=await(await Ot(t.AGENT,`${r}::${i}`)).inspectPersistedSession(c);return Response.json(u)}catch(d){return console.error("[agents] failed to inspect persisted session",d),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function bi(o,t,n){var c,d,u,p;let e=new URL(o.url),s=await no(o,t,n);if(s instanceof Response)return s;let r=await sn(o,t);if(r instanceof Response)return r;let i=await rn(o,t);if(i instanceof Response)return i;if(e.pathname.startsWith("/a/")){let g=e.pathname.split("/"),l=g[2],f=g[3];try{if(!l)return Response.redirect(new URL("/",e.origin).toString(),302);let a;try{a=await W(l,t)}catch{return new Response("Flow not found",{status:404})}if(!a.metadata||((c=a.metadata)==null?void 0:c.status)!=="active")return new Response("NO chat",{status:404});if(((d=a.metadata)==null?void 0:d.visibility)==="private"&&!await Y(o,t,n)){let y=new URL("/login",e.origin);return y.searchParams.set("nextURL",`${e.pathname}${e.search}`),Response.redirect(y.toString(),302)}if(!f){let m=crypto.randomUUID(),y=new URL(`/a/${l}/${m}`,e.origin);return Response.redirect(y.toString(),302)}if(!on.test(f))return new Response("Id del chat no v\xE1lido",{status:400})}catch(a){return console.error("Error accessing flow KV:",a),new Response("Flow error",{status:500})}}if(e.pathname.startsWith("/api/agent/flow")){let g=e.pathname.split("/"),l=g[4],f=g[5],a=`${l}::${f}`;try{let m=await Y(o,t,n);if(!m){let R=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${R}) \u2014 Composio connections from tool editor will not apply`)}let y=new Headers(o.headers);y.delete("X-User-Payload"),m&&y.set("X-User-Payload",JSON.stringify(m));let w=new Request(o,{headers:y});return(await Ot(t.AGENT,a)).fetch(w)}catch(m){return console.error("Error accessing agent:",m),new Response("Agent error",{status:500})}}if(e.pathname.startsWith("/api/ora/connect")){let g=e.pathname.split("/"),l=g[4],f=g[5];if(!l||!f)return new Response("Missing flowId or sessionId",{status:400});let a=o.headers.get("Authorization")||e.searchParams.get("authorization");if(!a)return new Response("Missing Authorization header",{status:401});try{let m=`${t.HX_CORE_URL}/p/v1/validation/key/agent/${l}`,w=await(await fetch(m,{method:"GET",headers:{Authorization:a}})).json();if(((u=w.payload)==null?void 0:u.flowId)!==l)return console.error("FlowId mismatch:",(p=w.payload)==null?void 0:p.flowId,"!==",l),new Response("Validation error",{status:403});let h=`${l}::${f}`,I=await Y(o,t,n);if(!I){let D=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${D}) \u2014 Composio connections from tool editor will not apply`)}let R=new Headers(o.headers);R.delete("X-User-Payload"),I&&R.set("X-User-Payload",JSON.stringify(I));let x=new Request(o,{headers:R});return(await Ot(t.AGENT,h)).fetch(x)}catch(m){return console.error("Error in /api/ora/connect:",m),new Response("Internal error",{status:500})}}}async function Li(o,t,n){let e=new URL(o.url),s=o.method;if(!e.pathname.startsWith("/api/instances"))return;let r=await Y(o,t,n);if(!r)return new Response("Unauthorized",{status:401});let i=t.HX_CORE_URL,c=t.HX_API_KEY;if(!i||!c)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let u=e.pathname.slice("/api/instances".length);u.startsWith("/")&&(u=u.slice(1)),u.endsWith("/")&&(u=u.slice(0,-1));let p="/ora/instances";u&&(p+=`/${u}`);let g=i.endsWith("/")?i.slice(0,-1):i,l=new URL(`${g}${p}`);e.searchParams.forEach((m,y)=>{l.searchParams.set(y,m)}),s==="GET"&&!u&&l.searchParams.set("filter_user_id",r.email);let f=new Headers;f.set("Authorization",c),f.set("Content-Type","application/json"),f.set("X-User-Payload",JSON.stringify(r));let a={method:s,headers:f};if(["POST","PATCH","PUT"].includes(s))try{a.body=await o.text()}catch(m){console.error("Error reading request body:",m)}try{let m=await fetch(l.toString(),a),y=await m.text();return new Response(y,{status:m.status,headers:{"Content-Type":"application/json"}})}catch(m){return console.error("Error proxying to flow instance backend:",m),new Response("Internal Server Error",{status:500})}}async function qi(o,t,n){let e=new URL(o.url);if(o.method==="POST"&&e.pathname==="/auth/login")try{let s=await o.formData(),r=s.get("username"),i=s.get("password"),c=s.get("nextURL")||"/";if(!r||!i)return new Response("Missing username or password",{status:400});let d=new URLSearchParams;d.append("username",r),d.append("password",i),d.append("grant_type","password"),d.append("client_id",t.KC_CLIENT_ID),d.append("client_secret",t.KC_CLIENT_SECRET);let u=await fetch(`${t.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:d});if(!u.ok)return new Response("Unauthorized",{status:401});let p=await u.json(),g=new Response(null,{status:302,headers:{Location:c}}),l=(f,a,m)=>{g.headers.append("Set-Cookie",`${f}=${a}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${m}`)};return p.access_token&&l("access_token",p.access_token,p.expires_in),p.refresh_token&&l("refresh_token",p.refresh_token,p.refresh_expires_in||3600*24*30),p.id_token&&l("id_token",p.id_token,p.expires_in),g}catch(s){return console.error("Auth error:",s),new Response("Internal Server Error",{status:500})}if(e.pathname==="/auth/logout"){let s=new Response(null,{status:302,headers:{Location:"/login"}}),r=i=>{s.headers.append("Set-Cookie",`${i}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return r("access_token"),r("refresh_token"),r("id_token"),s}if(e.pathname.startsWith("/s/")){let s=await Y(o,t,n);if(!s){let r=new URL("/login",e.origin);return r.searchParams.set("nextURL",`${e.pathname}${e.search}`),Response.redirect(r.toString(),302)}return{user:s}}}export{co as ANONYMOUS_RUN_USER_PREFIX,ze as AgentDO,mn as FLOW_INPUT_NAME_RE,Ct as FlowExecutionStoppedError,yn as GENERATION_PARAM_KEYS,hn as GENERATION_PRESETS,gn as MAX_USER_IDENTITY_LENGTH,Kn as MODEL_REGISTRY_SNAPSHOT,v as NodeType,Un as OUT_VAR_NAME_RE,wn as PRESET_PARAM_KEYS,$n as REASONING_EFFORT_LEVELS,fe as TOOL_REGISTRY_SNAPSHOT,Ze as TRIGGER_NONCE_HEADER,Be as TRIGGER_SIGNATURE_HEADER,Ai as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,ve as TRIGGER_TENANT_HEADER,Qe as TRIGGER_TIMESTAMP_HEADER,V as VariableResolutionError,In as applyPresetToOverrides,ee as buildReasoningProviderOptions,En as buildScope,Ci as buildSignedTriggerHeaders,Yt as buildTriggerMessageText,dn as buildUrl,Bo as canonicalUserEmail,rt as claimRun,xt as clearAllContext,wt as clearAllMessages,Tt as completeRun,an as convertTempMessure,Ft as createRun,Te as deleteContextToolsUpToCycle,Rn as deriveParamSupport,We as dispatchTrigger,Gt as embedText,Ae as ensureAgentTables,ao as ensureContextTable,io as ensureMessagesTable,Sn as extractTemplateReferences,jn as findScopedSourceNode,Re as getAllContext,z as getAllMessages,bn as getAncestorNodeIds,Rt as getContext,xe as getContextData,ht as getContextIndex,Mn as getDefaultOutVars,ft as getEffectiveOutVars,tt as getFlowInputDefs,Ne as getMaxContextCycle,Jn as getModelEntry,Ln as getRefTail,et as getUpstreamOutVars,bi as handleAgentsRoutes,qi as handleAuthRoutes,Ri as handleCommonRoutes,Li as handleIntancesRoutes,rn as handlePersistedSessionInspection,sn as handleSessionRunControl,no as handleTriggerRoutes,pn as hashText,at as initializeEngineState,Hn as isBinaryOutVar,pe as jsonSchemaToZod,ot as logc,E as messageTypes,tn as normalizeDestination,Tn as normalizeEffectiveParams,Wt as normalizeFlowInputs,Pn as normalizeModelEntry,kn as normalizeReasoning,An as openAiReasoningParamSupport,Nn as openAiStandardParamSupport,Ge as parseCookies,qn as parseTemplateExpression,Bt as parseUserAuth,dt as parseUserMessage,Qt as pickNodeOverrides,Fn as reasoningEffortLevels,vt as reasoningExposable,Oe as recordRun,Dn as registerProvider,fo as resolveAnswerMappings,Ie as resolveContextRef,ut as resolveModelById,Vn as resolveOutVarRef,xn as resolvePreset,te as resolveReasoningEffort,K as resolveReference,Ce as resolveRunUserId,le as resolveTemplate,Xn as rewriteTemplateNodeRefs,ct as runAgentTurn,ln as safeParseJSON,nt as sanitizeUserIdentity,Se as sendEvent,H as serverSend,he as setContext,we as setMessage,eo as signTriggerMaterial,je as startEngine,_n as stripUnsupportedFromNodeData,cn as tempTool,en as timingSafeEqualHex,Zt as toStreamTextSettings,to as triggerSignatureMaterial,un as twitter,fi as validateFlowStart,ce as validateOutVars,fn as vectorize,Qo as verifyToken,oo as verifyTriggerRequest,Y as verifyUser,mt as walkPath,On as workersAiParamSupport,Cn as xaiParamSupport};
|
|
28
|
+
-----END PUBLIC KEY-----`,e=await nn(n,"RS256");try{let{payload:s,protectedHeader:r}=await sn(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 Si(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 cn}from"agents";async function Ke(o,t){let n=t.sessionId||t.runAsUserId,e=t.inputs||{},s=t.runId;if(!s){let c=await bt(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(!c)return{status:"error",error:"Failed to register run"};if(!c.created&&c.run.status!=="queued")return{status:"deduped",runId:c.run.id};s=c.run.id}let r={...t,sessionId:n,runId:s,inputs:e},a=await(await cn(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 qe="x-ora-signature",Je="x-ora-timestamp",ze="x-ora-nonce",We="x-ora-tenant",Ji=300,Xe=new TextEncoder;function ln(o){return[...new Uint8Array(o)].map(t=>t.toString(16).padStart(2,"0")).join("")}function dn(o){try{let t=new URL(o);return`${t.origin}${t.pathname.replace(/\/$/,"")}`}catch{return o.replace(/\/$/,"")}}function Ge(o){return["v1",o.timestamp,o.nonce,o.tenant,dn(o.destination),o.body].join(`
|
|
29
|
+
`)}async function Ye(o,t){let n=await crypto.subtle.importKey("raw",Xe.encode(o),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return ln(await crypto.subtle.sign("HMAC",n,Xe.encode(t)))}function un(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 zi(o){let t=String(o.timestamp??Math.floor(Date.now()/1e3)),n=await Ye(o.secret,Ge({timestamp:t,nonce:o.nonce,tenant:o.tenant,destination:o.destination,body:o.body}));return{"content-type":"application/json",[We]:o.tenant,[Je]:t,[ze]:o.nonce,[qe]:`v1=${n}`}}async function Be(o){var u,p,g,d,m;if(!((u=o.secret)!=null&&u.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let t=(p=o.headers.get(We))==null?void 0:p.trim(),n=(g=o.headers.get(Je))==null?void 0:g.trim(),e=(d=o.headers.get(ze))==null?void 0:d.trim(),s=(m=o.headers.get(qe))==null?void 0:m.trim();if(!t||!n||!e||!s)return{ok:!1,error:"missing signature headers"};if(!s.startsWith("v1="))return{ok:!1,error:"unsupported signature version"};let r=Number(n);if(!Number.isFinite(r))return{ok:!1,error:"invalid timestamp"};let i=Math.floor((o.now??Date.now())/1e3),a=o.toleranceSeconds??300;if(Math.abs(i-r)>a)return{ok:!1,error:"stale timestamp"};let c=await Ye(o.secret.trim(),Ge({timestamp:n,nonce:e,tenant:t,destination:o.url,body:o.body}));return un(s.slice(3),c)?{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 Ze(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 Be({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 G(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 c=await Ke(t,{...i,sessionId:i.sessionId||i.runAsUserId,nonce:r.nonce});return c.status==="error"?J({error:c.error},502):c.status==="deduped"?J({deduped:!0,runId:c.runId},200):J({accepted:!0,runId:c.runId,taskId:c.taskId},202)}var pn=/^[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}$/,fn=new Set(["state","messages","memory"]);async function mn(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 gn(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||!fn.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(c){return console.error("[agents] failed to inspect persisted session",c),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function oa(o,t,n){var a,c,u,p;let e=new URL(o.url),s=await Ze(o,t,n);if(s instanceof Response)return s;let r=await mn(o,t);if(r instanceof Response)return r;let i=await gn(o,t);if(i instanceof Response)return i;if(e.pathname.startsWith("/a/")){let g=e.pathname.split("/"),d=g[2],m=g[3];try{if(!d)return Response.redirect(new URL("/",e.origin).toString(),302);let l;try{l=await G(d,t)}catch{return new Response("Flow not found",{status:404})}if(!l.metadata||((a=l.metadata)==null?void 0:a.status)!=="active")return new Response("NO chat",{status:404});if(((c=l.metadata)==null?void 0:c.visibility)==="private"&&!await Y(o,t,n)){let y=new URL("/login",e.origin);return y.searchParams.set("nextURL",`${e.pathname}${e.search}`),Response.redirect(y.toString(),302)}if(!m){let f=crypto.randomUUID(),y=new URL(`/a/${d}/${f}`,e.origin);return Response.redirect(y.toString(),302)}if(!pn.test(m))return new Response("Id del chat no v\xE1lido",{status:400})}catch(l){return console.error("Error accessing flow KV:",l),new Response("Flow error",{status:500})}}if(e.pathname.startsWith("/api/agent/flow")){let g=e.pathname.split("/"),d=g[4],m=g[5],l=`${d}::${m}`;try{let f=await Y(o,t,n);if(!f){let x=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${x}) \u2014 Composio connections from tool editor will not apply`)}let y=new Headers(o.headers);y.delete("X-User-Payload"),f&&y.set("X-User-Payload",JSON.stringify(f));let h=new Request(o,{headers:y});return(await $t(t.AGENT,l)).fetch(h)}catch(f){return console.error("Error accessing agent:",f),new Response("Agent error",{status:500})}}if(e.pathname.startsWith("/api/ora/connect")){let g=e.pathname.split("/"),d=g[4],m=g[5];if(!d||!m)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/${d}`,h=await(await fetch(f,{method:"GET",headers:{Authorization:l}})).json();if(((u=h.payload)==null?void 0:u.flowId)!==d)return console.error("FlowId mismatch:",(p=h.payload)==null?void 0:p.flowId,"!==",d),new Response("Validation error",{status:403});let w=`${d}::${m}`,R=await Y(o,t,n);if(!R){let F=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${F}) \u2014 Composio connections from tool editor will not apply`)}let x=new Headers(o.headers);x.delete("X-User-Payload"),R&&x.set("X-User-Payload",JSON.stringify(R));let I=new Request(o,{headers:x});return(await $t(t.AGENT,w)).fetch(I)}catch(f){return console.error("Error in /api/ora/connect:",f),new Response("Internal error",{status:500})}}}async function ra(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,d=new URL(`${g}${p}`);e.searchParams.forEach((f,y)=>{d.searchParams.set(y,f)}),s==="GET"&&!u&&d.searchParams.set("filter_user_id",r.email);let m=new Headers;m.set("Authorization",a),m.set("Content-Type","application/json"),m.set("X-User-Payload",JSON.stringify(r));let l={method:s,headers:m};if(["POST","PATCH","PUT"].includes(s))try{l.body=await o.text()}catch(f){console.error("Error reading request body:",f)}try{let f=await fetch(d.toString(),l),y=await f.text();return new Response(y,{status:f.status,headers:{"Content-Type":"application/json"}})}catch(f){return console.error("Error proxying to flow instance backend:",f),new Response("Internal Server Error",{status:500})}}async function ca(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 c=new URLSearchParams;c.append("username",r),c.append("password",i),c.append("grant_type","password"),c.append("client_id",t.KC_CLIENT_ID),c.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:c});if(!u.ok)return new Response("Unauthorized",{status:401});let p=await u.json(),g=new Response(null,{status:302,headers:{Location:a}}),d=(m,l,f)=>{g.headers.append("Set-Cookie",`${m}=${l}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${f}`)};return p.access_token&&d("access_token",p.access_token,p.expires_in),p.refresh_token&&d("refresh_token",p.refresh_token,p.refresh_expires_in||3600*24*30),p.id_token&&d("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{eo as ANONYMOUS_RUN_USER_PREFIX,Se as AgentDO,On as DEFAULT_MEMORY_LENGTH,_n as DEFAULT_MEMORY_MODEL,Nn as FLOW_INPUT_NAME_RE,_t as FlowExecutionStoppedError,Vn as GENERATION_PARAM_KEYS,Xn as GENERATION_PRESETS,An as MAX_USER_IDENTITY_LENGTH,kn as MEMORY_LENGTH_TOKENS,vn as MODEL_REGISTRY_SNAPSHOT,B as NodeType,Pn as OUT_VAR_NAME_RE,Kn as PRESET_PARAM_KEYS,Zn as REASONING_EFFORT_LEVELS,me as TOOL_REGISTRY_SNAPSHOT,ze as TRIGGER_NONCE_HEADER,qe as TRIGGER_SIGNATURE_HEADER,Ji as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,We as TRIGGER_TENANT_HEADER,Je as TRIGGER_TIMESTAMP_HEADER,V as VariableResolutionError,Jn as applyPresetToOverrides,xt as buildReasoningProviderOptions,Dn as buildScope,zi as buildSignedTriggerHeaders,Zt as buildTriggerMessageText,Rn as buildUrl,rn as canonicalUserEmail,ut as capMemoryContent,rt as claimRun,Tt as clearAllMessages,Nt as completeRun,yn as convertTempMessure,bt as createRun,le as deriveParamSupport,Ke as dispatchTrigger,Yt as embedText,Re as ensureAgentTables,to as ensureMessagesTable,Mn as estimateTokens,Hn as extractTemplateReferences,oe as extractUserKeypoints,Cn as findScopedSourceNode,z as getAllMessages,Fn as getAncestorNodeIds,bn as getDefaultOutVars,mt as getEffectiveOutVars,v as getFlowInputDefs,ts as getModelEntry,Un as getRefTail,tt as getUpstreamOutVars,oa as handleAgentsRoutes,ca as handleAuthRoutes,Si as handleCommonRoutes,ra as handleIntancesRoutes,gn as handlePersistedSessionInspection,mn as handleSessionRunControl,Ze as handleTriggerRoutes,Tn as hashText,it as initializeEngineState,En as isBinaryOutVar,pt as isStartMemoryEnabled,ce as jsonSchemaToZod,ot as logc,ee as looksLikeTranscript,te as memoryGenerationMaxTokens,dt as memoryTokenLimit,ne as mergeKeypointMemory,j as messageTypes,dn as normalizeDestination,ue as normalizeEffectiveParams,Bt as normalizeFlowInputs,_o as normalizeModelEntry,pe as normalizeReasoning,Wn as openAiReasoningParamSupport,zn as openAiStandardParamSupport,Ve as parseCookies,$n as parseMemoryLength,Ln as parseTemplateExpression,Qt as parseUserAuth,lt as parseUserMessage,de as pickNodeOverrides,Qn as reasoningEffortLevels,fe as reasoningExposable,Te as recordRun,Us as registerProvider,ro as resolveAnswerMappings,et as resolveModelById,jn as resolveOutVarRef,qn as resolvePreset,Rt as resolveReasoningEffort,q as resolveReference,xe as resolveRunUserId,re as resolveTemplate,Sn as rewriteTemplateNodeRefs,at as runAgentTurn,hn as safeParseJSON,Mt as sanitizeMemoryDocument,nt as sanitizeUserIdentity,Ee as sendEvent,S as serverSend,he as setMessage,Ye as signTriggerMaterial,Pe as startEngine,ft as startMemoryLength,vt as startMemoryModel,Bn as stripUnsupportedFromNodeData,wn as tempTool,un as timingSafeEqualHex,ht as toStreamTextSettings,Ge as triggerSignatureMaterial,xn as twitter,Ci as validateFlowStart,se as validateOutVars,In as vectorize,an as verifyToken,Be as verifyTriggerRequest,Y as verifyUser,gt as walkPath,Yn as workersAiParamSupport,Gn as xaiParamSupport};
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { Agent, type Connection, type ConnectionContext, type WSMessage } from 'agents';
|
|
2
2
|
import type { UserInterface } from 'lib/common/types/user-types';
|
|
3
3
|
import { type Message } from '../../common/types/agent-types';
|
|
4
|
-
import type { ContextIndexEntry, ContextRow, ContextUpsertInput, MemoryConfig } from '../../common/types/memory-types';
|
|
5
4
|
import type { TriggerActivation } from '../../common/types/trigger-types';
|
|
6
5
|
import type { FlowEngineState } from '../logic/FlowEngine';
|
|
7
6
|
import type { ComposioSessionMeta } from '../utils/composio';
|
|
@@ -16,14 +15,6 @@ export interface SessionEnv {
|
|
|
16
15
|
getMessages?: () => Promise<Message[]>;
|
|
17
16
|
setMessages?: (msg: Message) => Promise<void>;
|
|
18
17
|
getOraModel?: (modelId: string) => Promise<any>;
|
|
19
|
-
memoryConfig?: MemoryConfig;
|
|
20
|
-
cycle?: number;
|
|
21
|
-
setContext?: (row: ContextUpsertInput) => Promise<void>;
|
|
22
|
-
getContextIndex?: () => Promise<ContextIndexEntry[]>;
|
|
23
|
-
getContextData?: (ref: string) => Promise<string | null>;
|
|
24
|
-
getContext?: (ref: string) => Promise<ContextRow | null>;
|
|
25
|
-
resolveContext?: (ref: string) => Promise<ContextRow | null>;
|
|
26
|
-
pruneContext?: (upToCycle: number) => Promise<void>;
|
|
27
18
|
/** Tenant-scoped secrets resolved at session boot. Server-only — never copy into engineState or any client-bound event. */
|
|
28
19
|
secrets?: SecretsMap;
|
|
29
20
|
/** End-user-supplied ephemeral credentials sent live over WebSocket (`AUT`). DO memory only — never persisted, never copied into engineState/state/telemetry, masked in events. Resolved by `{{ auth.NAME }}`. */
|
|
@@ -44,6 +35,8 @@ export interface SessionEnv {
|
|
|
44
35
|
runId?: string;
|
|
45
36
|
/** Turn-local structured output collector. Never persisted in Agent state. */
|
|
46
37
|
outputCollector?: RunOutputCollector;
|
|
38
|
+
/** Durable memory document for this DO (from `this.state.memory`, not engineState). */
|
|
39
|
+
agentMemory?: string;
|
|
47
40
|
}
|
|
48
41
|
export type { ComposioSessionMeta };
|
|
49
42
|
export interface State {
|
|
@@ -55,14 +48,27 @@ export interface State {
|
|
|
55
48
|
engineState?: FlowEngineState;
|
|
56
49
|
error?: string;
|
|
57
50
|
modelsCache?: Record<string, any>;
|
|
51
|
+
/** Session memory document for this DO. Sibling of engineState — never copied into engineState as the source of truth. */
|
|
52
|
+
memory?: {
|
|
53
|
+
content: string;
|
|
54
|
+
updatedTs: number;
|
|
55
|
+
lastError?: string;
|
|
56
|
+
fallback?: boolean;
|
|
57
|
+
};
|
|
58
58
|
}
|
|
59
|
-
export type PersistedSessionSection = 'state' | 'messages' | '
|
|
59
|
+
export type PersistedSessionSection = 'state' | 'messages' | 'memory';
|
|
60
|
+
export type PersistedSessionMemory = {
|
|
61
|
+
content: string;
|
|
62
|
+
updatedTs: number;
|
|
63
|
+
lastError?: string;
|
|
64
|
+
fallback?: boolean;
|
|
65
|
+
};
|
|
60
66
|
export type PersistedSessionSectionResult = {
|
|
61
67
|
state: State;
|
|
62
68
|
} | {
|
|
63
69
|
messages: Message[];
|
|
64
70
|
} | {
|
|
65
|
-
|
|
71
|
+
memory: PersistedSessionMemory | null;
|
|
66
72
|
};
|
|
67
73
|
export declare class AgentDO extends Agent<Env, State> {
|
|
68
74
|
initialState: State;
|
|
@@ -78,7 +84,7 @@ export declare class AgentDO extends Agent<Env, State> {
|
|
|
78
84
|
private publicOrigin?;
|
|
79
85
|
/**
|
|
80
86
|
* Internal audit surface used by the tenant runtime. Only functional persisted data is
|
|
81
|
-
* returned: Agents SDK state plus the DO SQLite messages
|
|
87
|
+
* returned: Agents SDK state plus the DO SQLite messages table. Runtime secrets,
|
|
82
88
|
* user-provided credentials, queues and nonce storage are intentionally outside this API.
|
|
83
89
|
*/
|
|
84
90
|
inspectPersistedSession(section: PersistedSessionSection): Promise<PersistedSessionSectionResult>;
|
|
@@ -28,7 +28,6 @@ export interface AgentTurnOptions {
|
|
|
28
28
|
runId?: string;
|
|
29
29
|
onServerEvent?: (event: FlowEngineEvent) => void | Promise<void>;
|
|
30
30
|
onError?: (error: string) => void;
|
|
31
|
-
onMemoryRef?: (ref: string) => void | Promise<void>;
|
|
32
31
|
onSecretsLoaded?: (secrets: SecretsMap) => void;
|
|
33
32
|
/** Cooperative run cancellation. Manual chat turns omit it. */
|
|
34
33
|
shouldStop?: () => boolean | Promise<boolean>;
|
|
@@ -41,7 +40,7 @@ export interface AgentTurnResult {
|
|
|
41
40
|
}
|
|
42
41
|
/**
|
|
43
42
|
* Single execution path shared by every trigger source: persists the user turn, refreshes
|
|
44
|
-
* the flow, resolves
|
|
43
|
+
* the flow, resolves secrets, runs the engine and indexes the session. Callers only
|
|
45
44
|
* differ in transport (WS frames, HTTP response, queued trigger).
|
|
46
45
|
*/
|
|
47
46
|
export declare function runAgentTurn(options: AgentTurnOptions): Promise<AgentTurnResult>;
|
|
@@ -20,8 +20,6 @@ export interface FlowEngineState {
|
|
|
20
20
|
results?: Record<string, any>;
|
|
21
21
|
lastNodeId?: string;
|
|
22
22
|
lastUserMessage?: string;
|
|
23
|
-
/** Monotonic flow-run counter for session context memory. */
|
|
24
|
-
cycle?: number;
|
|
25
23
|
tokenUsage?: {
|
|
26
24
|
promptTokens: number;
|
|
27
25
|
completionTokens: number;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Message } from '../../common/types/agent-types';
|
|
2
|
+
import { type MemoryLength } from '../../common/utils/agentMemory';
|
|
3
|
+
import type { SessionEnv } from '../core/AgentDO';
|
|
4
|
+
import type { FlowEngineState } from './FlowEngine';
|
|
5
|
+
export interface MemoryWriteResult {
|
|
6
|
+
status: 'written';
|
|
7
|
+
content: string;
|
|
8
|
+
truncated: boolean;
|
|
9
|
+
usage?: {
|
|
10
|
+
promptTokens: number;
|
|
11
|
+
completionTokens: number;
|
|
12
|
+
totalTokens: number;
|
|
13
|
+
};
|
|
14
|
+
modelId?: string;
|
|
15
|
+
fallback?: boolean;
|
|
16
|
+
error?: string;
|
|
17
|
+
}
|
|
18
|
+
export type MemoryWriteOutcome = MemoryWriteResult | {
|
|
19
|
+
status: 'skipped';
|
|
20
|
+
reason: string;
|
|
21
|
+
};
|
|
22
|
+
export declare function buildMemoryWriterPrompt(input: {
|
|
23
|
+
previous: string;
|
|
24
|
+
userText: string;
|
|
25
|
+
assistantText: string;
|
|
26
|
+
answers: string;
|
|
27
|
+
length: MemoryLength;
|
|
28
|
+
maxTokens: number;
|
|
29
|
+
}): {
|
|
30
|
+
system: string;
|
|
31
|
+
user: string;
|
|
32
|
+
};
|
|
33
|
+
export declare function fallbackMemoryDocument(input: {
|
|
34
|
+
previous: string;
|
|
35
|
+
userText: string;
|
|
36
|
+
maxTokens: number;
|
|
37
|
+
}): string;
|
|
38
|
+
export declare function updateAgentMemoryAfterTurn(options: {
|
|
39
|
+
sessionEnv: SessionEnv;
|
|
40
|
+
engineState: FlowEngineState;
|
|
41
|
+
previousContent: string;
|
|
42
|
+
userText: string;
|
|
43
|
+
messages: Message[];
|
|
44
|
+
}): Promise<MemoryWriteOutcome>;
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { Message } from '../../common/types/agent-types';
|
|
2
|
-
import type { ContextIndexEntry, ContextRow, ContextUpsertInput } from '../../common/types/memory-types';
|
|
3
2
|
export type SqlContext = {
|
|
4
3
|
sql: any;
|
|
5
4
|
};
|
|
@@ -7,19 +6,4 @@ export declare function ensureMessagesTable(ctx: SqlContext): Promise<void>;
|
|
|
7
6
|
export declare function setMessage(ctx: SqlContext, msg: Message): Promise<void>;
|
|
8
7
|
export declare function getAllMessages(ctx: SqlContext): Promise<Message[]>;
|
|
9
8
|
export declare function clearAllMessages(ctx: SqlContext): Promise<void>;
|
|
10
|
-
export declare function ensureContextTable(ctx: SqlContext): Promise<void>;
|
|
11
|
-
export declare function setContext(ctx: SqlContext, row: ContextUpsertInput): Promise<void>;
|
|
12
|
-
export declare function getContextIndex(ctx: SqlContext): Promise<ContextIndexEntry[]>;
|
|
13
|
-
export declare function getAllContext(ctx: SqlContext): Promise<ContextRow[]>;
|
|
14
|
-
export declare function getContext(ctx: SqlContext, ref: string): Promise<ContextRow | null>;
|
|
15
|
-
export declare function getContextData(ctx: SqlContext, ref: string): Promise<string | null>;
|
|
16
|
-
/**
|
|
17
|
-
* Resolve a context ref the model echoed back: exact match first, else a unique prefix match
|
|
18
|
-
* (the working-memory block exposes shortened hash tails). Ambiguous prefixes resolve to null.
|
|
19
|
-
*/
|
|
20
|
-
export declare function resolveContextRef(ctx: SqlContext, ref: string): Promise<ContextRow | null>;
|
|
21
|
-
/** Evict tool-domain rows up to and including a cycle (used after a summary folds them in). */
|
|
22
|
-
export declare function deleteContextToolsUpToCycle(ctx: SqlContext, cycle: number): Promise<void>;
|
|
23
|
-
export declare function getMaxContextCycle(ctx: SqlContext): Promise<number>;
|
|
24
|
-
export declare function clearAllContext(ctx: SqlContext): Promise<void>;
|
|
25
9
|
export declare function ensureAgentTables(ctx: SqlContext): Promise<void>;
|
|
@@ -12,7 +12,7 @@ export interface FlowRefreshResult {
|
|
|
12
12
|
* which serves `GET /ora/flow/:id/state` from its own KV read/write-through cache. So this fetch is
|
|
13
13
|
* cheap on the backend even though it runs every turn.
|
|
14
14
|
*
|
|
15
|
-
* Only `flowData` is swapped; runtime state (`context`, `results`, `executedNodes
|
|
15
|
+
* Only `flowData` is swapped; runtime state (`context`, `results`, `executedNodes`) is
|
|
16
16
|
* preserved. The `stateVersion` returned in the state payload tells us whether the flow actually
|
|
17
17
|
* changed — used to decide whether to bust the per-session `modelsCache`.
|
|
18
18
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b}from"./chunk-
|
|
1
|
+
import{a,b}from"./chunk-CDGUEX3J.js";import"./chunk-A2IRPAD4.js";import"./chunk-3TXHFKDN.js";export{b as readSkillRef,a as skillTool};
|
package/package.json
CHANGED
package/dist/chunk-57TCP6J4.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{d as M,h as b,p as k}from"./chunk-GRZ6ZRHM.js";import{openai as P}from"@ai-sdk/openai";import{extractReasoningMiddleware as _,wrapLanguageModel as j}from"ai";import{createWorkersAI as A}from"workers-ai-provider";import{xai as R}from"@ai-sdk/xai";import{anthropic as O}from"@ai-sdk/anthropic";import{createOpenRouter as C}from"@openrouter/ai-sdk-provider";var y={};function f(r){if(r!=null){if(typeof r!="string")return r;try{return JSON.parse(r)}catch{return}}}function T(r){return{...r,defaultParams:f(r.defaultParams)??r.defaultParams,capabilities:f(r.capabilities)??r.capabilities,price:f(r.price)??r.price}}async function $(r,e,o){var d,l;if(!(e!=null&&e.getOraModel))throw new Error("resolveModelById requires a sessionEnv with getOraModel capable of fetching models dynamically.");let n=await e.getOraModel(r);if(!n)return;let t=T(n),m=((d=t.capabilities)==null?void 0:d.params)??M(t),{effectiveParams:a,adjustments:s}=b(t.defaultParams,o,m),i;if(y[t.provider])i=await y[t.provider](t,e,o);else if(t.provider==="openai")i=P(t.providerModel);else if(t.provider==="xai")i=R(t.providerModel);else if(t.provider==="anthropic")i=O(t.providerModel);else if(t.provider==="openrouter")i=C()(t.providerModel);else if(t.provider==="workersai"||t.provider==="cloudflare"){if(!((l=e==null?void 0:e.env)!=null&&l.AI))throw new Error("Workers AI provider requires sessionEnv.env.AI binding");i=A({binding:e.env.AI})(t.providerModel)}else i={provider:t.provider,providerModel:t.providerModel};let c=k(t);return c.kind==="tag"&&i&&typeof i=="object"&&"specificationVersion"in i&&(i=j({model:i,middleware:_({tagName:c.tagName??"think",startWithReasoning:c.startWithReasoning??!1})})),{provider:t.provider,modelHandle:i,entry:t,effectiveParams:a,paramAdjustments:s.length>0?s:void 0,reasoning:c}}function U(r,e){y[r]=e}import{generateText as N}from"ai";var x=256*1024,I=2*1024*1024-1024;function Z(r){let e=r??{};return{enabled:e.memory_enabled!==!1,mode:e.memory_mode==="summarize"?"summarize":"raw",summaryModel:typeof e.memory_summary_model=="string"?e.memory_summary_model:"gpt_5_nano",summaryThreshold:typeof e.memory_summary_threshold=="number"&&Number.isFinite(e.memory_summary_threshold)?e.memory_summary_threshold:12,toolCache:e.memory_tool_cache===!0}}function h(r){if(r==null)return"null";if(typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return`[${r.map(h).join(",")}]`;let e=r;return`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${h(e[n])}`).join(",")}}`}async function E(r){let e=h(r??null),o=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(n)).map(t=>t.toString(16).padStart(2,"0")).join("")}function v(r){return r==null?"":typeof r!="object"?String(r):Array.isArray(r)?`[${r.map(e=>typeof e=="object"?JSON.stringify(e):String(e)).join(", ")}]`:Object.entries(r).map(([e,o])=>`${e}:${typeof o=="object"?JSON.stringify(o):String(o)}`).join(",")}function L(r,e){let o=v(r);return`Params: ${o.length>100?`${o.slice(0,100)}\u2026`:o} -> Result: ${S(e)}`}async function ee(r,e){let o=new Date().toISOString();return`tool:${r}:${o}`}function S(r,e=200){var n;if(r==null)return"(empty)";if(typeof r=="string"){let t=((n=r.split(`
|
|
2
|
-
`)[0])==null?void 0:n.trim())||r;return t.length>e?`${t.slice(0,e)}\u2026`:t}if(typeof r=="object"){let t=Object.keys(r);if(t.length===0)return"{}";let a=`{${t.slice(0,5).join(", ")}${t.length>5?", \u2026":""}}`;return a.length>e?`${a.slice(0,e)}\u2026`:a}let o=String(r);return o.length>e?`${o.slice(0,e)}\u2026`:o}function re(r){let e=new TextEncoder().encode(r);if(e.length<=x)return{data:r,truncated:!1};let o=Math.min(x,I),n=e.slice(0,o);return{data:new TextDecoder().decode(n),truncated:!0}}function z(r){let e=r.split(":");if(e.length>=3){let o=e[e.length-1];if(/^[0-9a-f]{16,}$/i.test(o))return`${e.slice(0,-1).join(":")}:${o.slice(0,8)}`}return r}var D=40;function te(r,e=D){let o='\n\n## Working Memory\nYou have access to the working memory of past tool executions. To retrieve the full result payload for any reference below, call the `recall` tool with its reference string or a unique prefix of it (e.g., `recall({ reference: "tool:toolName:..." })`).';if(!r.length)return`${o}
|
|
3
|
-
(No memory entries yet)`;let n=r.filter(i=>i.domain==="summary"),t=r.filter(i=>i.domain!=="summary"),m=t.length>e?t.slice(t.length-e):t,a=t.length-m.length,s=[...n,...m].map(i=>`- ${z(i.ref)} \u2014 ${i.description}`);return a>0&&s.unshift(`- \u2026(${a} older entries omitted \u2014 rely on the summary or call recall)`),`${o}
|
|
4
|
-
${s.join(`
|
|
5
|
-
`)}`}var g=new WeakSet;async function oe(r,e,o){var m,a,s,i;let n=e.memoryConfig;if(!(n!=null&&n.enabled)||n.mode!=="summarize"||g.has(r))return;let t=await((m=e.getContextIndex)==null?void 0:m.call(e))??[];if(!(t.length<n.summaryThreshold)){g.add(r);try{let c=t.filter(p=>p.domain==="tool").map(p=>`- ${p.ref}: ${p.description}`).join(`
|
|
6
|
-
`),d=await((a=e.getContextData)==null?void 0:a.call(e,"summary:session"))??"",l=await $(n.summaryModel,e);if(!l){console.warn(`[memory] summarize model '${n.summaryModel}' not found`);return}let{text:u}=await N({model:l.modelHandle,system:"Compress the session tool-memory into a concise cumulative working summary. Merge the previous summary with the new entries. Keep key facts and tool outcomes. Output plain text, no markdown headers.",prompt:`Cycle ${o}.
|
|
7
|
-
${d?`Previous summary:
|
|
8
|
-
${d}
|
|
9
|
-
|
|
10
|
-
`:""}New tool memory entries:
|
|
11
|
-
${c||"(none)"}`}),w=(u==null?void 0:u.trim())||"(empty summary)";await((s=e.setContext)==null?void 0:s.call(e,{ref:"summary:session",domain:"summary",description:S(w,300),data:w,cycle:o,meta:JSON.stringify({kind:"session_summary"})})),await((i=e.pruneContext)==null?void 0:i.call(e,o))}catch(c){console.error("[memory] summarizeCycle failed:",c)}finally{g.delete(r)}}}function J(r){if(!r)return{};try{return JSON.parse(r)}catch{return{}}}function ne(r,e){return JSON.stringify({...J(r),...e})}export{T as a,$ as b,U as c,Z as d,E as e,L as f,ee as g,re as h,te as i,oe as j,J as k,ne as l};
|
package/dist/chunk-E7BCWUTG.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function n(t){try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e}catch{}return{text:t}}var s=256;function i(t){if(typeof t!="string")return null;let e=t.trim();return e?e.slice(0,s):null}function a(t){try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.name=="string"&&typeof e.value=="string"){let r=e.name.trim();return/^[A-Z][A-Z0-9_]*$/.test(r)?{name:r,value:e.value}:null}}catch{}return null}var l={USER_MESSAGE:"M",USER_CLEAR_HISTORY:"CH",USER_AUTH:"AUT",USER_IDENTITY:"UID",SERVER_EVENT:"SE",SERVER_HISTORY:"HIS",SERVER_ERROR:"ERR",SERVER_STEP:"STEP",SERVER_TEXT_STREAM:"TS",SERVER_TEXT_STREAM_COMPLETE:"TSC",SERVER_REASONING_STREAM:"RS",SERVER_REASONING_STREAM_COMPLETE:"RSC",SERVER_CONFIG:"CFG"};var o=[{id:"convertTempMessure",label:"Convert Temperature",description:"Convert temperature between Celsius, Fahrenheit, and Kelvin with optional static parameters"},{id:"tempTool",label:"Temp Tool",description:"Temporary demo tool"},{id:"twitter",label:"Twitter",description:"Twitter API for user info, tweets, mentions, replies, advanced search, and trends"},{id:"vectorize",label:"Vectorize",description:"Perform a semantic vector search. Returns relevant matches with scores and metadata."}],y=o.reduce((t,e)=>(t[e.id]=e,t),{});var d={};function E(t){}export{l as a,n as b,s as c,i as d,a as e,y as f,d as g,E as h};
|
package/dist/chunk-GRZ6ZRHM.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var P=["temperature","topP","topK","frequencyPenalty","presencePenalty","maxOutputTokens","seed","stopSequences","maxRetries"],y=["temperature","topP","topK","frequencyPenalty","presencePenalty"],v={precise:{temperature:.3,topP:.9,topK:30},balanced:{temperature:.8,topP:1,topK:50},creative:{temperature:1.1,topP:.95,topK:80}},g=1e-6,x={temperature:{min:0,max:2,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:{min:-2,max:2,step:.1},presencePenalty:{min:-2,max:2,step:.1},maxOutputTokens:{max:128e3},seed:!0,stopSequences:{max:4}};function E(e){return/^gpt-5/i.test(e)}function m(e){let n=e.contextWindow??128e3;return e.provider==="openai"?E(e.providerModel)?{temperature:!1,topP:!1,topK:{min:1,max:500,step:1},frequencyPenalty:{min:-2,max:2,step:.1},presencePenalty:{min:-2,max:2,step:.1},maxOutputTokens:{max:n},seed:!0,stopSequences:{max:4}}:{...x,maxOutputTokens:{max:n}}:e.provider==="xai"?{...x,maxOutputTokens:{max:n},seed:!0}:e.provider==="anthropic"?{temperature:{min:0,max:1,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:!1,presencePenalty:!1,maxOutputTokens:{max:n},seed:!1,stopSequences:{max:4}}:e.provider==="openrouter"?{temperature:{min:0,max:2,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:{min:-2,max:2,step:.1},presencePenalty:{min:-2,max:2,step:.1},maxOutputTokens:{max:n},seed:!0,stopSequences:{max:4}}:e.provider==="workersai"||e.provider==="cloudflare"?{temperature:{min:0,max:2,step:.1},topP:{min:0,max:1,step:.05},topK:{min:1,max:500,step:1},frequencyPenalty:!1,presencePenalty:!1,maxOutputTokens:{max:n},seed:!1,stopSequences:{max:4}}:{...x,maxOutputTokens:{max:n}}}function d(e,n){if(e==="maxRetries")return!0;let t=n[e];return t===!1?!1:e==="seed"?t===!0:t!==void 0}function R(e,n,t){return Math.min(t,Math.max(n,e))}function k(e,n){return e===void 0&&n===void 0?!0:e===void 0||n===void 0?!1:Math.abs(e-n)<g}function q(e,n){for(let t of["precise","balanced","creative"]){let o=v[t],i=!0;for(let r of y){if(n&&!d(r,n))continue;let f=o[r],a=e[r];if(f!==void 0){if(typeof f=="number"&&typeof a=="number"){if(!k(a,f)){i=!1;break}}else if(a!==f){i=!1;break}}}if(i)return t}return"custom"}function h(e,n){let t=v[e],o={};for(let i of y){if(n&&!d(i,n))continue;let r=t[i];r!==void 0&&(o[i]=r)}return o}function A(e){if(!e)return{};let n={};for(let t of P){let o=e[t];o!==void 0&&(t==="stopSequences"?Array.isArray(o)&&(n.stopSequences=o.filter(i=>typeof i=="string")):t==="maxRetries"?typeof o=="number"&&(n.maxRetries=o):typeof o=="number"&&(n[t]=o))}return n}function K(e,n,t){var f;let o={...e,...n},i=[],r={};for(let a of P){let p=o[a];if(p===void 0)continue;if(a==="maxRetries"){r.maxRetries=p;continue}if(!d(a,t)){i.push({key:a,action:"stripped",detail:"unsupported by model"});continue}if(a==="stopSequences"){let s=p,u=((f=t.stopSequences)==null?void 0:f.max)??s.length;s.length>u?(r.stopSequences=s.slice(0,u),i.push({key:a,action:"clamped",detail:`truncated to ${u} sequences`})):r.stopSequences=s;continue}if(a==="seed"){r.seed=p;continue}let c=t[a];if(c&&typeof c=="object"&&"min"in c){let s=p,u=R(s,c.min,c.max);r[a]=u,u!==s&&i.push({key:a,action:"clamped",detail:`clamped from ${s} to ${u}`})}else if(a==="maxOutputTokens"){let s=p,u=t.maxOutputTokens.max,l=Math.min(s,u);r.maxOutputTokens=l,l!==s&&i.push({key:a,action:"clamped",detail:`clamped from ${s} to ${l}`})}}return{effectiveParams:r,adjustments:i}}function M(e){let n={};return e.temperature!==void 0&&(n.temperature=e.temperature),e.topP!==void 0&&(n.topP=e.topP),e.topK!==void 0&&(n.topK=e.topK),e.frequencyPenalty!==void 0&&(n.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(n.presencePenalty=e.presencePenalty),e.maxOutputTokens!==void 0&&(n.maxOutputTokens=e.maxOutputTokens),e.seed!==void 0&&(n.seed=e.seed),e.stopSequences!==void 0&&(n.stopSequences=e.stopSequences),e.maxRetries!==void 0&&(n.maxRetries=e.maxRetries),n}function L(e=128e3){return m({provider:"openai",providerModel:"gpt-4.1",contextWindow:e})}function w(e=2e6){return m({provider:"openai",providerModel:"gpt-5-nano",contextWindow:e})}function N(e=256e3){return m({provider:"xai",providerModel:"grok-4-fast",contextWindow:e})}function _(e=128e3){return m({provider:"cloudflare",providerModel:"@cf/meta/llama-3.2-3b-instruct",contextWindow:e})}function I(e,n){let t={...e};for(let o of P)o==="maxRetries"||t[o]===void 0||d(o,n)||delete t[o];return t}var S=["none","minimal","low","medium","high","xhigh"],b=e=>typeof e=="string"&&S.includes(e);function j(e){var t;let n=(t=e.capabilities)==null?void 0:t.reasoning;return n&&typeof n=="object"?n:n?{kind:"effort"}:{kind:"none"}}function O(e){return e.kind!=="effort"?[]:e.levels??[]}var T=e=>e===!0||e==="true";function C(e){return e.kind==="tag"?!0:e.kind==="effort"?T(e.exposesReasoning):!1}function F(e,n){if(e.kind!=="effort")return;let t=O(e);if(b(n)&&t.includes(n))return n;if(e.defaultLevel&&t.includes(e.defaultLevel))return e.defaultLevel}function $(e,n){let{effort:t,exposeReasoning:o,maxTokens:i}=n;if(e==="openai"){let r={};return t&&(r.reasoningEffort=t),o&&(r.reasoningSummary="auto"),Object.keys(r).length?{openai:r}:void 0}if(e==="xai")return t?{xai:{reasoningEffort:t}}:void 0;if(e==="openrouter"){if(!i&&!t)return;let r={};return o!==void 0&&(r.exclude=!o),i?{openrouter:{reasoning:{...r,max_tokens:i}}}:{openrouter:{reasoning:{...r,effort:t}}}}if(e==="anthropic"){let r={};return(t||o)&&(r.thinking={type:"adaptive",...o?{display:"summarized"}:{}}),t&&(r.effort=t),Object.keys(r).length?{anthropic:r}:void 0}}export{P as a,y as b,v as c,m as d,q as e,h as f,A as g,K as h,M as i,L as j,w as k,N as l,_ as m,I as n,S as o,j as p,O as q,C as r,F as s,$ as t};
|
package/dist/chunk-K4MP63XM.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
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};
|
package/dist/chunk-W6DBEVOO.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
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
|
-
|
|
3
|
-
References:
|
|
4
|
-
${u.join(`
|
|
5
|
-
`)}`}function w(e,c,u,t){if(e.kind!=="skill")throw new Error(`skillTool: unsupported kind '${e.kind}' for tool '${e.name}'`);let a=typeof e.execution=="string"?JSON.parse(e.execution):e.execution||{},n=a.instructions||"",o=Array.isArray(a.references)?a.references:[],h=R(e.name,o);return k({description:e.description||e.label||e.name,inputSchema:m.object({}),execute:async()=>(t==null||t({type:"info:skill:bodyServed",content:{skill:e.name,refCount:o.length,refs:o.map(s=>s.name)}}),{instructions:n,references:o,...h?{how_to_use_references:h}:{}})})}function T(e,c,u,t){return k({description:"Loads the full content of an in-depth reference document belonging to a skill that was already opened in this conversation. Pass the skill name and the reference name exactly as listed in the skill's reference menu.",inputSchema:m.object({skill:m.string().describe("The name of the skill/tool that owns the reference"),ref:m.string().describe("The name of the reference document to read")}),execute:async({skill:a,ref:n})=>{var p,y;t==null||t({type:"info:skill:refRequested",content:{skill:a,ref:n}});let o=c.find(i=>i.name===a);if(!o){let i=c.map(l=>l.name).join(", ");return t==null||t({type:"warn:skill:skillMissing",content:{skill:a,availableSkills:i}}),{error:`Skill "${a}" not found or not attached to this LLM node.`,availableSkills:i}}let s=(typeof o.execution=="string"?JSON.parse(o.execution):o.execution||{}).references||[];if(!s.find(i=>i.name===n)){let i=s.map(l=>l.name).join(", ");return t==null||t({type:"warn:skill:refMissing",content:{skill:a,ref:n,availableRefs:i||"(none)"}}),{error:`Reference "${n}" not found in skill "${a}".`,availableRefs:i||"(none)"}}let f=`${o.id}:${n}`;if(e.skillRefCache&&e.skillRefCache.has(f))return t==null||t({type:"info:skill:refCacheHit",content:{skill:a,ref:n,tier:1}}),{name:n,content:e.skillRefCache.get(f)};let d=`skill:${o.id}:${n}`;if((p=e.memoryConfig)!=null&&p.enabled&&e.getContext)try{let i=await e.getContext(d),l=i!=null&&i.meta?JSON.parse(i.meta).truncated:!1;if(i!=null&&i.data&&!l)return t==null||t({type:"info:skill:refCacheHit",content:{skill:a,ref:n,tier:2}}),e.skillRefCache&&e.skillRefCache.set(f,i.data),{name:n,content:i.data}}catch(i){console.warn(`[readSkillRef] failed to check context memory for ${d}:`,i)}if(!e.env)throw new Error("Cloudflare bindings / Env missing on sessionEnv");t==null||t({type:"info:skill:refFetching",content:{skill:a,ref:n,toolId:o.id}});let r=await g(e.env,o.id,n);if(e.skillRefCache&&e.skillRefCache.set(f,r.content),(y=e.memoryConfig)!=null&&y.enabled&&e.setContext)try{await e.setContext({ref:d,domain:"skill",description:`Skill reference doc for ${a} (${n})`,data:r.content,cycle:e.cycle??0,meta:JSON.stringify({toolName:"readSkillRef",skill:a,ref:n,cacheable:!0})})}catch(i){console.warn(`[readSkillRef] failed to save to context memory for ${d}:`,i)}return t==null||t({type:"info:skill:refFetched",content:{skill:a,ref:n,bytes:r.content.length}}),{name:n,content:r.content}}})}export{w as a,T as b};
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
export type MemoryMode = 'raw' | 'summarize';
|
|
2
|
-
export type ContextDomain = 'tool' | 'summary' | 'keydata' | 'info' | 'skill';
|
|
3
|
-
export interface MemoryConfig {
|
|
4
|
-
enabled: boolean;
|
|
5
|
-
mode: MemoryMode;
|
|
6
|
-
summaryModel: string;
|
|
7
|
-
summaryThreshold: number;
|
|
8
|
-
toolCache: boolean;
|
|
9
|
-
}
|
|
10
|
-
export interface ContextMeta {
|
|
11
|
-
toolName?: string;
|
|
12
|
-
paramsHash?: string;
|
|
13
|
-
cacheable?: boolean;
|
|
14
|
-
truncated?: boolean;
|
|
15
|
-
}
|
|
16
|
-
export interface ContextRow {
|
|
17
|
-
ref: string;
|
|
18
|
-
domain: ContextDomain;
|
|
19
|
-
description: string;
|
|
20
|
-
data?: string;
|
|
21
|
-
cycle: number;
|
|
22
|
-
meta?: string;
|
|
23
|
-
ts: number;
|
|
24
|
-
}
|
|
25
|
-
export type ContextIndexEntry = Pick<ContextRow, 'ref' | 'domain' | 'description' | 'cycle' | 'ts' | 'meta'>;
|
|
26
|
-
export type ContextUpsertInput = Omit<ContextRow, 'ts'> & {
|
|
27
|
-
ts?: number;
|
|
28
|
-
};
|
|
@@ -1 +0,0 @@
|
|
|
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/recall-IABRCSHY.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{k as a}from"./chunk-57TCP6J4.js";import"./chunk-GRZ6ZRHM.js";import"./chunk-3TXHFKDN.js";import{tool as i}from"ai";import{z as m}from"zod";function y(t,l,c,r){return i({description:"Retrieve full stored data for a working-memory reference from a prior tool call or summary. Use the ref from the ## Working memory block.",inputSchema:m.object({reference:m.string().describe("The memory reference key, e.g. tool:myTool:abc123")}),execute:async({reference:o})=>{var n;let e=await((n=t.resolveContext)==null?void 0:n.call(t,o))??null;if(!e||e.data==null)return r==null||r({type:"warn:memory:recallMiss",content:{reference:o}}),{error:`No memory found for reference: ${o}`};if(a(e.meta).truncated===!0)return{ref:e.ref,truncated:!0,partial:e.data};try{return JSON.parse(e.data)}catch{return e.data}}})}export{y as recall};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { type Tool } from 'ai';
|
|
2
|
-
import type { SessionEnv } from '../core/AgentDO';
|
|
3
|
-
import type { FlowEngineState } from '../logic/FlowEngine';
|
|
4
|
-
export declare function recall(sessionEnv: SessionEnv, _engineState: FlowEngineState, _opts?: unknown, onServerEvent?: (event: {
|
|
5
|
-
type: string;
|
|
6
|
-
content: unknown;
|
|
7
|
-
}) => void): Tool;
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import type { MemoryConfig, ContextIndexEntry } from '../../common/types/memory-types';
|
|
2
|
-
import type { SessionEnv } from '../core/AgentDO';
|
|
3
|
-
/** Target cap for stored payloads (~256 KB). Hard ceiling stays under DO 2 MB row limit. */
|
|
4
|
-
export declare const DATA_CAP_BYTES: number;
|
|
5
|
-
export declare const DATA_HARD_CAP_BYTES: number;
|
|
6
|
-
export declare function buildMemoryConfig(startNodeData?: Record<string, unknown>): MemoryConfig;
|
|
7
|
-
/** Canonical JSON with sorted object keys for stable hashing. */
|
|
8
|
-
export declare function canonicalize(value: unknown): string;
|
|
9
|
-
export declare function hashParams(args: unknown): Promise<string>;
|
|
10
|
-
export declare function formatParams(args: unknown): string;
|
|
11
|
-
export declare function buildToolDescription(args: unknown, rawResult: unknown): string;
|
|
12
|
-
export declare function buildToolRef(toolName: string, args?: unknown): Promise<string>;
|
|
13
|
-
export declare function cheapSummary(result: unknown, maxLen?: number): string;
|
|
14
|
-
export declare function capData(raw: string): {
|
|
15
|
-
data: string;
|
|
16
|
-
truncated: boolean;
|
|
17
|
-
};
|
|
18
|
-
/** Shorten the hash tail of a tool/context ref so the model can echo it reliably in `recall`. */
|
|
19
|
-
export declare function shortRef(ref: string): string;
|
|
20
|
-
/** Max non-summary entries injected into the prompt; summaries are always kept. */
|
|
21
|
-
export declare const WORKING_MEMORY_MAX_ENTRIES = 40;
|
|
22
|
-
export declare function formatWorkingMemoryBlock(index: ContextIndexEntry[], maxEntries?: number): string;
|
|
23
|
-
export declare function summarizeCycle(agent: object, sessionEnv: SessionEnv, cycle: number): Promise<void>;
|
|
24
|
-
export declare function parseContextMeta(meta?: string): Record<string, unknown>;
|
|
25
|
-
export declare function mergeContextMeta(existing: string | undefined, patch: Record<string, unknown>): string;
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import type { SessionEnv } from '../core/AgentDO';
|
|
2
|
-
import type { FlowEngineState } from '../logic/FlowEngine';
|
|
3
|
-
import { type SqlContext } from '../sql/agentSQL';
|
|
4
|
-
export declare function findStartNodeData(engineState?: FlowEngineState): Record<string, unknown> | undefined;
|
|
5
|
-
export declare function resolveCycle(agent: SqlContext, engineState: FlowEngineState): Promise<number>;
|
|
6
|
-
export declare function buildMemorySessionEnv(agent: SqlContext, base: Omit<SessionEnv, 'memoryConfig' | 'cycle' | 'setContext' | 'getContextIndex' | 'getContextData' | 'getContext' | 'resolveContext' | 'pruneContext'>, engineState: FlowEngineState, cycle: number, onMemoryUpdated?: (ref: string) => void | Promise<void>): SessionEnv;
|
|
7
|
-
export declare function emitMemoryUpdated(onServerEvent: ((event: {
|
|
8
|
-
type: string;
|
|
9
|
-
content: unknown;
|
|
10
|
-
timestamp?: number;
|
|
11
|
-
}) => void | Promise<void>) | undefined, ref: string): Promise<void>;
|
|
12
|
-
export declare function newFlowEventId(): string;
|