@hugex/ai 2.9.5 → 2.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ ${l.map(y=>{let x=y.keywords??y["keywords/topics"]??"",C=Array.isArray(x)?x.join
11
11
 
12
12
  Select the best matching category id.`;try{let y=Date.now(),x=l.map(A=>String(A.id)),C="gpt_4_1_mini",R=await at(C,o);if(!R)throw new Error(`Model '${C}' not found in registry`);let{modelHandle:k,effectiveParams:_}=R,P=await we({model:k,messages:[{role:"system",content:m},{role:"user",content:i}],schema:ee.object({classification:ee.enum(x).describe("The id of the best matching category")}),temperature:_.temperature??0}),I=Date.now()-y,$=P.object.classification;p==null||p({type:"class_telemetry",payload:{nodeId:e.id,totalLatency:I,model:P.response.modelId,usage:P.usage,options:x}}),p==null||p({type:"class_result",payload:{result:P}}),n==null||n(e.id,{classification:$}),s.context=s.context||{},s.context.classified_id=$,a==null||a(s),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}catch(y){t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(y)}})}}import{stepCountIs as Ne,streamText as Ce}from"ai";import{nanoid as Te}from"nanoid";import"zod";var U=(o,e,s)=>{o.send(e+"::"+s)};function oe(o,e){var t,n,a,p,c,d;let s="";if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let u of o.data.varMapping){let l=u.from;if(!l)continue;let f=!1;if(l==="files"||l==="file_content")f=!0;else{let r=l.indexOf(".");if(r!==-1){let m=l.substring(0,r),i=l.substring(r+1).split(".")[0],g=(p=(a=(n=e.flowData)==null?void 0:n.state)==null?void 0:a.nodes)==null?void 0:p.find(h=>h.id===m);if(g){let w=st(g).find(y=>y.name===i);(w==null?void 0:w.type)==="file"&&(f=!0)}}}if(f){let r=nt(l,{context:e.context||{},results:e.results||{},nodes:((d=(c=e.flowData)==null?void 0:c.state)==null?void 0:d.nodes)||[]});typeof r=="string"&&r.trim()&&(s+=(s?`
13
13
 
14
- `:"")+r)}}return s}function se(o,e){var t,n,a,p,c,d;let s=[];if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let u of o.data.varMapping){let l=u.from;if(!l)continue;let f=!1;if(l==="images")f=!0;else{let r=l.indexOf(".");if(r!==-1){let m=l.substring(0,r),i=l.substring(r+1).split(".")[0],g=(p=(a=(n=e.flowData)==null?void 0:n.state)==null?void 0:a.nodes)==null?void 0:p.find(h=>h.id===m);if(g){let w=st(g).find(y=>y.name===i);(w==null?void 0:w.type)==="image"&&(f=!0)}}}if(f){let r=nt(l,{context:e.context||{},results:e.results||{},nodes:((d=(c=e.flowData)==null?void 0:c.state)==null?void 0:d.nodes)||[]});Array.isArray(r)&&s.push(...r)}}return s}var xe=v({"../tools/composioTool.ts":()=>import("./composioTool-TVURCFXP.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-NTDDXZZE.js"),"../tools/recall.ts":()=>import("./recall-IABRCSHY.js"),"../tools/skillTool.ts":()=>import("./skillTool-BSQFKZGK.js"),"../tools/tempTool.ts":()=>import("./tempTool-2RXAF56M.js"),"../tools/twitter.ts":()=>import("./twitter-OMDEG7T2.js"),"../tools/vectorize.ts":()=>import("./vectorize-UJXIDL2E.js")});var Re=v({});function Ot(o,e,s,t,n){var p;if(!((p=t.memoryConfig)!=null&&p.enabled)||!t.memoryConfig.toolCache||!s.cacheable||!e||typeof e.execute!="function")return e;let a=e.execute.bind(e);return e.execute=async(c,...d)=>{var r;if(!t.getContextIndex)return a(c,...d);let u=await xt(c),f=(await t.getContextIndex()).find(m=>{if(m.domain!=="tool")return!1;let i=Rt(m.meta);return i.toolName===o&&i.paramsHash===u});if(f){let m=await((r=t.getContext)==null?void 0:r.call(t,f.ref));if((m==null?void 0:m.data)!=null&&Rt(m.meta).truncated!==!0){n==null||n({type:"info:memory:cacheHit",content:{ref:m.ref,toolName:o}});try{return JSON.parse(m.data)}catch{return m.data}}}return a(c,...d)},e}async function Ie(o,e,s,t){var l,f;if(!((l=s.memoryConfig)!=null&&l.enabled)||!s.setContext||s.cycle==null)return;let n=o.toolCalls??[],a=o.toolResults??[];if(!n.length||!a.length)return;let p=new Map;for(let r of a)r!=null&&r.toolCallId&&p.set(r.toolCallId,r);let c=Array.isArray((f=e==null?void 0:e.data)==null?void 0:f.tools)?e.data.tools:[],d=new Map;for(let r of c)r&&typeof r.id=="string"&&d.set(r.id,r);let u=new Map;for(let r of Object.values(s.toolDefs??{}))r&&r.name&&u.set(r.name,r);for(let r of n){let m=r.toolCallId,i=r.toolName,g=p.get(m);if(!i||!g||i==="readSkillRef")continue;let h=r.args??r.input,w=g.result??g.output,y=!1,x="",C="tool",R="",k=u.get(i);k&&k.kind==="skill"&&(y=!0,x=`skill:${i}`,C="skill",R=`Skill instructions for ${i}`),x||(x=await Bt(i,h),R=Et(h,w));let _=d.get(i)??c.find($=>$.id===i),P=await xt(h),I=typeof w=="string"?w:JSON.stringify(w??null);await s.setContext({ref:x,domain:C,description:R,data:I,cycle:s.cycle,meta:JSON.stringify({toolName:i,paramsHash:P,cacheable:(_==null?void 0:_.cacheable)===!0})}),t==null||t({type:"info:memory:updated",content:{ref:x}})}}async function Oe(o,e,s,t){var f;let n=Array.isArray((f=s==null?void 0:s.data)==null?void 0:f.tools)?s.data.tools:[];if(n.length===0)return{};let a={},p=r=>{var x,C;let m=typeof(r==null?void 0:r.description)=="string"?r.description:"",i=r==null?void 0:r.inputSchema,g;try{let R=(i==null?void 0:i.shape)??(typeof((x=i==null?void 0:i._def)==null?void 0:x.shape)=="function"?i._def.shape():(C=i==null?void 0:i._def)==null?void 0:C.shape);R&&typeof R=="object"&&(g=R)}catch{}let h=g?Object.keys(g):[],w=m?`description="${m.length>120?m.slice(0,120)+"\u2026":m}"`:"description=(none)",y=h.length?`inputSchema={${h.join(", ")}}`:"inputSchema=(none)";return`${w} ${y}`},c=(()=>{let r=[],m=[],i=[],g=[];for(let w=0;w<n.length;w++){let y=n[w];!y||typeof y!="object"||typeof y.id!="string"?g.push(w):y.kind==="builtin"?r.push(y.id):y.kind==="skill"?i.push(y.id):y.kind==="http"||y.kind==="mcp"||y.kind==="composio"?m.push(y.id):g.push(w)}let h=[];return r.length&&h.push(`builtin[${r.join(", ")}]`),m.length&&h.push(`custom[${m.join(", ")}]`),i.length&&h.push(`skill[${i.join(", ")}]`),g.length&&h.push(`invalid@[${g.join(", ")}]`),h.join(" ")||"(none)"})();console.log(`[tools] node ${s.id} requested (${n.length}): ${c}`);let d=!1,u=async()=>{if(d&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},d=!0,o.toolDefs;try{let r=await Xt(o.env),m={};for(let i of r)i&&i.id&&(m[i.id]=i);o.toolDefs=m}catch(r){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(r)}`}),o.toolDefs=o.toolDefs||{}}return d=!0,o.toolDefs},l=[];for(let r=0;r<n.length;r++){let m=n[r];if(!m||typeof m!="object"||typeof m.id!="string"||m.kind!=="builtin"&&m.kind!=="http"&&m.kind!=="mcp"&&m.kind!=="composio"&&m.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${r}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let i=m;if(i.kind!=="builtin"){let h=(await u())[i.id];if(!h){console.error(`[tools] \u2717 custom '${i.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${i.id}' not found for this tenant`});continue}if(i.kind==="composio"){try{let y=await zt(h,o,e,t),x=Object.keys(y);for(let[C,R]of Object.entries(y))a[C]=Ot(C,R,i,o,t);console.log(`[tools] \u2713 composio '${i.id}' \u2192 ${x.length} tool(s)`)}catch(y){console.error(`[tools] \u2717 composio '${i.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${i.id}': ${String(y)}`})}continue}if(i.kind==="skill"){if(h.kind!=="skill"){console.error(`[tools] \u2717 skill '${i.id}': row is of kind '${h.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${i.id}' is not a skill`});continue}let y=h.name;if(a[y]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${y}' \u2014 builtin/other already registered, skipping skill '${i.id}'`});continue}try{a[y]=Yt(h,o,e,t),l.push(h);let x=typeof h.execution=="string"?JSON.parse(h.execution):h.execution||{},C=Array.isArray(x.references)?x.references.map(R=>R==null?void 0:R.name):[];console.log(`[tools] \u2713 skill '${i.id}' \u2192 '${y}' (refs: ${C.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:y,refCount:C.length,refs:C}})}catch(x){console.error(`[tools] \u2717 skill '${i.id}': ${String(x)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${i.id}': ${String(x)}`})}continue}let w=h.name;if(a[w]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin already registered, skipping custom tool '${i.id}'`});continue}try{let y=Wt(h,o,e,t);a[w]=Ot(w,y,i,o,t),console.log(`[tools] \u2713 custom '${i.id}' \u2192 '${w}'`),console.log(`[tools] ${p(a[w])}`)}catch(y){console.error(`[tools] \u2717 custom '${i.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${i.id}': ${String(y)}`})}continue}if(!Jt[i.id]){console.error(`[tools] \u2717 builtin '${i.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${i.id}' not found in registry`});continue}try{let g;try{g=await xe(`../tools/${i.id}.ts`)}catch{g=await Re(`../tools/${i.id}.js`)}let h;if(g[i.id])h=g[i.id];else if(g.default)h=g.default;else if(g.create)h=g.create;else{let _=Object.values(g);_.length>0&&(h=_[0])}if(!h){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${i.id}'`});continue}let w,y,x={};if(i.params&&typeof i.params=="object"){if(typeof i.params.description=="string"?w=i.params.description:i.params.description!==void 0&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${i.id}' \u2014 must be a string`})),i.params.inputSchema!==void 0){let _=i.params.inputSchema;typeof _=="object"&&(typeof _.safeParse=="function"||_._def)?y=_:typeof _=="object"&&_!==null&&_.type==="object"&&_.properties?(y=Kt(_),y||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${i.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${i.id}' \u2014 must be a Zod schema or JSON Schema object`})}i.params.defaults!==void 0?typeof i.params.defaults=="object"&&i.params.defaults!==null&&!Array.isArray(i.params.defaults)?x=i.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${i.id}' \u2014 must be an object`}),x={}):i.params.source!==void 0||i.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${i.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),x={}):x={}}let C=h(o,e,x,t);w&&C&&typeof C=="object"&&(C.description=w),y&&C&&typeof C=="object"&&(C.inputSchema=y),a[i.id]=Ot(i.id,C,i,o,t);let R=[];w&&R.push("description"),y&&R.push("inputSchema"),Object.keys(x).length&&R.push(`defaults(${Object.keys(x).join(",")})`);let k=R.length?` [overrides: ${R.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${i.id}'${k}`),console.log(`[tools] ${p(C)}`)}catch(g){console.error(`[tools] \u2717 builtin '${i.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${i.id}': ${String(g)}`});continue}}if(l.length>0)if(a.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{a.readSkillRef=Gt(o,l,e,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${l.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:l.map(r=>r.name)}})}catch(r){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(r)}`)}return a}async function _t(o,e,s,t,n,a,p){var P,I,$,A,j;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=!1;try{let N=(P=s.flowData)==null?void 0:P.state;if(N&&N.edges&&N.nodes){let D=N.edges.filter(M=>M.source===e.id);if(D.length>0){let M=N.nodes.find(q=>q.id===D[0].target);M&&M.type==="answerNode"&&(c=!0)}}}catch(N){console.error("Error determining next node for streaming:",N)}let d=K(e.data.template,e,s,t,{sessionEnv:o});(!d||!d.trim())&&(d="Answer straight forward to the user, dont offer any other option to continue");let u=d,l="";if((I=o.memoryConfig)!=null&&I.enabled){let N=await(($=o.getContextIndex)==null?void 0:$.call(o))??[];l=Zt(N),d+=l}let f=K(e.data.user_template||"",e,s,t,{sessionEnv:o}),r=N=>N&&Object.fromEntries(Object.keys(N).map(D=>[D,"[redacted]"])),m=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:r(o.secrets),userAuth:r(o.userAuth)}:o,i=K(e.data.template,e,s,void 0,{sessionEnv:m})||u;i+=l;let g=K(e.data.user_template||"",e,s,void 0,{sessionEnv:m});t==null||t({type:`info:llmNodeRunner:${e.id}`,content:i}),t==null||t({type:`info:llmNodeRunner:${e.id}`,content:g});let h=(A=e==null?void 0:e.data)==null?void 0:A.window_size,w=Number(h);(!Number.isInteger(w)||w<=0)&&(w=5);let y=se(e,s),x=oe(e,s),R=(await((j=o.getMessages)==null?void 0:j.call(o))??[]).slice(-w),k=R.filter(N=>N&&typeof N.role=="string"&&typeof N.content=="string");k.length!==R.length&&console.warn(`Filtered ${R.length-k.length} invalid messages from history`);let _=Fe(k,f,y,x);await _e(d,_,o.conn,t,e,c,n,s,a,o,p)}async function _e(o,e,s,t,n,a,p,c,d,u,l){var r;let f=Date.now();if(!((r=u.env)!=null&&r.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(m,i)=>{var j,N,D,M,q,B,Q;let g,h={},w,y="none",x=!1,C,R=!1,k=!1,_=0,P=0,I=(j=n==null?void 0:n.data)==null?void 0:j.sendReasoning,$=I!==!1;try{let L=(N=n==null?void 0:n.data)==null?void 0:N.model,W=Array.isArray(L)?L[0]:L||"gpt_5_nano",T=Lt(n==null?void 0:n.data),F=await at(W,u,T);if(!F)throw new Error(`Model '${W}' not found in registry`);g=F.modelHandle,h=F.effectiveParams||{},y=F.reasoning.kind;let O=Vt(F.reasoning,(D=n==null?void 0:n.data)==null?void 0:D.reasoningEffort);x=$&&Ht(F.reasoning);let V=typeof((M=n==null?void 0:n.data)==null?void 0:M.reasoningMaxTokens)=="number"?n.data.reasoningMaxTokens:void 0;w=qt(F.provider,{effort:O,exposeReasoning:x,maxTokens:V}),O&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:O})),console.log(`[reasoning] ${JSON.stringify({model:W,provider:F.provider,capability:F.reasoning,requestedEffort:((q=n==null?void 0:n.data)==null?void 0:q.reasoningEffort)??null,resolvedEffort:O??null,sendReasoning:$,exposeReasoning:x,providerOptions:w??null},null,2)}`);for(let H of F.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:H});t==null||t({type:"info:llmNodeRunner:model",content:W}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(B=n==null?void 0:n.data)!=null&&B.generationPreset?{preset:n.data.generationPreset}:{},...h,...y!=="none"?{reasoning:y,configuredSendReasoning:I,sendReasoning:$,exposeReasoning:x,...O?{effort:O}:{}}:{}}})}catch(L){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(L)}`}),L}let A=await Oe(u,c,n,t);if((Q=u.memoryConfig)!=null&&Q.enabled){let{recall:L}=await import("./recall-IABRCSHY.js");A.recall=L(u,c,void 0,t)}console.log(`[tools] node ${n.id} loaded ${Object.keys(A).length}: ${Object.keys(A).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:n.id,tools:Object.keys(A)}});try{let L=Ce({model:g,system:o,messages:e,stopWhen:(()=>{var H;let F=!!A.readSkillRef?10:5,O=Number(((H=n.data)==null?void 0:H.max_steps)??F),V=Number.isFinite(O)?Math.max(1,Math.min(30,O)):F;return Ne(V)})(),...jt(h),...w?{providerOptions:w}:{},tools:A,onFinish:async T=>{var At,Mt;let F=T.text||"",O=T.reasoningText??((At=T.reasoning)==null?void 0:At.text)??"";if(console.log(`[reasoning] done: deltas=${_} chars=${P} result.reasoningText=${O.length} finishReason=${T.finishReason??"n/a"} reasoningTokens=${((Mt=T.usage)==null?void 0:Mt.reasoningTokens)??"n/a"}`),$&&x&&!R&&O&&s){R=!0;try{U(s,b.SERVER_REASONING_STREAM,O)}catch(he){console.warn("Failed to send finished reasoning over connection",he)}}let V={id:Te(),role:"assistant",type:"text",content:F,ts:Date.now()};a&&(u.setMessages?await u.setMessages(V):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),s&&$&&R&&!k&&(k=!0,U(s,b.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),a&&s&&U(s,b.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),p==null||p((n==null?void 0:n.id)||"llm_result",F),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(T)});let H=Date.now()-f,ge=C?C-f:void 0;l==null||l({type:"llm_telemetry",payload:{nodeId:n.id,totalLatency:H,timeToFirstToken:ge,model:T.response.modelId,usage:T.usage}}),l==null||l({type:"llm_result",payload:{result:T}})},onStepFinish:async T=>{let F=(O,V=200)=>{let H=typeof O=="string"?O:JSON.stringify(O);return H?H.length>V?`${H.slice(0,V)}\u2026(+${H.length-V})`:H:""};if(T.toolCalls&&T.toolCalls.length>0){for(let O of T.toolCalls)console.log(`[tools] \u2192 ${O.toolName}(${F(O.args??O.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${n.id}`,content:JSON.stringify(T.toolCalls)})}if(T.toolResults&&T.toolResults.length>0){for(let O of T.toolResults)console.log(`[tools] \u2190 ${O.toolName} \u2192 ${F(O.result??O.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${n.id}`,content:JSON.stringify(T.toolResults)})}await Ie(T,n,u,t)},experimental_onToolCallStart:T=>{var F;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(F=T==null?void 0:T.toolCall)==null?void 0:F.toolName,status:"start"}})},experimental_onToolCallFinish:T=>{var F;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(F=T==null?void 0:T.toolCall)==null?void 0:F.toolName,status:T!=null&&T.success?"success":"error"}})},onError:T=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),i(T)},onChunk:T=>{if(T.chunk.type==="reasoning-delta"){let O=T.chunk.text??T.chunk.delta??"";if(O&&(R=!0,_+=1,P+=O.length,_===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),$&&s&&O)try{U(s,b.SERVER_REASONING_STREAM,O)}catch(V){console.warn("Failed to send reasoning chunk over connection",V)}return}if(T.chunk.type==="text-delta"){if(C||(C=Date.now()),s&&$&&R&&!k){k=!0;try{U(s,b.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to send reasoning complete over connection",O)}}return}l==null||l({type:T.chunk.type,payload:{nodeId:n.id,chunk:T.chunk}});let F=`llm_chunk:${T.chunk.type}`;t==null||t({type:F,content:{...T}})}}),W=async()=>{let T="";for await(let F of L.fullStream)if(F.type==="text-delta"){if(T+=F.text,a&&s)try{U(s,b.SERVER_TEXT_STREAM,F.text)}catch(O){console.warn("Failed to send chunk over connection",O)}}else if(F.type==="finish-step"&&F.finishReason==="tool-calls"){if(a&&s&&T.trim())try{U(s,b.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to flush text segment over connection",O)}T=""}};await Promise.all([L,W()]),m(),t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"success"}})}catch(L){t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"error",error:String(L)}}),i(L)}})}function Fe(o,e,s,t){let n=!!(s&&s.length>0),a=!!t,p=n||a,d=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,u=l=>{let f=[],r="";if(a&&(r+=`[Attached files]
14
+ `:"")+r)}}return s}function se(o,e){var t,n,a,p,c,d;let s=[];if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let u of o.data.varMapping){let l=u.from;if(!l)continue;let f=!1;if(l==="images")f=!0;else{let r=l.indexOf(".");if(r!==-1){let m=l.substring(0,r),i=l.substring(r+1).split(".")[0],g=(p=(a=(n=e.flowData)==null?void 0:n.state)==null?void 0:a.nodes)==null?void 0:p.find(h=>h.id===m);if(g){let w=st(g).find(y=>y.name===i);(w==null?void 0:w.type)==="image"&&(f=!0)}}}if(f){let r=nt(l,{context:e.context||{},results:e.results||{},nodes:((d=(c=e.flowData)==null?void 0:c.state)==null?void 0:d.nodes)||[]});Array.isArray(r)&&s.push(...r)}}return s}var xe=v({"../tools/composioTool.ts":()=>import("./composioTool-TVURCFXP.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-NTDDXZZE.js"),"../tools/recall.ts":()=>import("./recall-IABRCSHY.js"),"../tools/skillTool.ts":()=>import("./skillTool-BSQFKZGK.js"),"../tools/tempTool.ts":()=>import("./tempTool-2RXAF56M.js"),"../tools/twitter.ts":()=>import("./twitter-OMDEG7T2.js"),"../tools/vectorize.ts":()=>import("./vectorize-UJXIDL2E.js")});var Re=v({});function Ot(o,e,s,t,n){var p;if(!((p=t.memoryConfig)!=null&&p.enabled)||!t.memoryConfig.toolCache||!s.cacheable||!e||typeof e.execute!="function")return e;let a=e.execute.bind(e);return e.execute=async(c,...d)=>{var r;if(!t.getContextIndex)return a(c,...d);let u=await xt(c),f=(await t.getContextIndex()).find(m=>{if(m.domain!=="tool")return!1;let i=Rt(m.meta);return i.toolName===o&&i.paramsHash===u});if(f){let m=await((r=t.getContext)==null?void 0:r.call(t,f.ref));if((m==null?void 0:m.data)!=null&&Rt(m.meta).truncated!==!0){n==null||n({type:"info:memory:cacheHit",content:{ref:m.ref,toolName:o}});try{return JSON.parse(m.data)}catch{return m.data}}}return a(c,...d)},e}async function Ie(o,e,s,t){var l,f;if(!((l=s.memoryConfig)!=null&&l.enabled)||!s.setContext||s.cycle==null)return;let n=o.toolCalls??[],a=o.toolResults??[];if(!n.length||!a.length)return;let p=new Map;for(let r of a)r!=null&&r.toolCallId&&p.set(r.toolCallId,r);let c=Array.isArray((f=e==null?void 0:e.data)==null?void 0:f.tools)?e.data.tools:[],d=new Map;for(let r of c)r&&typeof r.id=="string"&&d.set(r.id,r);let u=new Map;for(let r of Object.values(s.toolDefs??{}))r&&r.name&&u.set(r.name,r);for(let r of n){let m=r.toolCallId,i=r.toolName,g=p.get(m);if(!i||!g||i==="readSkillRef")continue;let h=r.args??r.input,w=g.result??g.output,y=!1,x="",C="tool",R="",k=u.get(i);k&&k.kind==="skill"&&(y=!0,x=`skill:${i}`,C="skill",R=`Skill instructions for ${i}`),x||(x=await Bt(i,h),R=Et(h,w));let _=d.get(i)??c.find($=>$.id===i),P=await xt(h),I=typeof w=="string"?w:JSON.stringify(w??null);await s.setContext({ref:x,domain:C,description:R,data:I,cycle:s.cycle,meta:JSON.stringify({toolName:i,paramsHash:P,cacheable:(_==null?void 0:_.cacheable)===!0})}),t==null||t({type:"info:memory:updated",content:{ref:x}})}}async function Oe(o,e,s,t){var f;let n=Array.isArray((f=s==null?void 0:s.data)==null?void 0:f.tools)?s.data.tools:[];if(n.length===0)return{};let a={},p=r=>{var x,C;let m=typeof(r==null?void 0:r.description)=="string"?r.description:"",i=r==null?void 0:r.inputSchema,g;try{let R=(i==null?void 0:i.shape)??(typeof((x=i==null?void 0:i._def)==null?void 0:x.shape)=="function"?i._def.shape():(C=i==null?void 0:i._def)==null?void 0:C.shape);R&&typeof R=="object"&&(g=R)}catch{}let h=g?Object.keys(g):[],w=m?`description="${m.length>120?m.slice(0,120)+"\u2026":m}"`:"description=(none)",y=h.length?`inputSchema={${h.join(", ")}}`:"inputSchema=(none)";return`${w} ${y}`},c=(()=>{let r=[],m=[],i=[],g=[];for(let w=0;w<n.length;w++){let y=n[w];!y||typeof y!="object"||typeof y.id!="string"?g.push(w):y.kind==="builtin"?r.push(y.id):y.kind==="skill"?i.push(y.id):y.kind==="http"||y.kind==="mcp"||y.kind==="composio"?m.push(y.id):g.push(w)}let h=[];return r.length&&h.push(`builtin[${r.join(", ")}]`),m.length&&h.push(`custom[${m.join(", ")}]`),i.length&&h.push(`skill[${i.join(", ")}]`),g.length&&h.push(`invalid@[${g.join(", ")}]`),h.join(" ")||"(none)"})();console.log(`[tools] node ${s.id} requested (${n.length}): ${c}`);let d=!1,u=async()=>{if(d&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},d=!0,o.toolDefs;try{let r=await Xt(o.env),m={};for(let i of r)i&&i.id&&(m[i.id]=i);o.toolDefs=m}catch(r){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(r)}`}),o.toolDefs=o.toolDefs||{}}return d=!0,o.toolDefs},l=[];for(let r=0;r<n.length;r++){let m=n[r];if(!m||typeof m!="object"||typeof m.id!="string"||m.kind!=="builtin"&&m.kind!=="http"&&m.kind!=="mcp"&&m.kind!=="composio"&&m.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${r}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let i=m;if(i.kind!=="builtin"){let h=(await u())[i.id];if(!h){console.error(`[tools] \u2717 custom '${i.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${i.id}' not found for this tenant`});continue}if(i.kind==="composio"){try{let y=await zt(h,o,e,t),x=Object.keys(y);for(let[C,R]of Object.entries(y))a[C]=Ot(C,R,i,o,t);console.log(`[tools] \u2713 composio '${i.id}' \u2192 ${x.length} tool(s)`)}catch(y){console.error(`[tools] \u2717 composio '${i.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${i.id}': ${String(y)}`})}continue}if(i.kind==="skill"){if(h.kind!=="skill"){console.error(`[tools] \u2717 skill '${i.id}': row is of kind '${h.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${i.id}' is not a skill`});continue}let y=h.name;if(a[y]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${y}' \u2014 builtin/other already registered, skipping skill '${i.id}'`});continue}try{a[y]=Yt(h,o,e,t),l.push(h);let x=typeof h.execution=="string"?JSON.parse(h.execution):h.execution||{},C=Array.isArray(x.references)?x.references.map(R=>R==null?void 0:R.name):[];console.log(`[tools] \u2713 skill '${i.id}' \u2192 '${y}' (refs: ${C.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:y,refCount:C.length,refs:C}})}catch(x){console.error(`[tools] \u2717 skill '${i.id}': ${String(x)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${i.id}': ${String(x)}`})}continue}let w=h.name;if(a[w]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${w}' \u2014 builtin already registered, skipping custom tool '${i.id}'`});continue}try{let y=Wt(h,o,e,t);a[w]=Ot(w,y,i,o,t),console.log(`[tools] \u2713 custom '${i.id}' \u2192 '${w}'`),console.log(`[tools] ${p(a[w])}`)}catch(y){console.error(`[tools] \u2717 custom '${i.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${i.id}': ${String(y)}`})}continue}if(!Jt[i.id]){console.error(`[tools] \u2717 builtin '${i.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${i.id}' not found in registry`});continue}try{let g;try{g=await xe(`../tools/${i.id}.ts`)}catch{g=await Re(`../tools/${i.id}.js`)}let h;if(g[i.id])h=g[i.id];else if(g.default)h=g.default;else if(g.create)h=g.create;else{let _=Object.values(g);_.length>0&&(h=_[0])}if(!h){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${i.id}'`});continue}let w,y,x={};if(i.params&&typeof i.params=="object"){if(typeof i.params.description=="string"?w=i.params.description:i.params.description!==void 0&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${i.id}' \u2014 must be a string`})),i.params.inputSchema!==void 0){let _=i.params.inputSchema;typeof _=="object"&&(typeof _.safeParse=="function"||_._def)?y=_:typeof _=="object"&&_!==null&&_.type==="object"&&_.properties?(y=Kt(_),y||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${i.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${i.id}' \u2014 must be a Zod schema or JSON Schema object`})}i.params.defaults!==void 0?typeof i.params.defaults=="object"&&i.params.defaults!==null&&!Array.isArray(i.params.defaults)?x=i.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${i.id}' \u2014 must be an object`}),x={}):i.params.source!==void 0||i.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${i.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),x={}):x={}}let C=h(o,e,x,t);w&&C&&typeof C=="object"&&(C.description=w),y&&C&&typeof C=="object"&&(C.inputSchema=y),a[i.id]=Ot(i.id,C,i,o,t);let R=[];w&&R.push("description"),y&&R.push("inputSchema"),Object.keys(x).length&&R.push(`defaults(${Object.keys(x).join(",")})`);let k=R.length?` [overrides: ${R.join(", ")}]`:"";console.log(`[tools] \u2713 builtin '${i.id}'${k}`),console.log(`[tools] ${p(C)}`)}catch(g){console.error(`[tools] \u2717 builtin '${i.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${i.id}': ${String(g)}`});continue}}if(l.length>0)if(a.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{a.readSkillRef=Gt(o,l,e,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${l.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:l.map(r=>r.name)}})}catch(r){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(r)}`)}return a}async function _t(o,e,s,t,n,a,p){var P,I,$,A,j;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=!1;try{let N=(P=s.flowData)==null?void 0:P.state;if(N&&N.edges&&N.nodes){let D=N.edges.filter(M=>M.source===e.id);if(D.length>0){let M=N.nodes.find(q=>q.id===D[0].target);M&&M.type==="answerNode"&&(c=!0)}}}catch(N){console.error("Error determining next node for streaming:",N)}let d=K(e.data.template,e,s,t,{sessionEnv:o});(!d||!d.trim())&&(d="Answer straight forward to the user, dont offer any other option to continue");let u=d,l="";if((I=o.memoryConfig)!=null&&I.enabled){let N=await(($=o.getContextIndex)==null?void 0:$.call(o))??[];l=Zt(N),d+=l}let f=K(e.data.user_template||"",e,s,t,{sessionEnv:o}),r=N=>N&&Object.fromEntries(Object.keys(N).map(D=>[D,"[redacted]"])),m=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:r(o.secrets),userAuth:r(o.userAuth)}:o,i=K(e.data.template,e,s,void 0,{sessionEnv:m})||u;i+=l;let g=K(e.data.user_template||"",e,s,void 0,{sessionEnv:m});t==null||t({type:`info:llmNodeRunner:${e.id}`,content:i}),t==null||t({type:`info:llmNodeRunner:${e.id}`,content:g});let h=(A=e==null?void 0:e.data)==null?void 0:A.window_size,w=Number(h);(!Number.isInteger(w)||w<=0)&&(w=5);let y=se(e,s),x=oe(e,s),R=(await((j=o.getMessages)==null?void 0:j.call(o))??[]).slice(-w),k=R.filter(N=>N&&typeof N.role=="string"&&typeof N.content=="string");k.length!==R.length&&console.warn(`Filtered ${R.length-k.length} invalid messages from history`);let _=Fe(k,f,y,x);await _e(d,_,o.conn,t,e,c,n,s,a,o,p)}async function _e(o,e,s,t,n,a,p,c,d,u,l){var r;let f=Date.now();if(!((r=u.env)!=null&&r.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(m,i)=>{var j,N,D,M,q,B,Q;let g,h={},w,y="none",x=!1,C,R=!1,k=!1,_=0,P=0,I=(j=n==null?void 0:n.data)==null?void 0:j.sendReasoning,$=I!==!1;try{let L=(N=n==null?void 0:n.data)==null?void 0:N.model,W=Array.isArray(L)?L[0]:L||"gpt_5_nano",T=Lt(n==null?void 0:n.data),F=await at(W,u,T);if(!F)throw new Error(`Model '${W}' not found in registry`);g=F.modelHandle,h=F.effectiveParams||{},y=F.reasoning.kind;let O=Vt(F.reasoning,(D=n==null?void 0:n.data)==null?void 0:D.reasoningEffort);x=$&&Ht(F.reasoning);let V=typeof((M=n==null?void 0:n.data)==null?void 0:M.reasoningMaxTokens)=="number"?n.data.reasoningMaxTokens:void 0;w=qt(F.provider,{effort:O,exposeReasoning:x,maxTokens:V}),O&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:O})),console.log(`[reasoning] ${JSON.stringify({model:W,provider:F.provider,capability:F.reasoning,requestedEffort:((q=n==null?void 0:n.data)==null?void 0:q.reasoningEffort)??null,resolvedEffort:O??null,sendReasoning:$,exposeReasoning:x,providerOptions:w??null},null,2)}`);for(let H of F.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:H});t==null||t({type:"info:llmNodeRunner:model",content:W}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(B=n==null?void 0:n.data)!=null&&B.generationPreset?{preset:n.data.generationPreset}:{},...h,...y!=="none"?{reasoning:y,configuredSendReasoning:I,sendReasoning:$,exposeReasoning:x,...O?{effort:O}:{}}:{}}})}catch(L){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(L)}`}),L}let A=await Oe(u,c,n,t);if((Q=u.memoryConfig)!=null&&Q.enabled){let{recall:L}=await import("./recall-IABRCSHY.js");A.recall=L(u,c,void 0,t)}console.log(`[tools] node ${n.id} loaded ${Object.keys(A).length}: ${Object.keys(A).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:n.id,tools:Object.keys(A)}});try{let L=Ce({model:g,system:o,messages:e,stopWhen:(()=>{var H;let F=!!A.readSkillRef?10:5,O=Number(((H=n.data)==null?void 0:H.max_steps)??F),V=Number.isFinite(O)?Math.max(1,Math.min(30,O)):F;return Ne(V)})(),...jt(h),...w?{providerOptions:w}:{},tools:A,onFinish:async T=>{var At,Mt;let F=T.text||"",O=T.reasoningText??((At=T.reasoning)==null?void 0:At.text)??"";if(console.log(`[reasoning] done: deltas=${_} chars=${P} result.reasoningText=${O.length} finishReason=${T.finishReason??"n/a"} reasoningTokens=${((Mt=T.usage)==null?void 0:Mt.reasoningTokens)??"n/a"}`),$&&x&&!R&&O&&s){R=!0;try{U(s,b.SERVER_REASONING_STREAM,O)}catch(he){console.warn("Failed to send finished reasoning over connection",he)}}let V={id:Te(),role:"assistant",type:"text",content:F,ts:Date.now()};a&&(u.setMessages?await u.setMessages(V):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),s&&$&&R&&!k&&(k=!0,U(s,b.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),a&&s&&U(s,b.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),p==null||p((n==null?void 0:n.id)||"llm_result",F),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(T)});let H=Date.now()-f,ge=C?C-f:void 0;l==null||l({type:"llm_telemetry",payload:{nodeId:n.id,totalLatency:H,timeToFirstToken:ge,model:T.response.modelId,usage:T.usage}}),l==null||l({type:"llm_result",payload:{result:T}})},onStepFinish:async T=>{let F=(O,V=200)=>{let H=typeof O=="string"?O:JSON.stringify(O);return H?H.length>V?`${H.slice(0,V)}\u2026(+${H.length-V})`:H:""};if(T.toolCalls&&T.toolCalls.length>0){for(let O of T.toolCalls)console.log(`[tools] \u2192 ${O.toolName}(${F(O.args??O.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${n.id}`,content:JSON.stringify(T.toolCalls)})}if(T.toolResults&&T.toolResults.length>0){for(let O of T.toolResults)console.log(`[tools] \u2190 ${O.toolName} \u2192 ${F(O.result??O.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${n.id}`,content:JSON.stringify(T.toolResults)})}await Ie(T,n,u,t)},experimental_onToolCallStart:T=>{var F;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(F=T==null?void 0:T.toolCall)==null?void 0:F.toolName,status:"start"}})},experimental_onToolCallFinish:T=>{var F,O;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(F=T==null?void 0:T.toolCall)==null?void 0:F.toolName,status:((O=T==null?void 0:T.toolOutput)==null?void 0:O.type)==="tool-error"?"error":"success"}})},onError:T=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),i(T)},onChunk:T=>{if(T.chunk.type==="reasoning-delta"){let O=T.chunk.text??T.chunk.delta??"";if(O&&(R=!0,_+=1,P+=O.length,_===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),$&&s&&O)try{U(s,b.SERVER_REASONING_STREAM,O)}catch(V){console.warn("Failed to send reasoning chunk over connection",V)}return}if(T.chunk.type==="text-delta"){if(C||(C=Date.now()),s&&$&&R&&!k){k=!0;try{U(s,b.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to send reasoning complete over connection",O)}}return}l==null||l({type:T.chunk.type,payload:{nodeId:n.id,chunk:T.chunk}});let F=`llm_chunk:${T.chunk.type}`;t==null||t({type:F,content:{...T}})}}),W=async()=>{let T="";for await(let F of L.fullStream)if(F.type==="text-delta"){if(T+=F.text,a&&s)try{U(s,b.SERVER_TEXT_STREAM,F.text)}catch(O){console.warn("Failed to send chunk over connection",O)}}else if(F.type==="finish-step"&&F.finishReason==="tool-calls"){if(a&&s&&T.trim())try{U(s,b.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(O){console.warn("Failed to flush text segment over connection",O)}T=""}};await Promise.all([L,W()]),m(),t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"success"}})}catch(L){t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"error",error:String(L)}}),i(L)}})}function Fe(o,e,s,t){let n=!!(s&&s.length>0),a=!!t,p=n||a,d=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,u=l=>{let f=[],r="";if(a&&(r+=`[Attached files]
15
15
  ${t}
16
16
  [End of attached files]
17
17
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hugex/ai",
3
- "version": "2.9.5",
3
+ "version": "2.9.6",
4
4
  "description": "Ora AI Agent Framework",
5
5
  "author": "a@hugex.co",
6
6
  "license": "SEE LICENSE IN LICENSE",