@hugex/ai 2.8.15 → 2.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +7 -0
- package/dist/index.js +10 -10
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -47,6 +47,10 @@ interface FlowData {
|
|
|
47
47
|
flowId: string;
|
|
48
48
|
chatId: string;
|
|
49
49
|
state?: FlowState;
|
|
50
|
+
/** Monotonic version from FlowDO, bumped on every state save. Undefined for flows
|
|
51
|
+
* never re-saved since versioning shipped — treated as "unknown", never stale. */
|
|
52
|
+
stateVersion?: number;
|
|
53
|
+
detail?: Record<string, any>;
|
|
50
54
|
}
|
|
51
55
|
|
|
52
56
|
interface TelemetryEvent {
|
|
@@ -156,6 +160,9 @@ declare class AgentDO extends Agent<Env, State> {
|
|
|
156
160
|
private skillRefCache;
|
|
157
161
|
/** Public origin from the active socket upgrade (used for OAuth callback URLs). */
|
|
158
162
|
private publicOrigin?;
|
|
163
|
+
/** Throttles the per-turn flow-version KV probe (DO memory only; resets on hibernation,
|
|
164
|
+
* which just means the next turn re-probes — correct, only loses the throttle benefit). */
|
|
165
|
+
private lastFlowVersionCheckTs;
|
|
159
166
|
onRequest(request: Request): Promise<Response>;
|
|
160
167
|
onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
|
|
161
168
|
onMessage(connection: Connection, message: WSMessage): Promise<void>;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as it,b as
|
|
1
|
+
import{a as it,b as Ut,c as Kt,d as Wt}from"./chunk-26SLPOG6.js";import{a as zt}from"./chunk-GOWQA2OT.js";import{a as mo,b as at,c as yo,d as G,e as xt,f as Gt,g as Bt,h as Qt,i as Zt,j as rt,k as Rt,l as St}from"./chunk-57TCP6J4.js";import{a as Yt,b as Et}from"./chunk-4FUIFBZO.js";import{a as P,b as et,c as Be,d as ot,e as bt,f as Jt,g as go,h as ho}from"./chunk-HAYNUZZB.js";import{a as E,b as Qe,c as Ze,d as st,e as nt,f as Pt}from"./chunk-OYP6D5VN.js";import{a as Se,b as ve,c as to,d as eo,e as oo,f as so,g as Lt,h as no,i as jt,j as io,k as ao,l as ro,m as lo,n as co,o as fo,p as po,q as uo,r as Ht,s as Vt,t as qt}from"./chunk-GRZ6ZRHM.js";import{a as Ke}from"./chunk-43NDF544.js";import{a as Xe}from"./chunk-2JN3IX2Y.js";import{a as Ye}from"./chunk-6HY7QUMP.js";import{a as We,b as ze}from"./chunk-V6JSMX5A.js";import{a as z,b as Y,c as Ee,d as Dt,e as Ge}from"./chunk-TUI5H3ZB.js";import{a as tt}from"./chunk-U56YWPSI.js";import{a as Xt}from"./chunk-YHXUBVN2.js";import{a as v}from"./chunk-6BYZCJPP.js";import{Agent as Ue}from"agents";import{nanoid as Le}from"nanoid";async function vt(o,e){return o.length?!e||!e.HX_ORA_URL||!e.HX_API_KEY?(console.error("extractDocuments: missing HX_ORA_URL or HX_API_KEY"),o.map(t=>({name:t.name,text:""}))):await Promise.all(o.map(async t=>{try{let n=await fetch(`${e.HX_ORA_URL}/internal/files/extract`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e.HX_API_KEY},body:JSON.stringify(t)});if(!n.ok)return console.error(`extractDocuments: ${t.name} failed ${n.status}`),{name:t.name,text:""};let l=await n.json();return{name:t.name,text:l.text||""}}catch(n){return console.error(`extractDocuments: ${t.name} threw`,n),{name:t.name,text:""}}})):[]}async function Nt(o,e,s,t,n,l,p){var c,d,u;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});try{let r=await((c=o.getMessages)==null?void 0:c.call(o))??[],{flowId:f,chatId:a,tenant:m}=s.flowData,i=((d=r[r.length-1])==null?void 0:d.type)==="text"?r[r.length-1].content:"NO-TEXT";p==null||p({type:"answer_node",payload:{userMessage:(u=s==null?void 0:s.context)==null?void 0:u.user_input,answer:i}})}catch(r){console.error("answerNodeRunner: failed to emit answer telemetry:",r),t==null||t({type:"debug",content:"Warning: failed to emit answer telemetry"}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(r)}})}n==null||n(e.id,{type:"answerNode",message:"Answer response for: "+e.data.response,saved:!0}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}function K(o,e,s,t,n){var c,d,u;let l=(n==null?void 0:n.callerTag)??"llmNodeRunner",p=(n==null?void 0:n.serializeNonStrings)??!1;try{return Pt(o,e,{context:s.context??{},results:s.results??{},nodes:((d=(c=s.flowData)==null?void 0:c.state)==null?void 0:d.nodes)??[],secrets:(u=n==null?void 0:n.sessionEnv)==null?void 0:u.secrets},{callerTag:l,serializeNonStrings:p,onError:r=>{t==null||t({type:`error:${l}`,content:r})}})}catch(r){return console.error(r),"error"}}var te="[redacted]",Ct=(o,e,s,t,n)=>K(o,e,s,n,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function Tt(o,e,s,t,n,l,p){var u,r,f,a,m,i;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=null,d=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(s.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(s.results||{}));let g=((u=e.data)==null?void 0:u.url)||"",h=Ct(g,e,s,o,t);if(console.log("[apiNodeRunner] resolved url:",it(g)?Ut(h):h),!h){t==null||t({type:"error:apiNodeRunner",content:"Missing url"}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:"Missing url"}}),n==null||n(e.id,c);return}let w=(((r=e.data)==null?void 0:r.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",w);let y=((f=e.data)==null?void 0:f.headers)||{},x={},C={};for(let D in y)if(Object.prototype.hasOwnProperty.call(y,D)){let q=String(y[D]??"");C[D]=it(q),x[D]=Ct(q,e,s,o,t)}let R,$=!1;if(w!=="GET"&&w!=="HEAD"&&((a=e.data)==null?void 0:a.body)!==void 0){let D=typeof e.data.body=="string"?e.data.body:JSON.stringify(e.data.body);$=it(D),R=Ct(D,e,s,o,t),!x["Content-Type"]&&!x["content-type"]&&(x["Content-Type"]="application/json")}let _={};for(let D in x)_[D]=C[D]?te:x[D];console.log("[apiNodeRunner] headers:",JSON.stringify(_)),console.log("[apiNodeRunner] body:",$?te:R),t==null||t({type:"info:apiNodeRunner",content:`${w} ${h}`});let I=Number((m=e.data)==null?void 0:m.timeoutMs),A=new AbortController,k=Number.isFinite(I)&&I>0?setTimeout(()=>A.abort(),I):null,M;try{console.log("[apiNodeRunner] fetching..."),M=await fetch(h,{method:w,headers:x,body:R,signal:A.signal}),console.log("[apiNodeRunner] fetch returned status:",M.status)}finally{k&&clearTimeout(k)}let j=M.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",j);let N;j.includes("application/json")?N=await M.json():N=await M.text(),console.log("[apiNodeRunner] payload preview:",typeof N=="string"?N.slice(0,200):JSON.stringify(N).slice(0,200)),c={ok:M.ok,status:M.status,data:N};let b=Date.now()-d;p==null||p({type:"api_call",payload:{nodeId:e.id,url:h,method:w,status:M.status,latencyMs:b}}),t==null||t({type:"info:apiNodeRunner",content:`Response ${M.status} (${b}ms)`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}catch(g){console.error("Error processing ApiNode:",g),t==null||t({type:"error:apiNodeRunner",content:`API node execution failed: ${g}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(g)}})}finally{console.log("[apiNodeRunner] final result:",(i=JSON.stringify(c))==null?void 0:i.slice(0,300)),n==null||n(e.id,c)}}import{generateObject as we}from"ai";import{z as ee}from"zod";async function It(o,e,s,t,n,l,p){var g,h,w;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=(s==null?void 0:s.context)??{},d=String(((g=e==null?void 0:e.data)==null?void 0:g.input_variable)||"user_input").trim(),u=(c==null?void 0:c[d])??"",r=Array.isArray((h=e==null?void 0:e.data)==null?void 0:h.items)?e.data.items:[];if(r.length===0){t==null||t({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let f=String((w=r[r.length-1])==null?void 0:w.id);if(!u||String(u).trim().length===0){t==null||t({type:"warning:classifier",content:"No input for classification \u2014 falling back to last item."}),n==null||n(e.id,{classification:f}),s.context=s.context||{},s.context.classified_id=f,l==null||l(s);return}let m=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
|
|
2
2
|
If the message is ambiguous or none clearly matches, choose the LAST category in the list.
|
|
3
3
|
|
|
4
4
|
Categories:
|
|
@@ -7,20 +7,20 @@ ${r.map(y=>{let x=y.keywords??y["keywords/topics"]??"",C=Array.isArray(x)?x.join
|
|
|
7
7
|
keywords/topics: ${C}`}).join(`
|
|
8
8
|
`)}
|
|
9
9
|
`,i=`User message:
|
|
10
|
-
"""${String(
|
|
10
|
+
"""${String(u).trim()}"""
|
|
11
11
|
|
|
12
|
-
Select the best matching category id.`;try{let y=Date.now(),x=r.map(
|
|
12
|
+
Select the best matching category id.`;try{let y=Date.now(),x=r.map(M=>String(M.id)),C="gpt_4_1_mini",R=await at(C,o);if(!R)throw new Error(`Model '${C}' not found in registry`);let{modelHandle:$,effectiveParams:_}=R,I=await we({model:$,messages:[{role:"system",content:m},{role:"user",content:i}],schema:ee.object({classification:ee.enum(x).describe("The id of the best matching category")}),temperature:_.temperature??0}),A=Date.now()-y,k=I.object.classification;p==null||p({type:"class_telemetry",payload:{nodeId:e.id,totalLatency:A,model:I.response.modelId,usage:I.usage,options:x}}),p==null||p({type:"class_result",payload:{result:I}}),n==null||n(e.id,{classification:k}),s.context=s.context||{},s.context.classified_id=k,l==null||l(s),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}catch(y){t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(y)}})}}import{stepCountIs as Ne,streamText as Ce}from"ai";import{nanoid as Te}from"nanoid";import"zod";var U=(o,e,s)=>{o.send(e+"::"+s)};function oe(o,e){var t,n,l,p,c,d;let s="";if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let u of o.data.varMapping){let r=u.from;if(!r)continue;let f=!1;if(r==="files"||r==="file_content")f=!0;else{let a=r.indexOf(".");if(a!==-1){let m=r.substring(0,a),i=r.substring(a+1).split(".")[0],g=(p=(l=(n=e.flowData)==null?void 0:n.state)==null?void 0:l.nodes)==null?void 0:p.find(h=>h.id===m);if(g){let w=st(g).find(y=>y.name===i);(w==null?void 0:w.type)==="file"&&(f=!0)}}}if(f){let a=nt(r,{context:e.context||{},results:e.results||{},nodes:((d=(c=e.flowData)==null?void 0:c.state)==null?void 0:d.nodes)||[]});typeof a=="string"&&a.trim()&&(s+=(s?`
|
|
13
13
|
|
|
14
|
-
`:"")+a)}}return s}function oe(o,e){var t,n,l,m,c,d;let s=[];if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let f of o.data.varMapping){let r=f.from;if(!r)continue;let p=!1;if(r==="images")p=!0;else{let a=r.indexOf(".");if(a!==-1){let u=r.substring(0,a),i=r.substring(a+1).split(".")[0],g=(m=(l=(n=e.flowData)==null?void 0:n.state)==null?void 0:l.nodes)==null?void 0:m.find(h=>h.id===u);if(g){let w=st(g).find(y=>y.name===i);(w==null?void 0:w.type)==="image"&&(p=!0)}}}if(p){let a=nt(r,{context:e.context||{},results:e.results||{},nodes:((d=(c=e.flowData)==null?void 0:c.state)==null?void 0:d.nodes)||[]});Array.isArray(a)&&s.push(...a)}}return s}var we=S({"../tools/composioTool.ts":()=>import("./composioTool-EXCSM6F4.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-TT7DIP6C.js"),"../tools/httpTool.ts":()=>import("./httpTool-EU63HPF5.js"),"../tools/recall.ts":()=>import("./recall-SD6FENAS.js"),"../tools/skillTool.test.ts":()=>import("./skillTool.test-6UDHQARG.js"),"../tools/skillTool.ts":()=>import("./skillTool-Y5GZ4ZAR.js"),"../tools/tempTool.ts":()=>import("./tempTool-6Q6C4HEJ.js"),"../tools/twitter.ts":()=>import("./twitter-QNCTAE4E.js"),"../tools/vectorize.ts":()=>import("./vectorize-SQROWLSU.js")});var xe=S({});function It(o,e,s,t,n){var m;if(!((m=t.memoryConfig)!=null&&m.enabled)||!t.memoryConfig.toolCache||!s.cacheable||!e||typeof e.execute!="function")return e;let l=e.execute.bind(e);return e.execute=async(c,...d)=>{var a;if(!t.getContextIndex)return l(c,...d);let f=await wt(c),p=(await t.getContextIndex()).find(u=>{if(u.domain!=="tool")return!1;let i=xt(u.meta);return i.toolName===o&&i.paramsHash===f});if(p){let u=await((a=t.getContext)==null?void 0:a.call(t,p.ref));if((u==null?void 0:u.data)!=null&&xt(u.meta).truncated!==!0){n==null||n({type:"info:memory:cacheHit",content:{ref:u.ref,toolName:o}});try{return JSON.parse(u.data)}catch{return u.data}}}return l(c,...d)},e}async function Te(o,e,s,t){var r,p;if(!((r=s.memoryConfig)!=null&&r.enabled)||!s.setContext||s.cycle==null)return;let n=o.toolCalls??[],l=o.toolResults??[];if(!n.length||!l.length)return;let m=new Map;for(let a of l)a!=null&&a.toolCallId&&m.set(a.toolCallId,a);let c=Array.isArray((p=e==null?void 0:e.data)==null?void 0:p.tools)?e.data.tools:[],d=new Map;for(let a of c)a&&typeof a.id=="string"&&d.set(a.id,a);let f=new Map;for(let a of Object.values(s.toolDefs??{}))a&&a.name&&f.set(a.name,a);for(let a of n){let u=a.toolCallId,i=a.toolName,g=m.get(u);if(!i||!g||i==="readSkillRef")continue;let h=a.args??a.input,w=g.result??g.output,y=!1,x="",C="tool",N="",$=f.get(i);$&&$.kind==="skill"&&(y=!0,x=`skill:${i}`,C="skill",N=`Skill instructions for ${i}`),x||(x=await Bt(i,h),N=Gt(h,w));let R=d.get(i)??c.find(A=>A.id===i),k=await wt(h),D=typeof w=="string"?w:JSON.stringify(w??null);await s.setContext({ref:x,domain:C,description:N,data:D,cycle:s.cycle,meta:JSON.stringify({toolName:i,paramsHash:k,cacheable:(R==null?void 0:R.cacheable)===!0})}),t==null||t({type:"info:memory:updated",content:{ref:x}})}}async function Ie(o,e,s,t){var p;let n=Array.isArray((p=s==null?void 0:s.data)==null?void 0:p.tools)?s.data.tools:[];if(n.length===0)return{};let l={},m=a=>{var x,C;let u=typeof(a==null?void 0:a.description)=="string"?a.description:"",i=a==null?void 0:a.inputSchema,g;try{let N=(i==null?void 0:i.shape)??(typeof((x=i==null?void 0:i._def)==null?void 0:x.shape)=="function"?i._def.shape():(C=i==null?void 0:i._def)==null?void 0:C.shape);N&&typeof N=="object"&&(g=N)}catch{}let h=g?Object.keys(g):[],w=u?`description="${u.length>120?u.slice(0,120)+"\u2026":u}"`:"description=(none)",y=h.length?`inputSchema={${h.join(", ")}}`:"inputSchema=(none)";return`${w} ${y}`},c=(()=>{let a=[],u=[],i=[],g=[];for(let w=0;w<n.length;w++){let y=n[w];!y||typeof y!="object"||typeof y.id!="string"?g.push(w):y.kind==="builtin"?a.push(y.id):y.kind==="skill"?i.push(y.id):y.kind==="http"||y.kind==="mcp"||y.kind==="composio"?u.push(y.id):g.push(w)}let h=[];return a.length&&h.push(`builtin[${a.join(", ")}]`),u.length&&h.push(`custom[${u.join(", ")}]`),i.length&&h.push(`skill[${i.join(", ")}]`),g.length&&h.push(`invalid@[${g.join(", ")}]`),h.join(" ")||"(none)"})();console.log(`[tools] node ${s.id} requested (${n.length}): ${c}`);let d=!1,f=async()=>{if(d&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},d=!0,o.toolDefs;try{let a=await Kt(o.env),u={};for(let i of a)i&&i.id&&(u[i.id]=i);o.toolDefs=u}catch(a){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(a)}`}),o.toolDefs=o.toolDefs||{}}return d=!0,o.toolDefs},r=[];for(let a=0;a<n.length;a++){let u=n[a];if(!u||typeof u!="object"||typeof u.id!="string"||u.kind!=="builtin"&&u.kind!=="http"&&u.kind!=="mcp"&&u.kind!=="composio"&&u.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${a}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let i=u;if(i.kind!=="builtin"){let h=(await f())[i.id];if(!h){console.error(`[tools] \u2717 custom '${i.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${i.id}' not found for this tenant`});continue}if(i.kind==="composio"){try{let y=await Wt(h,o,e,t),x=Object.keys(y);for(let[C,N]of Object.entries(y))l[C]=It(C,N,i,o,t);console.log(`[tools] \u2713 composio '${i.id}' \u2192 ${x.length} tool(s)`)}catch(y){console.error(`[tools] \u2717 composio '${i.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${i.id}': ${String(y)}`})}continue}if(i.kind==="skill"){if(h.kind!=="skill"){console.error(`[tools] \u2717 skill '${i.id}': row is of kind '${h.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${i.id}' is not a skill`});continue}let y=h.name;if(l[y]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${y}' \u2014 builtin/other already registered, skipping skill '${i.id}'`});continue}try{l[y]=zt(h,o,e,t),r.push(h);let x=typeof h.execution=="string"?JSON.parse(h.execution):h.execution||{},C=Array.isArray(x.references)?x.references.map(N=>N==null?void 0:N.name):[];console.log(`[tools] \u2713 skill '${i.id}' \u2192 '${y}' (refs: ${C.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:y,refCount:C.length,refs:C}})}catch(x){console.error(`[tools] \u2717 skill '${i.id}': ${String(x)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${i.id}': ${String(x)}`})}continue}let w=h.name;if(l[w]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin already registered, skipping custom tool '${i.id}'`});continue}try{let y=Xt(h,o,e,t);l[w]=It(w,y,i,o,t),console.log(`[tools] \u2713 custom '${i.id}' \u2192 '${w}'`),console.log(`[tools] ${m(l[w])}`)}catch(y){console.error(`[tools] \u2717 custom '${i.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${i.id}': ${String(y)}`})}continue}if(!qt[i.id]){console.error(`[tools] \u2717 builtin '${i.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${i.id}' not found in registry`});continue}try{let g;try{g=await we(`../tools/${i.id}.ts`)}catch{g=await xe(`../tools/${i.id}.js`)}let h;if(g[i.id])h=g[i.id];else if(g.default)h=g.default;else if(g.create)h=g.create;else{let R=Object.values(g);R.length>0&&(h=R[0])}if(!h){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${i.id}'`});continue}let w,y,x={};if(i.params&&typeof i.params=="object"){if(typeof i.params.description=="string"?w=i.params.description:i.params.description!==void 0&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${i.id}' \u2014 must be a string`})),i.params.inputSchema!==void 0){let R=i.params.inputSchema;typeof R=="object"&&(typeof R.safeParse=="function"||R._def)?y=R:typeof R=="object"&&R!==null&&R.type==="object"&&R.properties?(y=Jt(R),y||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${i.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${i.id}' \u2014 must be a Zod schema or JSON Schema object`})}i.params.defaults!==void 0?typeof i.params.defaults=="object"&&i.params.defaults!==null&&!Array.isArray(i.params.defaults)?x=i.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${i.id}' \u2014 must be an object`}),x={}):i.params.source!==void 0||i.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${i.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),x={}):x={}}let C=h(o,e,x,t);w&&C&&typeof C=="object"&&(C.description=w),y&&C&&typeof C=="object"&&(C.inputSchema=y),l[i.id]=It(i.id,C,i,o,t);let N=[];w&&N.push("description"),y&&N.push("inputSchema"),Object.keys(x).length&&N.push(`defaults(${Object.keys(x).join(",")})`);let $=N.length?` [overrides: ${N.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${i.id}'${$}`),console.log(`[tools] ${m(C)}`)}catch(g){console.error(`[tools] \u2717 builtin '${i.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${i.id}': ${String(g)}`});continue}}if(r.length>0)if(l.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{l.readSkillRef=Yt(o,r,e,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${r.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:r.map(a=>a.name)}})}catch(a){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(a)}`)}return l}async function Ot(o,e,s,t,n,l,m){var k,D,A,F,j;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=!1;try{let T=(k=s.flowData)==null?void 0:k.state;if(T&&T.edges&&T.nodes){let U=T.edges.filter(M=>M.source===e.id);if(U.length>0){let M=T.nodes.find(q=>q.id===U[0].target);M&&M.type==="answerNode"&&(c=!0)}}}catch(T){console.error("Error determining next node for streaming:",T)}let d=K(e.data.template,e,s,t,{sessionEnv:o});(!d||!d.trim())&&(d="Answer straight forward to the user, dont offer any other option to continue");let f=d,r="";if((D=o.memoryConfig)!=null&&D.enabled){let T=await((A=o.getContextIndex)==null?void 0:A.call(o))??[];r=Qt(T),d+=r}let p=K(e.data.user_template||"",e,s,t,{sessionEnv:o}),a=T=>T&&Object.fromEntries(Object.keys(T).map(U=>[U,"[redacted]"])),u=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:a(o.secrets),userAuth:a(o.userAuth)}:o,i=K(e.data.template,e,s,void 0,{sessionEnv:u})||f;i+=r;let g=K(e.data.user_template||"",e,s,void 0,{sessionEnv:u});t==null||t({type:`info:llmNodeRunner:${e.id}`,content:i}),t==null||t({type:`info:llmNodeRunner:${e.id}`,content:g});let h=(F=e==null?void 0:e.data)==null?void 0:F.window_size,w=Number(h);(!Number.isInteger(w)||w<=0)&&(w=5);let y=oe(e,s),x=ee(e,s),N=(await((j=o.getMessages)==null?void 0:j.call(o))??[]).slice(-w),$=N.filter(T=>T&&typeof T.role=="string"&&typeof T.content=="string");$.length!==N.length&&console.warn(`Filtered ${N.length-$.length} invalid messages from history`);let R=_e($,p,y,x);await Oe(d,R,o.conn,t,e,c,n,s,l,o,m)}async function Oe(o,e,s,t,n,l,m,c,d,f,r){var a;let p=Date.now();if(!((a=f.env)!=null&&a.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(u,i)=>{var j,T,U,M,q,B,E;let g,h={},w,y="none",x=!1,C,N=!1,$=!1,R=0,k=0,D=(j=n==null?void 0:n.data)==null?void 0:j.sendReasoning,A=D!==!1;try{let L=(T=n==null?void 0:n.data)==null?void 0:T.model,W=Array.isArray(L)?L[0]:L||"gpt_5_nano",I=Ut(n==null?void 0:n.data),_=await at(W,f,I);if(!_)throw new Error(`Model '${W}' not found in registry`);g=_.modelHandle,h=_.effectiveParams||{},y=_.reasoning.kind;let O=Ht(_.reasoning,(U=n==null?void 0:n.data)==null?void 0:U.reasoningEffort);x=A&&jt(_.reasoning);let V=typeof((M=n==null?void 0:n.data)==null?void 0:M.reasoningMaxTokens)=="number"?n.data.reasoningMaxTokens:void 0;w=Vt(_.provider,{effort:O,exposeReasoning:x,maxTokens:V}),O&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:O})),console.log(`[reasoning] ${JSON.stringify({model:W,provider:_.provider,capability:_.reasoning,requestedEffort:((q=n==null?void 0:n.data)==null?void 0:q.reasoningEffort)??null,resolvedEffort:O??null,sendReasoning:A,exposeReasoning:x,providerOptions:w??null},null,2)}`);for(let H of _.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:H});t==null||t({type:"info:llmNodeRunner:model",content:W}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(B=n==null?void 0:n.data)!=null&&B.generationPreset?{preset:n.data.generationPreset}:{},...h,...y!=="none"?{reasoning:y,configuredSendReasoning:D,sendReasoning:A,exposeReasoning:x,...O?{effort:O}:{}}:{}}})}catch(L){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(L)}`}),L}let F=await Ie(f,c,n,t);if((E=f.memoryConfig)!=null&&E.enabled){let{recall:L}=await import("./recall-SD6FENAS.js");F.recall=L(f,c,void 0,t)}console.log(`[tools] node ${n.id} loaded ${Object.keys(F).length}: ${Object.keys(F).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:n.id,tools:Object.keys(F)}});try{let L=Ne({model:g,system:o,messages:e,stopWhen:(()=>{var H;let _=!!F.readSkillRef?10:5,O=Number(((H=n.data)==null?void 0:H.max_steps)??_),V=Number.isFinite(O)?Math.max(1,Math.min(30,O)):_;return Re(V)})(),...Lt(h),...w?{providerOptions:w}:{},tools:F,onFinish:async I=>{var At,Ft;let _=I.text||"",O=I.reasoningText??((At=I.reasoning)==null?void 0:At.text)??"";if(console.log(`[reasoning] done: deltas=${R} chars=${k} result.reasoningText=${O.length} finishReason=${I.finishReason??"n/a"} reasoningTokens=${((Ft=I.usage)==null?void 0:Ft.reasoningTokens)??"n/a"}`),A&&x&&!N&&O&&s){N=!0;try{P(s,b.SERVER_REASONING_STREAM,O)}catch(ge){console.warn("Failed to send finished reasoning over connection",ge)}}let V={id:Ce(),role:"assistant",type:"text",content:_,ts:Date.now()};l&&(f.setMessages?await f.setMessages(V):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),s&&A&&N&&!$&&($=!0,P(s,b.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),l&&s&&P(s,b.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),m==null||m((n==null?void 0:n.id)||"llm_result",_),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(I)});let H=Date.now()-p,ye=C?C-p:void 0;r==null||r({type:"llm_telemetry",payload:{nodeId:n.id,totalLatency:H,timeToFirstToken:ye,model:I.response.modelId,usage:I.usage}}),r==null||r({type:"llm_result",payload:{result:I}})},onStepFinish:async I=>{let _=(O,V=200)=>{let H=typeof O=="string"?O:JSON.stringify(O);return H?H.length>V?`${H.slice(0,V)}\u2026(+${H.length-V})`:H:""};if(I.toolCalls&&I.toolCalls.length>0){for(let O of I.toolCalls)console.log(`[tools] \u2192 ${O.toolName}(${_(O.args??O.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${n.id}`,content:JSON.stringify(I.toolCalls)})}if(I.toolResults&&I.toolResults.length>0){for(let O of I.toolResults)console.log(`[tools] \u2190 ${O.toolName} \u2192 ${_(O.result??O.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${n.id}`,content:JSON.stringify(I.toolResults)})}await Te(I,n,f,t)},experimental_onToolCallStart:I=>{var _;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(_=I==null?void 0:I.toolCall)==null?void 0:_.toolName,status:"start"}})},experimental_onToolCallFinish:I=>{var _;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(_=I==null?void 0:I.toolCall)==null?void 0:_.toolName,status:I!=null&&I.success?"success":"error"}})},onError:I=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),i(I)},onChunk:I=>{if(I.chunk.type==="reasoning-delta"){let O=I.chunk.text??I.chunk.delta??"";if(O&&(N=!0,R+=1,k+=O.length,R===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),A&&s&&O)try{P(s,b.SERVER_REASONING_STREAM,O)}catch(V){console.warn("Failed to send reasoning chunk over connection",V)}return}if(I.chunk.type==="text-delta"){if(C||(C=Date.now()),s&&A&&N&&!$){$=!0;try{P(s,b.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to send reasoning complete over connection",O)}}return}r==null||r({type:I.chunk.type,payload:{nodeId:n.id,chunk:I.chunk}});let _=`llm_chunk:${I.chunk.type}`;t==null||t({type:_,content:{...I}})}}),W=async()=>{let I="";for await(let _ of L.fullStream)if(_.type==="text-delta"){if(I+=_.text,l&&s)try{P(s,b.SERVER_TEXT_STREAM,_.text)}catch(O){console.warn("Failed to send chunk over connection",O)}}else if(_.type==="finish-step"&&_.finishReason==="tool-calls"){if(l&&s&&I.trim())try{P(s,b.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to flush text segment over connection",O)}I=""}};await Promise.all([L,W()]),u(),t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"success"}})}catch(L){t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"error",error:String(L)}}),i(L)}})}function _e(o,e,s,t){let n=!!(s&&s.length>0),l=!!t,m=n||l,d=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,f=r=>{let p=[],a="";if(l&&(a+=`[Attached files]
|
|
14
|
+
`:"")+a)}}return s}function se(o,e){var t,n,l,p,c,d;let s=[];if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let u of o.data.varMapping){let r=u.from;if(!r)continue;let f=!1;if(r==="images")f=!0;else{let a=r.indexOf(".");if(a!==-1){let m=r.substring(0,a),i=r.substring(a+1).split(".")[0],g=(p=(l=(n=e.flowData)==null?void 0:n.state)==null?void 0:l.nodes)==null?void 0:p.find(h=>h.id===m);if(g){let w=st(g).find(y=>y.name===i);(w==null?void 0:w.type)==="image"&&(f=!0)}}}if(f){let a=nt(r,{context:e.context||{},results:e.results||{},nodes:((d=(c=e.flowData)==null?void 0:c.state)==null?void 0:d.nodes)||[]});Array.isArray(a)&&s.push(...a)}}return s}var xe=v({"../tools/composioTool.ts":()=>import("./composioTool-EXCSM6F4.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-TT7DIP6C.js"),"../tools/httpTool.ts":()=>import("./httpTool-EU63HPF5.js"),"../tools/recall.ts":()=>import("./recall-SD6FENAS.js"),"../tools/skillTool.test.ts":()=>import("./skillTool.test-6UDHQARG.js"),"../tools/skillTool.ts":()=>import("./skillTool-Y5GZ4ZAR.js"),"../tools/tempTool.ts":()=>import("./tempTool-6Q6C4HEJ.js"),"../tools/twitter.ts":()=>import("./twitter-QNCTAE4E.js"),"../tools/vectorize.ts":()=>import("./vectorize-SQROWLSU.js")});var Re=v({});function Ot(o,e,s,t,n){var p;if(!((p=t.memoryConfig)!=null&&p.enabled)||!t.memoryConfig.toolCache||!s.cacheable||!e||typeof e.execute!="function")return e;let l=e.execute.bind(e);return e.execute=async(c,...d)=>{var a;if(!t.getContextIndex)return l(c,...d);let u=await xt(c),f=(await t.getContextIndex()).find(m=>{if(m.domain!=="tool")return!1;let i=Rt(m.meta);return i.toolName===o&&i.paramsHash===u});if(f){let m=await((a=t.getContext)==null?void 0:a.call(t,f.ref));if((m==null?void 0:m.data)!=null&&Rt(m.meta).truncated!==!0){n==null||n({type:"info:memory:cacheHit",content:{ref:m.ref,toolName:o}});try{return JSON.parse(m.data)}catch{return m.data}}}return l(c,...d)},e}async function Ie(o,e,s,t){var r,f;if(!((r=s.memoryConfig)!=null&&r.enabled)||!s.setContext||s.cycle==null)return;let n=o.toolCalls??[],l=o.toolResults??[];if(!n.length||!l.length)return;let p=new Map;for(let a of l)a!=null&&a.toolCallId&&p.set(a.toolCallId,a);let c=Array.isArray((f=e==null?void 0:e.data)==null?void 0:f.tools)?e.data.tools:[],d=new Map;for(let a of c)a&&typeof a.id=="string"&&d.set(a.id,a);let u=new Map;for(let a of Object.values(s.toolDefs??{}))a&&a.name&&u.set(a.name,a);for(let a of n){let m=a.toolCallId,i=a.toolName,g=p.get(m);if(!i||!g||i==="readSkillRef")continue;let h=a.args??a.input,w=g.result??g.output,y=!1,x="",C="tool",R="",$=u.get(i);$&&$.kind==="skill"&&(y=!0,x=`skill:${i}`,C="skill",R=`Skill instructions for ${i}`),x||(x=await Bt(i,h),R=Gt(h,w));let _=d.get(i)??c.find(k=>k.id===i),I=await xt(h),A=typeof w=="string"?w:JSON.stringify(w??null);await s.setContext({ref:x,domain:C,description:R,data:A,cycle:s.cycle,meta:JSON.stringify({toolName:i,paramsHash:I,cacheable:(_==null?void 0:_.cacheable)===!0})}),t==null||t({type:"info:memory:updated",content:{ref:x}})}}async function Oe(o,e,s,t){var f;let n=Array.isArray((f=s==null?void 0:s.data)==null?void 0:f.tools)?s.data.tools:[];if(n.length===0)return{};let l={},p=a=>{var x,C;let m=typeof(a==null?void 0:a.description)=="string"?a.description:"",i=a==null?void 0:a.inputSchema,g;try{let R=(i==null?void 0:i.shape)??(typeof((x=i==null?void 0:i._def)==null?void 0:x.shape)=="function"?i._def.shape():(C=i==null?void 0:i._def)==null?void 0:C.shape);R&&typeof R=="object"&&(g=R)}catch{}let h=g?Object.keys(g):[],w=m?`description="${m.length>120?m.slice(0,120)+"\u2026":m}"`:"description=(none)",y=h.length?`inputSchema={${h.join(", ")}}`:"inputSchema=(none)";return`${w} ${y}`},c=(()=>{let a=[],m=[],i=[],g=[];for(let w=0;w<n.length;w++){let y=n[w];!y||typeof y!="object"||typeof y.id!="string"?g.push(w):y.kind==="builtin"?a.push(y.id):y.kind==="skill"?i.push(y.id):y.kind==="http"||y.kind==="mcp"||y.kind==="composio"?m.push(y.id):g.push(w)}let h=[];return a.length&&h.push(`builtin[${a.join(", ")}]`),m.length&&h.push(`custom[${m.join(", ")}]`),i.length&&h.push(`skill[${i.join(", ")}]`),g.length&&h.push(`invalid@[${g.join(", ")}]`),h.join(" ")||"(none)"})();console.log(`[tools] node ${s.id} requested (${n.length}): ${c}`);let d=!1,u=async()=>{if(d&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},d=!0,o.toolDefs;try{let a=await Xt(o.env),m={};for(let i of a)i&&i.id&&(m[i.id]=i);o.toolDefs=m}catch(a){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(a)}`}),o.toolDefs=o.toolDefs||{}}return d=!0,o.toolDefs},r=[];for(let a=0;a<n.length;a++){let m=n[a];if(!m||typeof m!="object"||typeof m.id!="string"||m.kind!=="builtin"&&m.kind!=="http"&&m.kind!=="mcp"&&m.kind!=="composio"&&m.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${a}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let i=m;if(i.kind!=="builtin"){let h=(await u())[i.id];if(!h){console.error(`[tools] \u2717 custom '${i.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${i.id}' not found for this tenant`});continue}if(i.kind==="composio"){try{let y=await zt(h,o,e,t),x=Object.keys(y);for(let[C,R]of Object.entries(y))l[C]=Ot(C,R,i,o,t);console.log(`[tools] \u2713 composio '${i.id}' \u2192 ${x.length} tool(s)`)}catch(y){console.error(`[tools] \u2717 composio '${i.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${i.id}': ${String(y)}`})}continue}if(i.kind==="skill"){if(h.kind!=="skill"){console.error(`[tools] \u2717 skill '${i.id}': row is of kind '${h.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${i.id}' is not a skill`});continue}let y=h.name;if(l[y]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${y}' \u2014 builtin/other already registered, skipping skill '${i.id}'`});continue}try{l[y]=Yt(h,o,e,t),r.push(h);let x=typeof h.execution=="string"?JSON.parse(h.execution):h.execution||{},C=Array.isArray(x.references)?x.references.map(R=>R==null?void 0:R.name):[];console.log(`[tools] \u2713 skill '${i.id}' \u2192 '${y}' (refs: ${C.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:y,refCount:C.length,refs:C}})}catch(x){console.error(`[tools] \u2717 skill '${i.id}': ${String(x)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${i.id}': ${String(x)}`})}continue}let w=h.name;if(l[w]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin already registered, skipping custom tool '${i.id}'`});continue}try{let y=Wt(h,o,e,t);l[w]=Ot(w,y,i,o,t),console.log(`[tools] \u2713 custom '${i.id}' \u2192 '${w}'`),console.log(`[tools] ${p(l[w])}`)}catch(y){console.error(`[tools] \u2717 custom '${i.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${i.id}': ${String(y)}`})}continue}if(!Jt[i.id]){console.error(`[tools] \u2717 builtin '${i.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${i.id}' not found in registry`});continue}try{let g;try{g=await xe(`../tools/${i.id}.ts`)}catch{g=await Re(`../tools/${i.id}.js`)}let h;if(g[i.id])h=g[i.id];else if(g.default)h=g.default;else if(g.create)h=g.create;else{let _=Object.values(g);_.length>0&&(h=_[0])}if(!h){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${i.id}'`});continue}let w,y,x={};if(i.params&&typeof i.params=="object"){if(typeof i.params.description=="string"?w=i.params.description:i.params.description!==void 0&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${i.id}' \u2014 must be a string`})),i.params.inputSchema!==void 0){let _=i.params.inputSchema;typeof _=="object"&&(typeof _.safeParse=="function"||_._def)?y=_:typeof _=="object"&&_!==null&&_.type==="object"&&_.properties?(y=Kt(_),y||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${i.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${i.id}' \u2014 must be a Zod schema or JSON Schema object`})}i.params.defaults!==void 0?typeof i.params.defaults=="object"&&i.params.defaults!==null&&!Array.isArray(i.params.defaults)?x=i.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${i.id}' \u2014 must be an object`}),x={}):i.params.source!==void 0||i.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${i.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),x={}):x={}}let C=h(o,e,x,t);w&&C&&typeof C=="object"&&(C.description=w),y&&C&&typeof C=="object"&&(C.inputSchema=y),l[i.id]=Ot(i.id,C,i,o,t);let R=[];w&&R.push("description"),y&&R.push("inputSchema"),Object.keys(x).length&&R.push(`defaults(${Object.keys(x).join(",")})`);let $=R.length?` [overrides: ${R.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${i.id}'${$}`),console.log(`[tools] ${p(C)}`)}catch(g){console.error(`[tools] \u2717 builtin '${i.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${i.id}': ${String(g)}`});continue}}if(r.length>0)if(l.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{l.readSkillRef=Et(o,r,e,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${r.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:r.map(a=>a.name)}})}catch(a){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(a)}`)}return l}async function _t(o,e,s,t,n,l,p){var I,A,k,M,j;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=!1;try{let N=(I=s.flowData)==null?void 0:I.state;if(N&&N.edges&&N.nodes){let b=N.edges.filter(D=>D.source===e.id);if(b.length>0){let D=N.nodes.find(q=>q.id===b[0].target);D&&D.type==="answerNode"&&(c=!0)}}}catch(N){console.error("Error determining next node for streaming:",N)}let d=K(e.data.template,e,s,t,{sessionEnv:o});(!d||!d.trim())&&(d="Answer straight forward to the user, dont offer any other option to continue");let u=d,r="";if((A=o.memoryConfig)!=null&&A.enabled){let N=await((k=o.getContextIndex)==null?void 0:k.call(o))??[];r=Zt(N),d+=r}let f=K(e.data.user_template||"",e,s,t,{sessionEnv:o}),a=N=>N&&Object.fromEntries(Object.keys(N).map(b=>[b,"[redacted]"])),m=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:a(o.secrets),userAuth:a(o.userAuth)}:o,i=K(e.data.template,e,s,void 0,{sessionEnv:m})||u;i+=r;let g=K(e.data.user_template||"",e,s,void 0,{sessionEnv:m});t==null||t({type:`info:llmNodeRunner:${e.id}`,content:i}),t==null||t({type:`info:llmNodeRunner:${e.id}`,content:g});let h=(M=e==null?void 0:e.data)==null?void 0:M.window_size,w=Number(h);(!Number.isInteger(w)||w<=0)&&(w=5);let y=se(e,s),x=oe(e,s),R=(await((j=o.getMessages)==null?void 0:j.call(o))??[]).slice(-w),$=R.filter(N=>N&&typeof N.role=="string"&&typeof N.content=="string");$.length!==R.length&&console.warn(`Filtered ${R.length-$.length} invalid messages from history`);let _=Fe($,f,y,x);await _e(d,_,o.conn,t,e,c,n,s,l,o,p)}async function _e(o,e,s,t,n,l,p,c,d,u,r){var a;let f=Date.now();if(!((a=u.env)!=null&&a.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(m,i)=>{var j,N,b,D,q,B,Q;let g,h={},w,y="none",x=!1,C,R=!1,$=!1,_=0,I=0,A=(j=n==null?void 0:n.data)==null?void 0:j.sendReasoning,k=A!==!1;try{let L=(N=n==null?void 0:n.data)==null?void 0:N.model,W=Array.isArray(L)?L[0]:L||"gpt_5_nano",T=Lt(n==null?void 0:n.data),F=await at(W,u,T);if(!F)throw new Error(`Model '${W}' not found in registry`);g=F.modelHandle,h=F.effectiveParams||{},y=F.reasoning.kind;let O=Vt(F.reasoning,(b=n==null?void 0:n.data)==null?void 0:b.reasoningEffort);x=k&&Ht(F.reasoning);let V=typeof((D=n==null?void 0:n.data)==null?void 0:D.reasoningMaxTokens)=="number"?n.data.reasoningMaxTokens:void 0;w=qt(F.provider,{effort:O,exposeReasoning:x,maxTokens:V}),O&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:O})),console.log(`[reasoning] ${JSON.stringify({model:W,provider:F.provider,capability:F.reasoning,requestedEffort:((q=n==null?void 0:n.data)==null?void 0:q.reasoningEffort)??null,resolvedEffort:O??null,sendReasoning:k,exposeReasoning:x,providerOptions:w??null},null,2)}`);for(let H of F.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:H});t==null||t({type:"info:llmNodeRunner:model",content:W}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(B=n==null?void 0:n.data)!=null&&B.generationPreset?{preset:n.data.generationPreset}:{},...h,...y!=="none"?{reasoning:y,configuredSendReasoning:A,sendReasoning:k,exposeReasoning:x,...O?{effort:O}:{}}:{}}})}catch(L){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(L)}`}),L}let M=await Oe(u,c,n,t);if((Q=u.memoryConfig)!=null&&Q.enabled){let{recall:L}=await import("./recall-SD6FENAS.js");M.recall=L(u,c,void 0,t)}console.log(`[tools] node ${n.id} loaded ${Object.keys(M).length}: ${Object.keys(M).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:n.id,tools:Object.keys(M)}});try{let L=Ce({model:g,system:o,messages:e,stopWhen:(()=>{var H;let F=!!M.readSkillRef?10:5,O=Number(((H=n.data)==null?void 0:H.max_steps)??F),V=Number.isFinite(O)?Math.max(1,Math.min(30,O)):F;return Ne(V)})(),...jt(h),...w?{providerOptions:w}:{},tools:M,onFinish:async T=>{var At,Mt;let F=T.text||"",O=T.reasoningText??((At=T.reasoning)==null?void 0:At.text)??"";if(console.log(`[reasoning] done: deltas=${_} chars=${I} result.reasoningText=${O.length} finishReason=${T.finishReason??"n/a"} reasoningTokens=${((Mt=T.usage)==null?void 0:Mt.reasoningTokens)??"n/a"}`),k&&x&&!R&&O&&s){R=!0;try{U(s,P.SERVER_REASONING_STREAM,O)}catch(he){console.warn("Failed to send finished reasoning over connection",he)}}let V={id:Te(),role:"assistant",type:"text",content:F,ts:Date.now()};l&&(u.setMessages?await u.setMessages(V):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),s&&k&&R&&!$&&($=!0,U(s,P.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),l&&s&&U(s,P.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),p==null||p((n==null?void 0:n.id)||"llm_result",F),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(T)});let H=Date.now()-f,ge=C?C-f:void 0;r==null||r({type:"llm_telemetry",payload:{nodeId:n.id,totalLatency:H,timeToFirstToken:ge,model:T.response.modelId,usage:T.usage}}),r==null||r({type:"llm_result",payload:{result:T}})},onStepFinish:async T=>{let F=(O,V=200)=>{let H=typeof O=="string"?O:JSON.stringify(O);return H?H.length>V?`${H.slice(0,V)}\u2026(+${H.length-V})`:H:""};if(T.toolCalls&&T.toolCalls.length>0){for(let O of T.toolCalls)console.log(`[tools] \u2192 ${O.toolName}(${F(O.args??O.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${n.id}`,content:JSON.stringify(T.toolCalls)})}if(T.toolResults&&T.toolResults.length>0){for(let O of T.toolResults)console.log(`[tools] \u2190 ${O.toolName} \u2192 ${F(O.result??O.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${n.id}`,content:JSON.stringify(T.toolResults)})}await Ie(T,n,u,t)},experimental_onToolCallStart:T=>{var F;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(F=T==null?void 0:T.toolCall)==null?void 0:F.toolName,status:"start"}})},experimental_onToolCallFinish:T=>{var F;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(F=T==null?void 0:T.toolCall)==null?void 0:F.toolName,status:T!=null&&T.success?"success":"error"}})},onError:T=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),i(T)},onChunk:T=>{if(T.chunk.type==="reasoning-delta"){let O=T.chunk.text??T.chunk.delta??"";if(O&&(R=!0,_+=1,I+=O.length,_===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),k&&s&&O)try{U(s,P.SERVER_REASONING_STREAM,O)}catch(V){console.warn("Failed to send reasoning chunk over connection",V)}return}if(T.chunk.type==="text-delta"){if(C||(C=Date.now()),s&&k&&R&&!$){$=!0;try{U(s,P.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to send reasoning complete over connection",O)}}return}r==null||r({type:T.chunk.type,payload:{nodeId:n.id,chunk:T.chunk}});let F=`llm_chunk:${T.chunk.type}`;t==null||t({type:F,content:{...T}})}}),W=async()=>{let T="";for await(let F of L.fullStream)if(F.type==="text-delta"){if(T+=F.text,l&&s)try{U(s,P.SERVER_TEXT_STREAM,F.text)}catch(O){console.warn("Failed to send chunk over connection",O)}}else if(F.type==="finish-step"&&F.finishReason==="tool-calls"){if(l&&s&&T.trim())try{U(s,P.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to flush text segment over connection",O)}T=""}};await Promise.all([L,W()]),m(),t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"success"}})}catch(L){t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"error",error:String(L)}}),i(L)}})}function Fe(o,e,s,t){let n=!!(s&&s.length>0),l=!!t,p=n||l,d=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,u=r=>{let f=[],a="";if(l&&(a+=`[Attached files]
|
|
15
15
|
${t}
|
|
16
16
|
[End of attached files]
|
|
17
17
|
|
|
18
|
-
`),r&&(a+=r),a&&
|
|
18
|
+
`),r&&(a+=r),a&&f.push({type:"text",text:a}),n)for(let m of s)f.push({type:"image",image:m.data,mimeType:m.mimeType});return f};return e&&d&&d.content===e?[...o.slice(0,-1).map(f=>({role:f.role,content:f.content})),{role:"user",content:u(e)}]:e?[...o.map(r=>({role:r.role,content:r.content})),{role:"user",content:u(e)}]:p&&d?[...o.slice(0,-1).map(f=>({role:f.role,content:f.content})),{role:"user",content:u(d.content)}]:o.map(r=>({role:r.role,content:r.content}))}async function Ft(o,e,s,t,n,l,p){var u,r,f,a;console.log(`**** MEMO Node id: ${e.id} ****`),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c="",d=Date.now();try{if(t==null||t({type:"info:memoNodeRunner",content:"Starting memo node execution"}),((u=s==null?void 0:s.context)==null?void 0:u[e.data.query_key])===void 0){t==null||t({type:"error:memoNodeRunner",content:`Query key ${e.data.query_key} not found in context`}),n==null||n(e.id,c);return}if(!o.env||!o.ctx){t==null||t({type:"error:memoNodeRunner",content:"Missing env or ctx"}),n==null||n(e.id,c);return}if(!e.data.rag_id){t==null||t({type:"error:memoNodeRunner",content:"Missing rag_id"}),n==null||n(e.id,c);return}let m=((r=s==null?void 0:s.context)==null?void 0:r[e.data.query_key])||"";t==null||t({type:"info:memoNodeRunner",content:`Query text: ${m}`}),t==null||t({type:"info:memoNodeRunner",content:"Generating embedding for query"});let i=await Dt(o,m,!0);t==null||t({type:"info:memoNodeRunner",content:`Embedding generated successfully, length: ${i.data[0].length}`});let g=Array.isArray(e.data.rag_id)?e.data.rag_id:[e.data.rag_id],h=[];for(let C of g){t==null||t({type:"info:memoNodeRunner",content:`Executing RAG query with namespace: ${C}`});let R=await o.env[`VDB_${(f=s.flowData)==null?void 0:f.tenant}_1024`].query(i.data[0],{namespace:C,topK:e.data.topk,returnMetadata:"all"});t==null||t({type:"info:memoNodeRunner",content:`RAG query completed for namespace ${C}, matches: ${((a=R.matches)==null?void 0:a.length)||0}`}),Array.isArray(R.matches)&&h.push(...R.matches)}let w=Date.now()-d;c=h.map(C=>{var R;return(R=C.metadata)==null?void 0:R.value}).filter(C=>typeof C=="string").join(`
|
|
19
19
|
|
|
20
|
-
`),
|
|
20
|
+
`),p==null||p({type:"memo_search",payload:{nodeId:e.id,searchLatencyMs:w,retrievedContext:c}}),t==null||t({type:"info:memoNodeRunner",content:`Context retrieval complete, length: ${c.length}, preview: ${c.substring(0,200)}...`}),t==null||t({type:"info:memoNodeRunner",content:"Memo node execution completed successfully"})}catch(m){console.error("Error processing MemoNode:",m),t==null||t({type:"error:memoNodeRunner",content:`Memo node execution failed: ${m}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(m)}})}finally{n==null||n(e.id,c),t==null||t({type:"info:memoNodeRunner",content:`onResult called with context length: ${c.length}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}}async function $t(o,e,s,t,n,l,p){var u,r,f,a,m,i;console.log(`**** START Node ${e.id} ****`),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}}),t==null||t({type:"info:flow",content:s}),p==null||p({type:"start_node",payload:{userMessage:(u=s==null?void 0:s.context)==null?void 0:u.user_input}});let c=((r=e.data)==null?void 0:r.allow_images)!==!1,d=((f=e.data)==null?void 0:f.allow_documents)!==!1;!c&&(s!=null&&s.context)&&(s.context.user_images=[],l==null||l({...s})),!d&&(s!=null&&s.context)&&(s.context.files="",l==null||l({...s})),n==null||n(e.id,{user_input:(a=s==null?void 0:s.context)==null?void 0:a.user_input,images:c?(m=s==null?void 0:s.context)==null?void 0:m.user_images:[],files:d?(i=s==null?void 0:s.context)==null?void 0:i.files:""}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}function lt(o,e,s){let t=e;async function n(d){let u=d;for(t.executedNodes=t.executedNodes||[],t.context=t.context||{},t.results=t.results||{};u&&u.id;)await l(u),u=Ae(u,t.flowData,t)}async function l(d){var m;let u=c[d.type];if(!u){(m=s==null?void 0:s.onError)==null||m.call(s,`Unknown node type: ${d.type}`);return}let r=i=>{var g;return(g=s==null?void 0:s.onServerEvent)==null?void 0:g.call(s,{...i,ts:Date.now()})},f=i=>{var g,h;if((g=s==null?void 0:s.onTelemetry)==null||g.call(s,i),i.type==="llm_telemetry"||i.type==="class_telemetry"){let w=(h=i.payload)==null?void 0:h.usage;w&&(t.tokenUsage=t.tokenUsage||{promptTokens:0,completionTokens:0,totalTokens:0},t.tokenUsage.promptTokens+=w.promptTokens||0,t.tokenUsage.completionTokens+=w.completionTokens||0,t.tokenUsage.totalTokens+=w.totalTokens||0)}};return await u(o,d,t,r,(i,g)=>{t.results[i]=g},s==null?void 0:s.onChangeState,f)}let p=async d=>{var x,C,R;let u=Date.now(),r=typeof d=="string"?et(d):d,f=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.images)||[],m=(r==null?void 0:r.documents)||[],i=await vt(m,o.env),g=i.length>0?i.map($=>`--- file: ${$.name} ---
|
|
21
21
|
${$.text}`).join(`
|
|
22
22
|
|
|
23
|
-
`):"";t.context={user_input:
|
|
23
|
+
`):"";t.context={user_input:f,user_images:a,files:g},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},(x=s==null?void 0:s.onServerEvent)==null||x.call(s,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:h,error:w}=$e(t.flowData);if(!h){(C=s==null?void 0:s.onError)==null||C.call(s,w||"Flow Format Error");return}await n(h);let y=Date.now()-u;(R=s==null?void 0:s.onServerEvent)==null||R.call(s,{type:"agent:telemetry",content:{durationMs:y,tokenUsage:t.tokenUsage},timestamp:Date.now()})},c={startNode:$t,classifierNode:It,llmNode:_t,memoNode:Ft,answerNode:Nt,apiNode:Tt};return p}function $e(o){var r;let e=(o==null?void 0:o.state)??o;if(!e||!e.nodes||!e.edges||e.edges.length===0)return{error:"Flow is missing state, nodes, or edges."};let s=e.nodes.filter(f=>f.type==="startNode");if(s.length!==1)return{error:`Flow must include exactly one START node, found ${s.length}.`};let t=s[0],n=e.nodes.filter(f=>f.type==="answerNode");if(n.length===0)return{error:"Flow must include at least one ANSWER node."};let l=new Map;for(let f of e.edges)l.has(f.source)||l.set(f.source,[]),l.get(f.source).push(f.target);let p=new Map;for(let f of e.edges)p.has(f.target)||p.set(f.target,[]),p.get(f.target).push(f.source);let c=ne(t.id,l),d=new Set;for(let f of n){let a=ne(f.id,p);for(let m of a)d.add(m)}let u=[];for(let f of c)if(!d.has(f)){let a=e.nodes.find(m=>m.id===f);if(a){let m=((r=a.data)==null?void 0:r.label)||"";u.push(`${f}(${m},${a.type})`)}}return u.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${u.join(", ")}`}:{startNode:t}}function ne(o,e){let s=new Set,t=[o];for(s.add(o);t.length>0;){let n=t.shift(),l=e.get(n)||[];for(let p of l)s.has(p)||(s.add(p),t.push(p))}return s}function ke(o,e){var s;return((s=o.state)==null?void 0:s.nodes.find(t=>t.id===e))||null}function Ae(o,e,s){var c;let t=e==null?void 0:e.state;if(!t)return null;let n=t.edges.filter(d=>d.source===o.id);if(n.length===0)return null;let l=n[0].target;if(o.type==="classifierNode"&&((c=s==null?void 0:s.context)!=null&&c.classified_id)){let d=s.context.classified_id,u=n.find(r=>r.sourceHandle===`source-${d}`);u?l=u.target:console.log(`No matching edge, falling back to first: ${l}`)}return ke(e,l)}async function Me(o){o.sql`CREATE TABLE IF NOT EXISTS messages (id TEXT PRIMARY KEY, role TEXT NOT NULL, type TEXT NOT NULL, content TEXT NOT NULL, ts INTEGER NOT NULL)`}async function ct(o,e){o.sql`INSERT INTO messages (id, role, type, content, ts) VALUES (${e.id}, ${e.role}, ${e.type}, ${e.content}, ${e.ts})`}async function X(o){return o.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function dt(o){o.sql`DELETE FROM messages`}async function De(o){o.sql`CREATE TABLE IF NOT EXISTS context (
|
|
24
24
|
ref TEXT PRIMARY KEY,
|
|
25
25
|
domain TEXT NOT NULL,
|
|
26
26
|
description TEXT NOT NULL,
|
|
@@ -28,7 +28,7 @@ ${$.text}`).join(`
|
|
|
28
28
|
cycle INTEGER NOT NULL,
|
|
29
29
|
meta TEXT,
|
|
30
30
|
ts INTEGER NOT NULL
|
|
31
|
-
)`}async function
|
|
31
|
+
)`}async function ie(o,e){let s=e.data??null,t=s!=null?Qt(s):{data:null,truncated:!1},n=t.truncated?St(e.meta,{truncated:!0}):e.meta??null,l=e.ts??Date.now();o.sql`INSERT INTO context (ref, domain, description, data, cycle, meta, ts)
|
|
32
32
|
VALUES (${e.ref}, ${e.domain}, ${e.description}, ${t.data}, ${e.cycle}, ${n}, ${l})
|
|
33
33
|
ON CONFLICT(ref) DO UPDATE SET
|
|
34
34
|
domain = excluded.domain,
|
|
@@ -36,6 +36,6 @@ ${$.text}`).join(`
|
|
|
36
36
|
data = excluded.data,
|
|
37
37
|
cycle = excluded.cycle,
|
|
38
38
|
meta = excluded.meta,
|
|
39
|
-
ts = excluded.ts`}async function pt(o){return o.sql`SELECT ref, domain, description, cycle, meta, ts FROM context ORDER BY ts ASC`}async function ft(o,e){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${e} LIMIT 1`[0]??null}async function ie(o,e){var t;return((t=o.sql`SELECT data FROM context WHERE ref = ${e} LIMIT 1`[0])==null?void 0:t.data)??null}async function ae(o,e){let s=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${e} LIMIT 1`;if(s[0])return s[0];let t=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref LIKE ${e+"%"} LIMIT 2`;return t.length===1?t[0]:null}async function re(o,e){o.sql`DELETE FROM context WHERE domain = 'tool' AND cycle <= ${e}`}async function le(o){var s;return((s=o.sql`SELECT COALESCE(MAX(cycle), 0) AS maxCycle FROM context`[0])==null?void 0:s.maxCycle)??0}async function ut(o){o.sql`DELETE FROM context`}async function ce(o){await Fe(o),await Me(o)}var kt=Object.freeze({});async function Q(o,e){if(!e)return kt;if(o.HX_ORA_URL&&o.HX_API_KEY)try{let n=await fetch(`${o.HX_ORA_URL}/internal/secrets`,{headers:{Authorization:o.HX_API_KEY}});if(n.ok){let l=await n.json();if(l.secrets)return Object.freeze(l.secrets)}else console.warn(`[secrets] API failed with status ${n.status}, falling back to KV`)}catch(n){console.error("[secrets] API request failed, falling back to KV",n)}let s=o.ORA_SECRETS;if(!s)return kt;let t=`${e}:`;try{let n=await s.list({prefix:t,limit:1e3});n.list_complete===!1&&console.warn(`[secrets] tenant=${e} exceeded list page; truncating to first 1000 keys`);let l=await Promise.all(n.keys.map(async c=>{let d=await s.get(c.name);return d!==null?[c.name.slice(t.length),d]:null})),m={};for(let c of l){if(!c)continue;let[d,f]=c;d&&(m[d]=f)}return Object.freeze(m)}catch(n){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,err:n}),kt}}import{nanoid as As}from"nanoid";function Z(o){var n,l;let e=(n=o==null?void 0:o.flowData)==null?void 0:n.state,t=((e==null?void 0:e.nodes)??((l=o==null?void 0:o.flowData)==null?void 0:l.nodes)??[]).find(m=>m.type==="startNode");return t==null?void 0:t.data}async function mt(o,e){return typeof e.cycle=="number"&&Number.isFinite(e.cycle)?e.cycle+1:await le(o)+1}function yt(o,e,s,t,n){let l=G(Z(s));return{...e,memoryConfig:l,cycle:t,setContext:async c=>{await ne(o,c),await(n==null?void 0:n(c.ref))},getContextIndex:async()=>pt(o),getContextData:async c=>ie(o,c),getContext:async c=>ft(o,c),resolveContext:async c=>ae(o,c),pruneContext:async c=>re(o,c)}}function gt(o,e){return!o||!o.HX_ORA_URL||!o.HX_API_KEY?Promise.resolve():fetch(`${o.HX_ORA_URL}/internal/sessions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:o.HX_API_KEY},body:JSON.stringify(e)}).catch(s=>{console.error("[sessionIndex] failed to index session",s)})}var ht=async(o,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),`${JSON.stringify(o)}`};import{nanoid as be}from"nanoid";async function De(o,e){var l,m;let s=o.id||o.name||"",[t,n]=s.split("::");if(!t||!n)return null;try{let d=(l=(await z(t,e)).metadata)==null?void 0:l.tenant,f=await tt(t,e),r=(m=o.state)==null?void 0:m.user,p={flowData:{...f,tenant:d,flowId:t,chatId:n},executedNodes:[],context:r?{user:r}:{}};return o.setState({...o.state,engineState:p}),p}catch(c){return console.error("Failed to initialize engine state:",c),null}}async function de(o,e,s,t){var n,l,m;try{let c=await e.json(),d=c.message;if(!d||typeof d!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let f=typeof c.userId=="string"?ot(c.userId):null;f&&!((n=o.state.user)!=null&&n.email)&&o.setState({...o.state,injectedUserId:f});let r=()=>{var T;return((T=o.state.user)==null?void 0:T.email)??f??o.state.injectedUserId??void 0},p=Date.now(),a=[],u=async()=>await X(o),i=async T=>{await ct(o,T)},g={id:be(),role:"user",type:"text",content:d,ts:Date.now()};await i(g);let h={onChangeState:T=>{o.setState({...o.state,engineState:T})},onServerEvent:async T=>{a.push(T)},onTelemetry:async T=>{var U,M,q,B,E,L;await ht({...T,userId:r(),tenant:((M=(U=o.state.engineState)==null?void 0:U.flowData)==null?void 0:M.tenant)||"",flowId:((B=(q=o.state.engineState)==null?void 0:q.flowData)==null?void 0:B.flowId)||"",sessionId:((L=(E=o.state.engineState)==null?void 0:E.flowData)==null?void 0:L.chatId)||""},s)},onError:T=>{o.setState({...o.state,error:T})}},w=async T=>{if(o.state.modelsCache&&o.state.modelsCache[T])return o.state.modelsCache[T];try{let{fetchOraModel:U}=await import("./oraApi-3JWDQQUE.js"),M=await U(T,s);return o.setState({...o.state,modelsCache:{...o.state.modelsCache||{},[T]:M}}),M}catch(U){throw console.error(`Error fetching model ${T}:`,U),U}},y=o.state.engineState;if(!y&&(y=await De(o,s),!y))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let x=(l=y==null?void 0:y.flowData)==null?void 0:l.tenant,C=await Q(s,x),N=G(Z(y)),$=typeof y.cycle=="number"?y.cycle:0;N.enabled&&($=await mt(o,y),y={...y,cycle:$},o.setState({...o.state,engineState:y})),o.skillRefCache||(o.skillRefCache=new Map);let R=yt(o,{env:s,ctx:t,conn:void 0,getMessages:u,setMessages:i,getOraModel:w,secrets:C,skillRefCache:o.skillRefCache},y,$);await lt(R,y,h)(d);let{tenant:k,flowId:D,chatId:A}=y.flowData??{};k&&D&&A&&t.waitUntil(gt(s,{id:`${D}::${A}`,tenant:k,flowId:D,sessionId:A,userId:r(),title:d.slice(0,120),turnTs:p,events:a})),(m=R.memoryConfig)!=null&&m.enabled&&R.memoryConfig.mode==="summarize"&&t&&t.waitUntil(rt(o,R,$)),o.setState({...o.state,lastUpdated:new Date});let j=(await u()).reverse().find(T=>T.role==="assistant");return new Response(JSON.stringify({answer:(j==null?void 0:j.content)||""}),{headers:{"content-type":"application/json"}})}catch(c){return new Response(JSON.stringify({error:c.message}),{status:500,headers:{"content-type":"application/json"}})}}async function pe(o){try{return await dt(o),await ut(o),o.skillRefCache&&o.skillRefCache.clear(),o.setState({...o.state,error:"",engineState:void 0,lastUpdated:new Date}),new Response(JSON.stringify({success:!0,messages:[]}),{headers:{"content-type":"application/json"}})}catch(e){return new Response(JSON.stringify({error:e.message}),{status:500,headers:{"content-type":"application/json"}})}}var fe=class extends Pe{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{}};resolveSessionUserId(){var e;return((e=this.state.user)==null?void 0:e.email)??this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async onRequest(e){let s=new URL(e.url);if(s.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(s.pathname.endsWith("/history")){let t=await X(this);return new Response(JSON.stringify(t),{headers:{"content-type":"application/json"}})}if(s.pathname.endsWith("/context")){let t={"content-type":"application/json","access-control-allow-origin":"*"};if(!e.headers.get("X-User-Payload"))return new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:t});let n=s.searchParams.get("ref");if(n){let m=await ft(this,n);return m?new Response(JSON.stringify({entry:m}),{headers:t}):new Response(JSON.stringify({error:"Not found"}),{status:404,headers:t})}let l=await pt(this);return new Response(JSON.stringify({entries:l}),{headers:t})}return e.method==="POST"&&s.pathname.endsWith("/message")?de(this,e,this.env,this.ctx):e.method==="DELETE"&&s.pathname.endsWith("/clear")?pe(this):new Response("Ready to assist.")}async onConnect(e,s){var a,u,i,g,h;let[t,n]=e.server.split("::"),m=(a=(await z(t,this.env)).metadata)==null?void 0:a.tenant;this.secrets=await Q(this.env,m),this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let c=null;if(s.request){try{this.publicOrigin=new URL(s.request.url).origin}catch{}let w=s.request.headers.get("X-User-Payload");if(w)try{c=JSON.parse(w)}catch(y){console.warn("Failed to parse X-User-Payload",y)}}let d=await tt(t,this.env);this.setState({...this.state,user:c||null,sessionId:n,engineState:{flowData:{...d,tenant:m,flowId:t,chatId:n},executedNodes:[],context:c?{user:c}:{}}}),c||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let f=await X(this);P(e,b.SERVER_HISTORY,JSON.stringify({messages:f}));let p=(((u=d==null?void 0:d.state)==null?void 0:u.nodes)??(d==null?void 0:d.nodes)??[]).find(w=>w.type==="startNode");if(p){let w={allow_images:((i=p.data)==null?void 0:i.allow_images)??!1,allow_documents:((g=p.data)==null?void 0:g.allow_documents)??!1,greeting:(h=p.data)==null?void 0:h.greeting};P(e,b.SERVER_CONFIG,JSON.stringify(w))}}async onMessage(e,s){if(typeof s!="string")return;let t=s.indexOf(":");if(t===-1)return;let n=s.substring(0,t),l=s.substring(t+1);if(!n||!l)return;let c={[b.USER_MESSAGE]:d=>this.onUserMessage(e,d),[b.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[b.USER_AUTH]:d=>this.onUserAuth(e,d),[b.USER_IDENTITY]:d=>this.onUserIdentity(e,d)}[n];c&&await c(l)}async onUserMessage(e,s){var y,x,C,N,$;let t=Date.now(),n=[],l=async()=>await X(this),m=async R=>{await ct(this,R)},c=async R=>{if(this.state.modelsCache&&this.state.modelsCache[R])return this.state.modelsCache[R];try{let{fetchOraModel:k}=await import("./oraApi-3JWDQQUE.js"),D=await k(R,this.env);return this.setState({...this.state,modelsCache:{...this.state.modelsCache,[R]:D}}),D}catch(k){throw console.error(`Error fetching model ${R}:`,k),k}},d=et(s),f={id:Ue(),role:"user",type:"text",content:d.text,images:d.images,ts:Date.now()};await m(f);let r={onChangeState:R=>{this.setState({...this.state,engineState:R})},onServerEvent:async R=>{P(e,b.SERVER_EVENT,JSON.stringify(R)),n.push(R)},onTelemetry:async R=>{var k,D,A,F,j,T;await ht({...R,userId:this.resolveSessionUserId(),tenant:((D=(k=this.state.engineState)==null?void 0:k.flowData)==null?void 0:D.tenant)||"",flowId:((F=(A=this.state.engineState)==null?void 0:A.flowData)==null?void 0:F.flowId)||"",sessionId:((T=(j=this.state.engineState)==null?void 0:j.flowData)==null?void 0:T.chatId)||""},this.env)},onError:R=>{P(e,b.SERVER_ERROR,R),this.setState({...this.state,error:R})}};if(Object.keys(this.secrets).length===0){let R=(x=(y=this.state.engineState)==null?void 0:y.flowData)==null?void 0:x.tenant;R&&(this.secrets=await Q(this.env,R))}let p={...this.state.engineState};this.state.user&&!((C=p.context)!=null&&C.user)&&(p.context={...p.context||{},user:this.state.user});let a=G(Z(p)),u=typeof p.cycle=="number"?p.cycle:0;a.enabled&&(u=await mt(this,p),p.cycle=u,this.setState({...this.state,engineState:p}));let i=yt(this,{env:this.env,ctx:this.ctx,conn:e,getMessages:l,setMessages:m,getOraModel:c,secrets:this.secrets,userAuth:this.userAuth,user:this.state.user,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache},p,u,async R=>{P(e,b.SERVER_EVENT,JSON.stringify({type:"info:memory:updated",content:{ref:R}}))});await lt(i,p,r)(d);let{tenant:g,flowId:h,chatId:w}=p.flowData??{};g&&h&&w&&this.ctx.waitUntil(gt(this.env,{id:`${h}::${w}`,tenant:g,flowId:h,sessionId:w,userId:this.resolveSessionUserId(),title:(N=d.text)==null?void 0:N.slice(0,120),turnTs:t,events:n})),($=i.memoryConfig)!=null&&$.enabled&&i.memoryConfig.mode==="summarize"&&this.ctx&&this.ctx.waitUntil(rt(this,i,u)),this.setState({...this.state,lastUpdated:new Date})}async onUserIdentity(e,s){let t=ot(s);if(!t){P(e,b.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:t}),P(e,b.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,s){let t=bt(s);if(!t){P(e,b.SERVER_ERROR,"Invalid auth payload");return}let n=t.value.trim();n===""?delete this.userAuth[t.name]:this.userAuth[t.name]=t.value,P(e,b.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:t.name,set:n!==""}}))}async onClearHistory(e){await dt(this),await ut(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear();let s=this.state.engineState?{...this.state.engineState,cycle:void 0}:void 0;this.setState({...this.state,error:"",engineState:s,lastUpdated:new Date}),e&&P(e,b.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await ce(this);let e=await X(this);`${JSON.stringify(e)}`}async onClose(e,s,t,n){console.log(`Session closed: ${this.state.sessionId} ${s} - ${t}`)}async onError(e){console.error("AgentDO encountered an error:",e)}};function mn(o){let e=o.state;if(!e)return null;let s=["startNode","answerNode"];for(let t of s)if(!e.nodes.some(l=>l.type===t))return!1;return e.nodes.find(t=>t.type==="startNode")}import{importSPKI as Le,jwtVerify as je}from"jose";function ue(o){let e={};if(!o)return e;let s=o.split(";");for(let t of s){let n=t.indexOf("=");if(n>-1){let l=t.slice(0,n).trim(),m=t.slice(n+1).trim();l&&(e[l]=decodeURIComponent(m))}}return e}async function J(o,e,s){let t=ue(o.headers.get("cookie")),n=new URL(o.url),l=t.access_token||n.searchParams.get("access_token"),m=await He(e,l);if(m.ok){let c=m.payload,d=typeof c.preferred_username=="string"?c.preferred_username.trim():"",f=typeof c.email=="string"?c.email.trim():"";return{id:c.sub,email:d||f,name:c.name,first_name:c.given_name,last_name:c.family_name,tenant:c.tenant,roles:c["ora-roles"],db_name:c.db_name||null,user_id:c.user_id||null}}return null}async function He(o,e){if(!e||typeof e!="string")return{ok:!1,payload:null,protectedHeader:null};if(!o.KC_RS256_PK)throw new Error("PK is not defined");let s=`-----BEGIN PUBLIC KEY-----
|
|
39
|
+
ts = excluded.ts`}async function ft(o){return o.sql`SELECT ref, domain, description, cycle, meta, ts FROM context ORDER BY ts ASC`}async function pt(o,e){return o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${e} LIMIT 1`[0]??null}async function ae(o,e){var t;return((t=o.sql`SELECT data FROM context WHERE ref = ${e} LIMIT 1`[0])==null?void 0:t.data)??null}async function re(o,e){let s=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref = ${e} LIMIT 1`;if(s[0])return s[0];let t=o.sql`SELECT ref, domain, description, data, cycle, meta, ts FROM context WHERE ref LIKE ${e+"%"} LIMIT 2`;return t.length===1?t[0]:null}async function le(o,e){o.sql`DELETE FROM context WHERE domain = 'tool' AND cycle <= ${e}`}async function ce(o){var s;return((s=o.sql`SELECT COALESCE(MAX(cycle), 0) AS maxCycle FROM context`[0])==null?void 0:s.maxCycle)??0}async function ut(o){o.sql`DELETE FROM context`}async function de(o){await Me(o),await De(o)}async function mt(o,e){var t,n,l;let s=(t=e==null?void 0:e.flowData)==null?void 0:t.flowId;if(!(o!=null&&o.FLOW_KV)||!s)return{engineState:e,refreshed:!1};try{let p=await o.FLOW_KV.getWithMetadata(s,{cacheTtl:60}),c=(n=p==null?void 0:p.metadata)==null?void 0:n.stateVersion;if(typeof c!="number"||c===((l=e.flowData)==null?void 0:l.stateVersion))return{engineState:e,refreshed:!1};let d=await Y(s,o);return{engineState:{...e,flowData:{...d,tenant:e.flowData.tenant,flowId:s,chatId:e.flowData.chatId}},refreshed:!0}}catch(p){return console.error(`[flowRefresh] version check failed for flow ${s}:`,p),{engineState:e,refreshed:!1}}}var kt=Object.freeze({});async function Z(o,e){if(!e)return kt;if(o.HX_ORA_URL&&o.HX_API_KEY)try{let n=await fetch(`${o.HX_ORA_URL}/internal/secrets`,{headers:{Authorization:o.HX_API_KEY}});if(n.ok){let l=await n.json();if(l.secrets)return Object.freeze(l.secrets)}else console.warn(`[secrets] API failed with status ${n.status}, falling back to KV`)}catch(n){console.error("[secrets] API request failed, falling back to KV",n)}let s=o.ORA_SECRETS;if(!s)return kt;let t=`${e}:`;try{let n=await s.list({prefix:t,limit:1e3});n.list_complete===!1&&console.warn(`[secrets] tenant=${e} exceeded list page; truncating to first 1000 keys`);let l=await Promise.all(n.keys.map(async c=>{let d=await s.get(c.name);return d!==null?[c.name.slice(t.length),d]:null})),p={};for(let c of l){if(!c)continue;let[d,u]=c;d&&(p[d]=u)}return Object.freeze(p)}catch(n){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,err:n}),kt}}import{nanoid as bs}from"nanoid";function S(o){var n,l;let e=(n=o==null?void 0:o.flowData)==null?void 0:n.state,t=((e==null?void 0:e.nodes)??((l=o==null?void 0:o.flowData)==null?void 0:l.nodes)??[]).find(p=>p.type==="startNode");return t==null?void 0:t.data}async function yt(o,e){return typeof e.cycle=="number"&&Number.isFinite(e.cycle)?e.cycle+1:await ce(o)+1}function gt(o,e,s,t,n){let l=G(S(s));return{...e,memoryConfig:l,cycle:t,setContext:async c=>{await ie(o,c),await(n==null?void 0:n(c.ref))},getContextIndex:async()=>ft(o),getContextData:async c=>ae(o,c),getContext:async c=>pt(o,c),resolveContext:async c=>re(o,c),pruneContext:async c=>le(o,c)}}function ht(o,e){return!o||!o.HX_ORA_URL||!o.HX_API_KEY?Promise.resolve():fetch(`${o.HX_ORA_URL}/internal/sessions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:o.HX_API_KEY},body:JSON.stringify(e)}).catch(s=>{console.error("[sessionIndex] failed to index session",s)})}var wt=async(o,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),`${JSON.stringify(o)}`};import{nanoid as be}from"nanoid";async function Pe(o,e){var l,p;let s=o.id||o.name||"",[t,n]=s.split("::");if(!t||!n)return null;try{let d=(l=(await z(t,e)).metadata)==null?void 0:l.tenant,u=await Y(t,e),r=(p=o.state)==null?void 0:p.user,f={flowData:{...u,tenant:d,flowId:t,chatId:n},executedNodes:[],context:r?{user:r}:{}};return o.setState({...o.state,engineState:f}),f}catch(c){return console.error("Failed to initialize engine state:",c),null}}async function fe(o,e,s,t){var n,l,p;try{let c=await e.json(),d=c.message;if(!d||typeof d!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let u=typeof c.userId=="string"?ot(c.userId):null;u&&!((n=o.state.user)!=null&&n.email)&&o.setState({...o.state,injectedUserId:u});let r=()=>{var N;return((N=o.state.user)==null?void 0:N.email)??u??o.state.injectedUserId??void 0},f=Date.now(),a=[],m=async()=>await X(o),i=async N=>{await ct(o,N)},g={id:be(),role:"user",type:"text",content:d,ts:Date.now()};await i(g);let h={onChangeState:N=>{o.setState({...o.state,engineState:N})},onServerEvent:async N=>{a.push(N)},onTelemetry:async N=>{var b,D,q,B,Q,L;await wt({...N,userId:r(),tenant:((D=(b=o.state.engineState)==null?void 0:b.flowData)==null?void 0:D.tenant)||"",flowId:((B=(q=o.state.engineState)==null?void 0:q.flowData)==null?void 0:B.flowId)||"",sessionId:((L=(Q=o.state.engineState)==null?void 0:Q.flowData)==null?void 0:L.chatId)||""},s)},onError:N=>{o.setState({...o.state,error:N})}},w=async N=>{if(o.state.modelsCache&&o.state.modelsCache[N])return o.state.modelsCache[N];try{let{fetchOraModel:b}=await import("./oraApi-3JWDQQUE.js"),D=await b(N,s);return o.setState({...o.state,modelsCache:{...o.state.modelsCache||{},[N]:D}}),D}catch(b){throw console.error(`Error fetching model ${N}:`,b),b}},y=o.state.engineState;if(y){let{engineState:N,refreshed:b}=await mt(s,y);b&&(y=N,o.setState({...o.state,engineState:y,modelsCache:{}}))}else if(y=await Pe(o,s),!y)return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let x=(l=y==null?void 0:y.flowData)==null?void 0:l.tenant,C=await Z(s,x),R=G(S(y)),$=typeof y.cycle=="number"?y.cycle:0;R.enabled&&($=await yt(o,y),y={...y,cycle:$},o.setState({...o.state,engineState:y})),o.skillRefCache||(o.skillRefCache=new Map);let _=gt(o,{env:s,ctx:t,conn:void 0,getMessages:m,setMessages:i,getOraModel:w,secrets:C,skillRefCache:o.skillRefCache},y,$);await lt(_,y,h)(d);let{tenant:I,flowId:A,chatId:k}=y.flowData??{};I&&A&&k&&t.waitUntil(ht(s,{id:`${A}::${k}`,tenant:I,flowId:A,sessionId:k,userId:r(),title:d.slice(0,120),turnTs:f,events:a})),(p=_.memoryConfig)!=null&&p.enabled&&_.memoryConfig.mode==="summarize"&&t&&t.waitUntil(rt(o,_,$)),o.setState({...o.state,lastUpdated:new Date});let j=(await m()).reverse().find(N=>N.role==="assistant");return new Response(JSON.stringify({answer:(j==null?void 0:j.content)||""}),{headers:{"content-type":"application/json"}})}catch(c){return new Response(JSON.stringify({error:c.message}),{status:500,headers:{"content-type":"application/json"}})}}async function pe(o){try{return await dt(o),await ut(o),o.skillRefCache&&o.skillRefCache.clear(),o.setState({...o.state,error:"",engineState:void 0,modelsCache:{},lastUpdated:new Date}),new Response(JSON.stringify({success:!0,messages:[]}),{headers:{"content-type":"application/json"}})}catch(e){return new Response(JSON.stringify({error:e.message}),{status:500,headers:{"content-type":"application/json"}})}}var je=15e3,ue=class extends Ue{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{}};resolveSessionUserId(){var e;return((e=this.state.user)==null?void 0:e.email)??this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;lastFlowVersionCheckTs=0;async onRequest(e){let s=new URL(e.url);if(s.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(s.pathname.endsWith("/history")){let t=await X(this);return new Response(JSON.stringify(t),{headers:{"content-type":"application/json"}})}if(s.pathname.endsWith("/context")){let t={"content-type":"application/json","access-control-allow-origin":"*"};if(!e.headers.get("X-User-Payload"))return new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:t});let n=s.searchParams.get("ref");if(n){let p=await pt(this,n);return p?new Response(JSON.stringify({entry:p}),{headers:t}):new Response(JSON.stringify({error:"Not found"}),{status:404,headers:t})}let l=await ft(this);return new Response(JSON.stringify({entries:l}),{headers:t})}return e.method==="POST"&&s.pathname.endsWith("/message")?fe(this,e,this.env,this.ctx):e.method==="DELETE"&&s.pathname.endsWith("/clear")?pe(this):new Response("Ready to assist.")}async onConnect(e,s){var a,m,i,g,h;let[t,n]=e.server.split("::"),p=(a=(await z(t,this.env)).metadata)==null?void 0:a.tenant;this.secrets=await Z(this.env,p),this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let c=null;if(s.request){try{this.publicOrigin=new URL(s.request.url).origin}catch{}let w=s.request.headers.get("X-User-Payload");if(w)try{c=JSON.parse(w)}catch(y){console.warn("Failed to parse X-User-Payload",y)}}let d=await Y(t,this.env);this.setState({...this.state,user:c||null,sessionId:n,engineState:{flowData:{...d,tenant:p,flowId:t,chatId:n},executedNodes:[],context:c?{user:c}:{}}}),c||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let u=await X(this);U(e,P.SERVER_HISTORY,JSON.stringify({messages:u}));let f=(((m=d==null?void 0:d.state)==null?void 0:m.nodes)??(d==null?void 0:d.nodes)??[]).find(w=>w.type==="startNode");if(f){let w={allow_images:((i=f.data)==null?void 0:i.allow_images)??!1,allow_documents:((g=f.data)==null?void 0:g.allow_documents)??!1,greeting:(h=f.data)==null?void 0:h.greeting};U(e,P.SERVER_CONFIG,JSON.stringify(w))}}async onMessage(e,s){if(typeof s!="string")return;let t=s.indexOf(":");if(t===-1)return;let n=s.substring(0,t),l=s.substring(t+1);if(!n||!l)return;let c={[P.USER_MESSAGE]:d=>this.onUserMessage(e,d),[P.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[P.USER_AUTH]:d=>this.onUserAuth(e,d),[P.USER_IDENTITY]:d=>this.onUserIdentity(e,d)}[n];c&&await c(l)}async onUserMessage(e,s){var x,C,R,$,_;let t=Date.now(),n=[],l=async()=>await X(this),p=async I=>{await ct(this,I)},c=async I=>{if(this.state.modelsCache&&this.state.modelsCache[I])return this.state.modelsCache[I];try{let{fetchOraModel:A}=await import("./oraApi-3JWDQQUE.js"),k=await A(I,this.env);return this.setState({...this.state,modelsCache:{...this.state.modelsCache,[I]:k}}),k}catch(A){throw console.error(`Error fetching model ${I}:`,A),A}},d=et(s),u={id:Le(),role:"user",type:"text",content:d.text,images:d.images,ts:Date.now()};await p(u);let r={onChangeState:I=>{this.setState({...this.state,engineState:I})},onServerEvent:async I=>{U(e,P.SERVER_EVENT,JSON.stringify(I)),n.push(I)},onTelemetry:async I=>{var A,k,M,j,N,b;await wt({...I,userId:this.resolveSessionUserId(),tenant:((k=(A=this.state.engineState)==null?void 0:A.flowData)==null?void 0:k.tenant)||"",flowId:((j=(M=this.state.engineState)==null?void 0:M.flowData)==null?void 0:j.flowId)||"",sessionId:((b=(N=this.state.engineState)==null?void 0:N.flowData)==null?void 0:b.chatId)||""},this.env)},onError:I=>{U(e,P.SERVER_ERROR,I),this.setState({...this.state,error:I})}};if(Object.keys(this.secrets).length===0){let I=(C=(x=this.state.engineState)==null?void 0:x.flowData)==null?void 0:C.tenant;I&&(this.secrets=await Z(this.env,I))}let f={...this.state.engineState},a=Date.now();if(a-this.lastFlowVersionCheckTs>je){this.lastFlowVersionCheckTs=a;let{engineState:I,refreshed:A}=await mt(this.env,f);A&&(f=I,this.setState({...this.state,engineState:f,modelsCache:{}}))}this.state.user&&!((R=f.context)!=null&&R.user)&&(f.context={...f.context||{},user:this.state.user});let m=G(S(f)),i=typeof f.cycle=="number"?f.cycle:0;m.enabled&&(i=await yt(this,f),f.cycle=i,this.setState({...this.state,engineState:f}));let g=gt(this,{env:this.env,ctx:this.ctx,conn:e,getMessages:l,setMessages:p,getOraModel:c,secrets:this.secrets,userAuth:this.userAuth,user:this.state.user,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache},f,i,async I=>{U(e,P.SERVER_EVENT,JSON.stringify({type:"info:memory:updated",content:{ref:I}}))});await lt(g,f,r)(d);let{tenant:h,flowId:w,chatId:y}=f.flowData??{};h&&w&&y&&this.ctx.waitUntil(ht(this.env,{id:`${w}::${y}`,tenant:h,flowId:w,sessionId:y,userId:this.resolveSessionUserId(),title:($=d.text)==null?void 0:$.slice(0,120),turnTs:t,events:n})),(_=g.memoryConfig)!=null&&_.enabled&&g.memoryConfig.mode==="summarize"&&this.ctx&&this.ctx.waitUntil(rt(this,g,i)),this.setState({...this.state,lastUpdated:new Date})}async onUserIdentity(e,s){let t=ot(s);if(!t){U(e,P.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:t}),U(e,P.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,s){let t=bt(s);if(!t){U(e,P.SERVER_ERROR,"Invalid auth payload");return}let n=t.value.trim();n===""?delete this.userAuth[t.name]:this.userAuth[t.name]=t.value,U(e,P.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:t.name,set:n!==""}}))}async onClearHistory(e){await dt(this),await ut(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear();let s=this.state.engineState?{...this.state.engineState,cycle:void 0}:void 0;this.setState({...this.state,error:"",engineState:s,modelsCache:{},lastUpdated:new Date}),e&&U(e,P.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await de(this);let e=await X(this);`${JSON.stringify(e)}`}async onClose(e,s,t,n){console.log(`Session closed: ${this.state.sessionId} ${s} - ${t}`)}async onError(e){console.error("AgentDO encountered an error:",e)}};function Rn(o){let e=o.state;if(!e)return null;let s=["startNode","answerNode"];for(let t of s)if(!e.nodes.some(l=>l.type===t))return!1;return e.nodes.find(t=>t.type==="startNode")}import{importSPKI as He,jwtVerify as Ve}from"jose";function me(o){let e={};if(!o)return e;let s=o.split(";");for(let t of s){let n=t.indexOf("=");if(n>-1){let l=t.slice(0,n).trim(),p=t.slice(n+1).trim();l&&(e[l]=decodeURIComponent(p))}}return e}async function J(o,e,s){let t=me(o.headers.get("cookie")),n=new URL(o.url),l=t.access_token||n.searchParams.get("access_token"),p=await qe(e,l);if(p.ok){let c=p.payload,d=typeof c.preferred_username=="string"?c.preferred_username.trim():"",u=typeof c.email=="string"?c.email.trim():"";return{id:c.sub,email:d||u,name:c.name,first_name:c.given_name,last_name:c.family_name,tenant:c.tenant,roles:c["ora-roles"],db_name:c.db_name||null,user_id:c.user_id||null}}return null}async function qe(o,e){if(!e||typeof e!="string")return{ok:!1,payload:null,protectedHeader:null};if(!o.KC_RS256_PK)throw new Error("PK is not defined");let s=`-----BEGIN PUBLIC KEY-----
|
|
40
40
|
${o.KC_RS256_PK}
|
|
41
|
-
-----END PUBLIC KEY-----`,t=await
|
|
41
|
+
-----END PUBLIC KEY-----`,t=await He(s,"RS256");try{let{payload:n,protectedHeader:l}=await Ve(e,t);return{ok:!0,payload:n,protectedHeader:l}}catch(n){return console.error("JWT verification failed:",n),{ok:!1,payload:null,protectedHeader:null}}}async function _n(o,e,s){let t=new URL(o.url);if(t.pathname==="/favicon.ico")return new Response(null,{status:204});if(t.pathname.startsWith("/.well-known/appspecific"))return new Response(null,{status:204})}import{getAgentByName as ye}from"agents";var Je=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;async function Mn(o,e,s){var n,l,p,c;let t=new URL(o.url);if(t.pathname.startsWith("/a/")){let d=t.pathname.split("/"),u=d[2],r=d[3];try{if(!u)return Response.redirect(new URL("/",t.origin).toString(),302);let f;try{f=await z(u,e)}catch{return new Response("Flow not found",{status:404})}if(!f.metadata||((n=f.metadata)==null?void 0:n.status)!=="active")return new Response("NO chat",{status:404});if(((l=f.metadata)==null?void 0:l.visibility)==="private"&&!await J(o,e,s)){let m=new URL("/login",t.origin);return m.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(m.toString(),302)}if(!r){let a=crypto.randomUUID(),m=new URL(`/a/${u}/${a}`,t.origin);return Response.redirect(m.toString(),302)}if(!Je.test(r))return new Response("Id del chat no v\xE1lido",{status:400})}catch(f){return console.error("Error accessing flow KV:",f),new Response("Flow error",{status:500})}}if(t.pathname.startsWith("/api/agent/flow")){let d=t.pathname.split("/"),u=d[4],r=d[5],f=`${u}::${r}`;try{let a=await J(o,e,s);if(!a){let w=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${w}) \u2014 Composio connections from tool editor will not apply`)}let m=new Headers(o.headers);a&&m.set("X-User-Payload",JSON.stringify(a));let i=new Request(o,{headers:m});return(await ye(e.AGENT,f)).fetch(i)}catch(a){return console.error("Error accessing agent:",a),new Response("Agent error",{status:500})}}if(t.pathname.startsWith("/api/ora/connect")){let d=t.pathname.split("/"),u=d[4],r=d[5];if(!u||!r)return new Response("Missing flowId or sessionId",{status:400});let f=o.headers.get("Authorization")||t.searchParams.get("authorization");if(!f)return new Response("Missing Authorization header",{status:401});try{let a=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${u}`,i=await(await fetch(a,{method:"GET",headers:{Authorization:f}})).json();if(((p=i.payload)==null?void 0:p.flowId)!==u)return console.error("FlowId mismatch:",(c=i.payload)==null?void 0:c.flowId,"!==",u),new Response("Validation error",{status:403});let g=`${u}::${r}`,h=await J(o,e,s);if(!h){let R=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${R}) \u2014 Composio connections from tool editor will not apply`)}let w=new Headers(o.headers);h&&w.set("X-User-Payload",JSON.stringify(h));let y=new Request(o,{headers:w});return(await ye(e.AGENT,g)).fetch(y)}catch(a){return console.error("Error in /api/ora/connect:",a),new Response("Internal error",{status:500})}}}async function Pn(o,e,s){let t=new URL(o.url),n=o.method;if(!t.pathname.startsWith("/api/instances"))return;let l=await J(o,e,s);if(!l)return new Response("Unauthorized",{status:401});let p=e.HX_CORE_URL,c=e.HX_API_KEY;if(!p||!c)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let u=t.pathname.slice("/api/instances".length);u.startsWith("/")&&(u=u.slice(1)),u.endsWith("/")&&(u=u.slice(0,-1));let r="/ora/instances";u&&(r+=`/${u}`);let f=p.endsWith("/")?p.slice(0,-1):p,a=new URL(`${f}${r}`);t.searchParams.forEach((g,h)=>{a.searchParams.set(h,g)}),n==="GET"&&!u&&a.searchParams.set("filter_user_id",l.email);let m=new Headers;m.set("Authorization",c),m.set("Content-Type","application/json"),m.set("X-User-Payload",JSON.stringify(l));let i={method:n,headers:m};if(["POST","PATCH","PUT"].includes(n))try{i.body=await o.text()}catch(g){console.error("Error reading request body:",g)}try{let g=await fetch(a.toString(),i),h=await g.text();return new Response(h,{status:g.status,headers:{"Content-Type":"application/json"}})}catch(g){return console.error("Error proxying to flow instance backend:",g),new Response("Internal Server Error",{status:500})}}async function jn(o,e,s){let t=new URL(o.url);if(o.method==="POST"&&t.pathname==="/auth/login")try{let n=await o.formData(),l=n.get("username"),p=n.get("password"),c=n.get("nextURL")||"/";if(!l||!p)return new Response("Missing username or password",{status:400});let d=new URLSearchParams;d.append("username",l),d.append("password",p),d.append("grant_type","password"),d.append("client_id",e.KC_CLIENT_ID),d.append("client_secret",e.KC_CLIENT_SECRET);let u=await fetch(`${e.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:d});if(!u.ok)return new Response("Unauthorized",{status:401});let r=await u.json(),f=new Response(null,{status:302,headers:{Location:c}}),a=(m,i,g)=>{f.headers.append("Set-Cookie",`${m}=${i}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${g}`)};return r.access_token&&a("access_token",r.access_token,r.expires_in),r.refresh_token&&a("refresh_token",r.refresh_token,r.refresh_expires_in||3600*24*30),r.id_token&&a("id_token",r.id_token,r.expires_in),f}catch(n){return console.error("Auth error:",n),new Response("Internal Server Error",{status:500})}if(t.pathname==="/auth/logout"){let n=new Response(null,{status:302,headers:{Location:"/login"}}),l=p=>{n.headers.append("Set-Cookie",`${p}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return l("access_token"),l("refresh_token"),l("id_token"),n}if(t.pathname.startsWith("/s/")){let n=await J(o,e,s);if(!n){let l=new URL("/login",t.origin);return l.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(l.toString(),302)}return{user:n}}}export{ue as AgentDO,Se as GENERATION_PARAM_KEYS,to as GENERATION_PRESETS,Be as MAX_USER_IDENTITY_LENGTH,go as MODEL_REGISTRY_SNAPSHOT,E as NodeType,ve as PRESET_PARAM_KEYS,fo as REASONING_EFFORT_LEVELS,Jt as TOOL_REGISTRY_SNAPSHOT,so as applyPresetToOverrides,qt as buildReasoningProviderOptions,ze as buildUrl,ut as clearAllContext,dt as clearAllMessages,Ke as convertTempMessure,le as deleteContextToolsUpToCycle,eo as deriveParamSupport,Dt as embedText,de as ensureAgentTables,De as ensureContextTable,Me as ensureMessagesTable,X as getAllMessages,pt as getContext,ae as getContextData,ft as getContextIndex,Ze as getDefaultOutVars,st as getEffectiveOutVars,ce as getMaxContextCycle,ho as getModelEntry,Mn as handleAgentsRoutes,jn as handleAuthRoutes,_n as handleCommonRoutes,Pn as handleIntancesRoutes,Ee as hashText,Kt as jsonSchemaToZod,tt as logc,P as messageTypes,no as normalizeEffectiveParams,mo as normalizeModelEntry,po as normalizeReasoning,ao as openAiReasoningParamSupport,io as openAiStandardParamSupport,me as parseCookies,bt as parseUserAuth,et as parseUserMessage,Lt as pickNodeOverrides,uo as reasoningEffortLevels,Ht as reasoningExposable,yo as registerProvider,re as resolveContextRef,at as resolveModelById,nt as resolveOutVarRef,oo as resolvePreset,Vt as resolveReasoningEffort,Pt as resolveTemplate,We as safeParseJSON,ot as sanitizeUserIdentity,wt as sendEvent,U as serverSend,ie as setContext,ct as setMessage,lt as startEngine,co as stripUnsupportedFromNodeData,Xe as tempTool,jt as toStreamTextSettings,Ye as twitter,Rn as validateFlowStart,Ge as vectorize,qe as verifyToken,J as verifyUser,Qe as walkPath,lo as workersAiParamSupport,ro as xaiParamSupport};
|