@hugex/ai 2.9.8 → 2.9.10
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/common/types/trigger-types.d.ts +61 -35
- package/dist/index.js +10 -10
- package/dist/server/api/triggers.d.ts +1 -6
- package/dist/server/core/AgentDO.d.ts +3 -3
- package/dist/server/triggers/dispatch.d.ts +4 -27
- package/dist/server/triggers/hookAdapters.d.ts +2 -2
- package/dist/server/utils/oraTriggers.d.ts +11 -24
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
* QStash
|
|
2
|
+
* Trigger Core — shared execution contract.
|
|
3
|
+
* Provider details (QStash, webhooks, etc.) stay outside this surface.
|
|
4
4
|
*/
|
|
5
5
|
export type FlowInputType = 'string' | 'number' | 'boolean' | 'json';
|
|
6
6
|
/** A declarative input declared on the Start node and supplied by a trigger. */
|
|
@@ -13,48 +13,74 @@ export interface FlowInputDef {
|
|
|
13
13
|
default?: string | number | boolean | null;
|
|
14
14
|
}
|
|
15
15
|
export type FlowInputValues = Record<string, unknown>;
|
|
16
|
-
/**
|
|
17
|
-
export type
|
|
16
|
+
/** Kind of persistent trigger. */
|
|
17
|
+
export type TriggerKind = 'schedule' | 'webhook';
|
|
18
|
+
/** How a trigger activation was requested. Manual chat turns are not activators. */
|
|
19
|
+
export type InvocationMode = 'automatic' | 'run_now' | 'test';
|
|
20
|
+
export type SessionPolicy = 'owner';
|
|
21
|
+
export type OverlapPolicy = 'queue';
|
|
18
22
|
/** Lifecycle of a single run. Mirrored by its notification record. */
|
|
19
23
|
export type RunStatus = 'queued' | 'running' | 'succeeded' | 'failed' | 'skipped';
|
|
24
|
+
/** Functional config for a schedule trigger. */
|
|
25
|
+
export interface ScheduleSourceConfig {
|
|
26
|
+
cron: string;
|
|
27
|
+
timezone: string;
|
|
28
|
+
}
|
|
29
|
+
/** Functional config for a webhook trigger. */
|
|
30
|
+
export interface WebhookSourceConfig {
|
|
31
|
+
contentType: 'application/json';
|
|
32
|
+
}
|
|
33
|
+
export interface TriggerSourceConfigMap {
|
|
34
|
+
schedule: ScheduleSourceConfig;
|
|
35
|
+
webhook: WebhookSourceConfig;
|
|
36
|
+
}
|
|
37
|
+
export type TriggerSourceConfig<K extends TriggerKind = TriggerKind> = TriggerSourceConfigMap[K];
|
|
38
|
+
export type WebhookInputBinding = {
|
|
39
|
+
source: 'fixed';
|
|
40
|
+
value: unknown;
|
|
41
|
+
} | {
|
|
42
|
+
source: 'body';
|
|
43
|
+
pointer: string;
|
|
44
|
+
};
|
|
45
|
+
export type WebhookInputMapping = Record<string, WebhookInputBinding>;
|
|
46
|
+
/** Adapter-declared capabilities; UI and admin routes derive actions from these. */
|
|
47
|
+
export interface TriggerSourceCapabilities {
|
|
48
|
+
canPause: boolean;
|
|
49
|
+
canRunNow: boolean;
|
|
50
|
+
canTest: boolean;
|
|
51
|
+
canResync: boolean;
|
|
52
|
+
canRotateSecret: boolean;
|
|
53
|
+
exposesDestination: boolean;
|
|
54
|
+
}
|
|
55
|
+
export interface TriggerAllowedActions {
|
|
56
|
+
pause: boolean;
|
|
57
|
+
resume: boolean;
|
|
58
|
+
runNow: boolean;
|
|
59
|
+
test: boolean;
|
|
60
|
+
resync: boolean;
|
|
61
|
+
rotateSecret: boolean;
|
|
62
|
+
delete: boolean;
|
|
63
|
+
edit: boolean;
|
|
64
|
+
}
|
|
20
65
|
/**
|
|
21
|
-
* Normalized unit of work handed to
|
|
22
|
-
*
|
|
23
|
-
* (QStash retries, provider replays) collapse into a single execution.
|
|
66
|
+
* Normalized unit of work handed to the tenant runtime and AgentDO.
|
|
67
|
+
* One activation produces at most one effective run.
|
|
24
68
|
*/
|
|
25
|
-
export interface
|
|
69
|
+
export interface TriggerActivation {
|
|
70
|
+
activationId: string;
|
|
26
71
|
triggerId: string;
|
|
27
|
-
|
|
28
|
-
|
|
72
|
+
triggerKind: TriggerKind;
|
|
73
|
+
invocationMode: InvocationMode;
|
|
74
|
+
tenant: string;
|
|
29
75
|
flowId: string;
|
|
30
|
-
|
|
31
|
-
userId: string;
|
|
32
|
-
/** `flowId::sessionId` addresses the DO; schedules and hooks use `sessionId === userId`. */
|
|
76
|
+
runAsUserId: string;
|
|
33
77
|
sessionId: string;
|
|
34
78
|
runId: string;
|
|
35
|
-
scheduleId?: string;
|
|
36
79
|
inputs: FlowInputValues;
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
/** Human label used for the synthesized chat turn and the notification title. */
|
|
80
|
+
externalDeliveryId?: string;
|
|
81
|
+
correlationKey?: string;
|
|
40
82
|
label?: string;
|
|
41
|
-
/** Single-use id of the signed gateway request; the agent rejects a repeat of it. */
|
|
42
83
|
nonce?: string;
|
|
43
84
|
}
|
|
44
|
-
/**
|
|
45
|
-
|
|
46
|
-
* tenant and already registered `runId`, so the tenant only has to authenticate the request and
|
|
47
|
-
* persist the work in the right queue.
|
|
48
|
-
*/
|
|
49
|
-
export interface TriggerDispatchRequest {
|
|
50
|
-
tenant: string;
|
|
51
|
-
flowId: string;
|
|
52
|
-
userId: string;
|
|
53
|
-
sessionId?: string;
|
|
54
|
-
runId: string;
|
|
55
|
-
scheduleId?: string;
|
|
56
|
-
triggerType: TriggerType;
|
|
57
|
-
inputs?: FlowInputValues;
|
|
58
|
-
idempotencyKey?: string;
|
|
59
|
-
label?: string;
|
|
60
|
-
}
|
|
85
|
+
/** Signed hx-ora → tenant dispatch payload. */
|
|
86
|
+
export type TriggerDispatchRequest = TriggerActivation;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as dt,b as
|
|
1
|
+
import{a as dt,b as Qt,c as vt,d as te}from"./chunk-TK4TFAI5.js";import{a as oe,b as se}from"./chunk-4FUIFBZO.js";import{a as ee}from"./chunk-YHXUBVN2.js";import{a as Bo,b as it,c as Yo,d as at,e as wt,f as Jt,g as Xt,h as Gt,i as zt,j as Wt,k as xt,l as Bt}from"./chunk-57TCP6J4.js";import{a as P,b as rt,c as Po,d as S,e as jt,f as Zt,g as So,h as vo}from"./chunk-76OHKISD.js";import{a as B,b as Mo,c as Y,d as bt,e as Lt,f as Qo,g as Zo,h as ct,i as lt,j as Yt}from"./chunk-C2HAGFXJ.js";import{a as Do,b as Uo,c as bo,d as Lo,e as jo,f as Ho,g as Ht,h as Eo,i as Et,j as qo,k as Vo,l as Ko,m as Jo,n as Xo,o as Go,p as zo,q as Wo,r as qt,s as Vt,t as Kt}from"./chunk-GRZ6ZRHM.js";import{a as Co}from"./chunk-RYHQGPX5.js";import{a as Ao}from"./chunk-R6EKV3WR.js";import{a as $o}from"./chunk-6HY7QUMP.js";import{a as _o,b as Oo}from"./chunk-V6JSMX5A.js";import{a as K,b as W,c as ko,d as Ut,e as Fo}from"./chunk-G3SGJ7XJ.js";import{a as St}from"./chunk-4WAWR4LB.js";import{a as nt}from"./chunk-U56YWPSI.js";import{a as st}from"./chunk-3TXHFKDN.js";import{Agent as po}from"agents";import{nanoid as fo}from"nanoid";var U=(o,e,s)=>{o.send(e+"::"+s)};async function We(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 ne(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 J(o){return o.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function ut(o){o.sql`DELETE FROM messages`}async function Be(o){o.sql`CREATE TABLE IF NOT EXISTS context (
|
|
2
2
|
ref TEXT PRIMARY KEY,
|
|
3
3
|
domain TEXT NOT NULL,
|
|
4
4
|
description TEXT NOT NULL,
|
|
@@ -6,7 +6,7 @@ import{a as dt,b as Zt,c as te,d as ee}from"./chunk-TK4TFAI5.js";import{a as se,
|
|
|
6
6
|
cycle INTEGER NOT NULL,
|
|
7
7
|
meta TEXT,
|
|
8
8
|
ts INTEGER NOT NULL
|
|
9
|
-
)`}async function
|
|
9
|
+
)`}async function re(o,e){let s=e.data??null,t=s!=null?Gt(s):{data:null,truncated:!1},n=t.truncated?Bt(e.meta,{truncated:!0}):e.meta??null,r=e.ts??Date.now();o.sql`INSERT INTO context (ref, domain, description, data, cycle, meta, ts)
|
|
10
10
|
VALUES (${e.ref}, ${e.domain}, ${e.description}, ${t.data}, ${e.cycle}, ${n}, ${r})
|
|
11
11
|
ON CONFLICT(ref) DO UPDATE SET
|
|
12
12
|
domain = excluded.domain,
|
|
@@ -14,7 +14,7 @@ import{a as dt,b as Zt,c as te,d as ee}from"./chunk-TK4TFAI5.js";import{a as se,
|
|
|
14
14
|
data = excluded.data,
|
|
15
15
|
cycle = excluded.cycle,
|
|
16
16
|
meta = excluded.meta,
|
|
17
|
-
ts = excluded.ts`}async function pt(o){return o.sql`SELECT ref, domain, description, cycle, meta, ts FROM context ORDER BY ts ASC`}async function 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
|
|
17
|
+
ts = excluded.ts`}async function pt(o){return o.sql`SELECT ref, domain, description, cycle, meta, ts FROM context ORDER BY ts ASC`}async function 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 ce(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 mt(o){o.sql`DELETE FROM context`}async function de(o){await We(o),await Be(o)}function Rt(o){return{"Content-Type":"application/json",Authorization:o.HX_API_KEY}}function gt(o){return!!(o!=null&&o.HX_ORA_URL)&&!!(o!=null&&o.HX_API_KEY)}async function It(o,e){if(!gt(o))return null;let s=await fetch(`${o.HX_ORA_URL}/internal/runs`,{method:"POST",headers:Rt(o),body:JSON.stringify(e)});return s.ok?await s.json():(console.error("[oraTriggers] createRun failed",s.status,await s.text().catch(()=>"")),null)}async function ue(o,e){if(!gt(o))return{claimed:!0};let s=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/claim`,{method:"POST",headers:Rt(o)});if(!s.ok){let t=await s.text().catch(()=>"");throw new Error(`claimRun ${e} failed with ${s.status}: ${t}`)}return await s.json()}async function yt(o,e,s,t=3){if(!gt(o))return!0;for(let n=1;n<=t;n++){try{let r=await fetch(`${o.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/complete`,{method:"POST",headers:Rt(o),body:JSON.stringify(s)});if(r.ok)return!0;if(r.status===404)return console.error(`[oraTriggers] completeRun ${e} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${e} attempt ${n} failed with ${r.status}`)}catch(r){console.warn(`[oraTriggers] completeRun ${e} attempt ${n} threw`,r)}n<t&&await new Promise(r=>setTimeout(r,250*n))}return console.error(`[oraTriggers] completeRun ${e} exhausted ${t} attempts; hx-ora will time the run out`),!1}async function pe(o,e){if(!gt(o))return Promise.resolve();try{return await It(o,e)}catch(s){return console.error("[oraTriggers] recordRun failed",s),null}}var Tt=Object.freeze({});async function ht(o,e){if(!e)return Tt;if(o.HX_ORA_URL&&o.HX_API_KEY)try{let n=await fetch(`${o.HX_ORA_URL}/internal/secrets`,{headers:{Authorization:o.HX_API_KEY}});if(n.ok){let r=await n.json();if(r.secrets)return Object.freeze(r.secrets)}else console.warn(`[secrets] API failed with status ${n.status}, falling back to KV`)}catch(n){console.error("[secrets] API request failed, falling back to KV",n)}let s=o.ORA_SECRETS;if(!s)return Tt;let t=`${e}:`;try{let n=await s.list({prefix:t,limit:1e3});n.list_complete===!1&&console.warn(`[secrets] tenant=${e} exceeded list page; truncating to first 1000 keys`);let r=await Promise.all(n.keys.map(async c=>{let p=await s.get(c.name);return p!==null?[c.name.slice(t.length),p]:null})),i={};for(let c of r){if(!c)continue;let[p,f]=c;p&&(i[p]=f)}return Object.freeze(i)}catch(n){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,err:n}),Tt}}import{nanoid as is}from"nanoid";function v(o){var n,r;let e=(n=o==null?void 0:o.flowData)==null?void 0:n.state,t=((e==null?void 0:e.nodes)??((r=o==null?void 0:o.flowData)==null?void 0:r.nodes)??[]).find(i=>i.type==="startNode");return t==null?void 0:t.data}async function fe(o,e){return typeof e.cycle=="number"&&Number.isFinite(e.cycle)?e.cycle+1:await le(o)+1}function me(o,e,s,t,n){let r=at(v(s));return{...e,memoryConfig:r,cycle:t,setContext:async c=>{await re(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=>ce(o,c)}}import{nanoid as co}from"nanoid";async function ge(o,e){return o.length?!e||!e.HX_ORA_URL||!e.HX_API_KEY?(console.error("extractDocuments: missing HX_ORA_URL or HX_API_KEY"),o.map(t=>({name:t.name,text:""}))):await Promise.all(o.map(async t=>{try{let n=await fetch(`${e.HX_ORA_URL}/internal/files/extract`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e.HX_API_KEY},body:JSON.stringify(t)});if(!n.ok)return console.error(`extractDocuments: ${t.name} failed ${n.status}`),{name:t.name,text:""};let r=await n.json();return{name:t.name,text:r.text||""}}catch(n){return console.error(`extractDocuments: ${t.name} threw`,n),{name:t.name,text:""}}})):[]}async function Nt(o,e,s,t,n,r,i){var c,p,f;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});try{let u=await((c=o.getMessages)==null?void 0:c.call(o))??[],{flowId:m,chatId:l,tenant:d}=s.flowData,a=((p=u[u.length-1])==null?void 0:p.type)==="text"?u[u.length-1].content:"NO-TEXT";i==null||i({type:"answer_node",payload:{userMessage:(f=s==null?void 0:s.context)==null?void 0:f.user_input,answer:a}})}catch(u){console.error("answerNodeRunner: failed to emit answer telemetry:",u),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(u)}})}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 G(o,e,s,t,n){var c,p,f;let r=(n==null?void 0:n.callerTag)??"llmNodeRunner",i=(n==null?void 0:n.serializeNonStrings)??!1;try{return Yt(o,e,{context:s.context??{},results:s.results??{},nodes:((p=(c=s.flowData)==null?void 0:c.state)==null?void 0:p.nodes)??[],secrets:(f=n==null?void 0:n.sessionEnv)==null?void 0:f.secrets},{callerTag:r,serializeNonStrings:i,onError:u=>{t==null||t({type:`error:${r}`,content:u})}})}catch(u){return console.error(u),"error"}}var ye="[redacted]",Ct=(o,e,s,t,n)=>G(o,e,s,n,{callerTag:"apiNodeRunner",serializeNonStrings:!0,sessionEnv:t});async function At(o,e,s,t,n,r,i){var f,u,m,l,d,a;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=null,p=Date.now();try{console.log("[apiNodeRunner] context keys:",Object.keys(s.context||{})),console.log("[apiNodeRunner] results keys:",Object.keys(s.results||{}));let y=((f=e.data)==null?void 0:f.url)||"",w=Ct(y,e,s,o,t);if(console.log("[apiNodeRunner] resolved url:",dt(y)?Qt(w):w),!w){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 h=(((u=e.data)==null?void 0:u.method)||"GET").toUpperCase();console.log("[apiNodeRunner] method:",h);let g=((m=e.data)==null?void 0:m.headers)||{},x={},I={};for(let D in g)if(Object.prototype.hasOwnProperty.call(g,D)){let q=String(g[D]??"");I[D]=dt(q),x[D]=Ct(q,e,s,o,t)}let R,$=!1;if(h!=="GET"&&h!=="HEAD"&&((l=e.data)==null?void 0:l.body)!==void 0){let D=typeof e.data.body=="string"?e.data.body:JSON.stringify(e.data.body);$=dt(D),R=Ct(D,e,s,o,t),!x["Content-Type"]&&!x["content-type"]&&(x["Content-Type"]="application/json")}let O={};for(let D in x)O[D]=I[D]?ye:x[D];console.log("[apiNodeRunner] headers:",JSON.stringify(O)),console.log("[apiNodeRunner] body:",$?ye:R),t==null||t({type:"info:apiNodeRunner",content:`${h} ${w}`});let M=Number((d=e.data)==null?void 0:d.timeoutMs),b=new AbortController,F=Number.isFinite(M)&&M>0?setTimeout(()=>b.abort(),M):null,k;try{console.log("[apiNodeRunner] fetching..."),k=await fetch(w,{method:h,headers:x,body:R,signal:b.signal}),console.log("[apiNodeRunner] fetch returned status:",k.status)}finally{F&&clearTimeout(F)}let A=k.headers.get("content-type")||"";console.log("[apiNodeRunner] content-type:",A);let N;A.includes("application/json")?N=await k.json():N=await k.text(),console.log("[apiNodeRunner] payload preview:",typeof N=="string"?N.slice(0,200):JSON.stringify(N).slice(0,200)),c={ok:k.ok,status:k.status,data:N};let L=Date.now()-p;i==null||i({type:"api_call",payload:{nodeId:e.id,url:w,method:h,status:k.status,latencyMs:L}}),t==null||t({type:"info:apiNodeRunner",content:`Response ${k.status} (${L}ms)`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}catch(y){console.error("Error processing ApiNode:",y),t==null||t({type:"error:apiNodeRunner",content:`API node execution failed: ${y}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(y)}})}finally{console.log("[apiNodeRunner] final result:",(a=JSON.stringify(c))==null?void 0:a.slice(0,300)),n==null||n(e.id,c)}}import{generateObject as Ye}from"ai";import{z as he}from"zod";async function _t(o,e,s,t,n,r,i){var y,w,h;t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=(s==null?void 0:s.context)??{},p=String(((y=e==null?void 0:e.data)==null?void 0:y.input_variable)||"user_input").trim(),f=(c==null?void 0:c[p])??"",u=Array.isArray((w=e==null?void 0:e.data)==null?void 0:w.items)?e.data.items:[];if(u.length===0){t==null||t({type:"error:classifier",content:"ClassifierNode has no items to classify."});return}let m=String((h=u[u.length-1])==null?void 0:h.id);if(!f||String(f).trim().length===0){t==null||t({type:"warning:classifier",content:"No input for classification \u2014 falling back to last item."}),n==null||n(e.id,{classification:m}),s.context=s.context||{},s.context.classified_id=m,r==null||r(s);return}let d=`You are a precise classifier. Given a short user message, identify the category that best matches from the provided list.
|
|
18
18
|
If the message is ambiguous or none clearly matches, choose the LAST category in the list.
|
|
19
19
|
|
|
20
20
|
Categories:
|
|
@@ -25,18 +25,18 @@ ${u.map(g=>{let x=g.keywords??g["keywords/topics"]??"",I=Array.isArray(x)?x.join
|
|
|
25
25
|
`,a=`User message:
|
|
26
26
|
"""${String(f).trim()}"""
|
|
27
27
|
|
|
28
|
-
Select the best matching category id.`;try{let g=Date.now(),x=u.map(k=>String(k.id)),I="gpt_4_1_mini",R=await it(I,o);if(!R)throw new Error(`Model '${I}' not found in registry`);let{modelHandle:$,effectiveParams:O}=R,M=await Ye({model:$,messages:[{role:"system",content:d},{role:"user",content:a}],schema:
|
|
28
|
+
Select the best matching category id.`;try{let g=Date.now(),x=u.map(k=>String(k.id)),I="gpt_4_1_mini",R=await it(I,o);if(!R)throw new Error(`Model '${I}' not found in registry`);let{modelHandle:$,effectiveParams:O}=R,M=await Ye({model:$,messages:[{role:"system",content:d},{role:"user",content:a}],schema:he.object({classification:he.enum(x).describe("The id of the best matching category")}),temperature:O.temperature??0}),b=Date.now()-g,F=M.object.classification;i==null||i({type:"class_telemetry",payload:{nodeId:e.id,totalLatency:b,model:M.response.modelId,usage:M.usage,options:x}}),i==null||i({type:"class_result",payload:{result:M}}),n==null||n(e.id,{classification:F}),s.context=s.context||{},s.context.classified_id=F,r==null||r(s),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}catch(g){t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(g)}})}}import{stepCountIs as Se,streamText as ve}from"ai";import{nanoid as to}from"nanoid";import"zod";function we(o,e){var t,n,r,i,c,p;let s="";if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let f of o.data.varMapping){let u=f.from;if(!u)continue;let m=!1;if(u==="files"||u==="file_content")m=!0;else{let l=u.indexOf(".");if(l!==-1){let d=u.substring(0,l),a=u.substring(l+1).split(".")[0],y=(i=(r=(n=e.flowData)==null?void 0:n.state)==null?void 0:r.nodes)==null?void 0:i.find(w=>w.id===d);if(y){let h=ct(y).find(g=>g.name===a);(h==null?void 0:h.type)==="file"&&(m=!0)}}}if(m){let l=lt(u,{context:e.context||{},results:e.results||{},nodes:((p=(c=e.flowData)==null?void 0:c.state)==null?void 0:p.nodes)||[]});typeof l=="string"&&l.trim()&&(s+=(s?`
|
|
29
29
|
|
|
30
|
-
`:"")+l)}}return s}function Re(o,e){var t,n,r,i,c,p;let s=[];if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let f of o.data.varMapping){let u=f.from;if(!u)continue;let m=!1;if(u==="images")m=!0;else{let l=u.indexOf(".");if(l!==-1){let d=u.substring(0,l),a=u.substring(l+1).split(".")[0],y=(i=(r=(n=e.flowData)==null?void 0:n.state)==null?void 0:r.nodes)==null?void 0:i.find(w=>w.id===d);if(y){let h=ct(y).find(g=>g.name===a);(h==null?void 0:h.type)==="image"&&(m=!0)}}}if(m){let l=lt(u,{context:e.context||{},results:e.results||{},nodes:((p=(c=e.flowData)==null?void 0:c.state)==null?void 0:p.nodes)||[]});Array.isArray(l)&&s.push(...l)}}return s}var Qe=st({"../tools/composioTool.ts":()=>import("./composioTool-44B637WM.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-SFK4FG4Q.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 Ze=st({});function $t(o,e,s,t,n){var i;if(!((i=t.memoryConfig)!=null&&i.enabled)||!t.memoryConfig.toolCache||!s.cacheable||!e||typeof e.execute!="function")return e;let r=e.execute.bind(e);return e.execute=async(c,...p)=>{var l;if(!t.getContextIndex)return r(c,...p);let f=await xt(c),m=(await t.getContextIndex()).find(d=>{if(d.domain!=="tool")return!1;let a=Rt(d.meta);return a.toolName===o&&a.paramsHash===f});if(m){let d=await((l=t.getContext)==null?void 0:l.call(t,m.ref));if((d==null?void 0:d.data)!=null&&Rt(d.meta).truncated!==!0){n==null||n({type:"info:memory:cacheHit",content:{ref:d.ref,toolName:o}});try{return JSON.parse(d.data)}catch{return d.data}}}return r(c,...p)},e}async function eo(o,e,s,t){var u,m;if(!((u=s.memoryConfig)!=null&&u.enabled)||!s.setContext||s.cycle==null)return;let n=o.toolCalls??[],r=o.toolResults??[];if(!n.length||!r.length)return;let i=new Map;for(let l of r)l!=null&&l.toolCallId&&i.set(l.toolCallId,l);let c=Array.isArray((m=e==null?void 0:e.data)==null?void 0:m.tools)?e.data.tools:[],p=new Map;for(let l of c)l&&typeof l.id=="string"&&p.set(l.id,l);let f=new Map;for(let l of Object.values(s.toolDefs??{}))l&&l.name&&f.set(l.name,l);for(let l of n){let d=l.toolCallId,a=l.toolName,y=i.get(d);if(!a||!y||a==="readSkillRef")continue;let w=l.args??l.input,h=y.result??y.output,g=!1,x="",I="tool",R="",$=f.get(a);$&&$.kind==="skill"&&(g=!0,x=`skill:${a}`,I="skill",R=`Skill instructions for ${a}`),x||(x=await Gt(a,w),R=Xt(w,h));let O=p.get(a)??c.find(F=>F.id===a),M=await xt(w),b=typeof h=="string"?h:JSON.stringify(h??null);await s.setContext({ref:x,domain:I,description:R,data:b,cycle:s.cycle,meta:JSON.stringify({toolName:a,paramsHash:M,cacheable:(O==null?void 0:O.cacheable)===!0})}),t==null||t({type:"info:memory:updated",content:{ref:x}})}}async function oo(o,e,s,t){var m;let n=Array.isArray((m=s==null?void 0:s.data)==null?void 0:m.tools)?s.data.tools:[];if(n.length===0)return{};let r={},i=l=>{var x,I;let d=typeof(l==null?void 0:l.description)=="string"?l.description:"",a=l==null?void 0:l.inputSchema,y;try{let R=(a==null?void 0:a.shape)??(typeof((x=a==null?void 0:a._def)==null?void 0:x.shape)=="function"?a._def.shape():(I=a==null?void 0:a._def)==null?void 0:I.shape);R&&typeof R=="object"&&(y=R)}catch{}let w=y?Object.keys(y):[],h=d?`description="${d.length>120?d.slice(0,120)+"\u2026":d}"`:"description=(none)",g=w.length?`inputSchema={${w.join(", ")}}`:"inputSchema=(none)";return`${h} ${g}`},c=(()=>{let l=[],d=[],a=[],y=[];for(let h=0;h<n.length;h++){let g=n[h];!g||typeof g!="object"||typeof g.id!="string"?y.push(h):g.kind==="builtin"?l.push(g.id):g.kind==="skill"?a.push(g.id):g.kind==="http"||g.kind==="mcp"||g.kind==="composio"?d.push(g.id):y.push(h)}let w=[];return l.length&&w.push(`builtin[${l.join(", ")}]`),d.length&&w.push(`custom[${d.join(", ")}]`),a.length&&w.push(`skill[${a.join(", ")}]`),y.length&&w.push(`invalid@[${y.join(", ")}]`),w.join(" ")||"(none)"})();console.log(`[tools] node ${s.id} requested (${n.length}): ${c}`);let p=!1,f=async()=>{if(p&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},p=!0,o.toolDefs;try{let l=await oe(o.env),d={};for(let a of l)a&&a.id&&(d[a.id]=a);o.toolDefs=d}catch(l){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(l)}`}),o.toolDefs=o.toolDefs||{}}return p=!0,o.toolDefs},u=[];for(let l=0;l<n.length;l++){let d=n[l];if(!d||typeof d!="object"||typeof d.id!="string"||d.kind!=="builtin"&&d.kind!=="http"&&d.kind!=="mcp"&&d.kind!=="composio"&&d.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${l}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let a=d;if(a.kind!=="builtin"){let w=(await f())[a.id];if(!w){console.error(`[tools] \u2717 custom '${a.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${a.id}' not found for this tenant`});continue}if(a.kind==="composio"){try{let g=await vt(w,o,e,t),x=Object.keys(g);for(let[I,R]of Object.entries(g))r[I]=$t(I,R,a,o,t);console.log(`[tools] \u2713 composio '${a.id}' \u2192 ${x.length} tool(s)`)}catch(g){console.error(`[tools] \u2717 composio '${a.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${a.id}': ${String(g)}`})}continue}if(a.kind==="skill"){if(w.kind!=="skill"){console.error(`[tools] \u2717 skill '${a.id}': row is of kind '${w.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${a.id}' is not a skill`});continue}let g=w.name;if(r[g]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${g}' \u2014 builtin/other already registered, skipping skill '${a.id}'`});continue}try{r[g]=se(w,o,e,t),u.push(w);let x=typeof w.execution=="string"?JSON.parse(w.execution):w.execution||{},I=Array.isArray(x.references)?x.references.map(R=>R==null?void 0:R.name):[];console.log(`[tools] \u2713 skill '${a.id}' \u2192 '${g}' (refs: ${I.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:g,refCount:I.length,refs:I}})}catch(x){console.error(`[tools] \u2717 skill '${a.id}': ${String(x)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${a.id}': ${String(x)}`})}continue}let h=w.name;if(r[h]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${h}' \u2014 builtin already registered, skipping custom tool '${a.id}'`});continue}try{let g=ee(w,o,e,t);r[h]=$t(h,g,a,o,t),console.log(`[tools] \u2713 custom '${a.id}' \u2192 '${h}'`),console.log(`[tools] ${i(r[h])}`)}catch(g){console.error(`[tools] \u2717 custom '${a.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${a.id}': ${String(g)}`})}continue}if(!St[a.id]){console.error(`[tools] \u2717 builtin '${a.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${a.id}' not found in registry`});continue}try{let y;try{y=await Qe(`../tools/${a.id}.ts`)}catch{y=await Ze(`../tools/${a.id}.js`)}let w;if(y[a.id])w=y[a.id];else if(y.default)w=y.default;else if(y.create)w=y.create;else{let O=Object.values(y);O.length>0&&(w=O[0])}if(!w){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${a.id}'`});continue}let h,g,x={};if(a.params&&typeof a.params=="object"){if(typeof a.params.description=="string"?h=a.params.description:a.params.description!==void 0&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${a.id}' \u2014 must be a string`})),a.params.inputSchema!==void 0){let O=a.params.inputSchema;typeof O=="object"&&(typeof O.safeParse=="function"||O._def)?g=O:typeof O=="object"&&O!==null&&O.type==="object"&&O.properties?(g=te(O),g||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${a.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${a.id}' \u2014 must be a Zod schema or JSON Schema object`})}a.params.defaults!==void 0?typeof a.params.defaults=="object"&&a.params.defaults!==null&&!Array.isArray(a.params.defaults)?x=a.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${a.id}' \u2014 must be an object`}),x={}):a.params.source!==void 0||a.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${a.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),x={}):x={}}let I=w(o,e,x,t);h&&I&&typeof I=="object"&&(I.description=h),g&&I&&typeof I=="object"&&(I.inputSchema=g),r[a.id]=$t(a.id,I,a,o,t);let R=[];h&&R.push("description"),g&&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 '${a.id}'${$}`),console.log(`[tools] ${i(I)}`)}catch(y){console.error(`[tools] \u2717 builtin '${a.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${a.id}': ${String(y)}`});continue}}if(u.length>0)if(r.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{r.readSkillRef=ne(o,u,e,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${u.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:u.map(l=>l.name)}})}catch(l){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(l)}`)}return r}async function kt(o,e,s,t,n,r,i){var M,b,F,k,A;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=!1;try{let N=(M=s.flowData)==null?void 0:M.state;if(N&&N.edges&&N.nodes){let L=N.edges.filter(D=>D.source===e.id);if(L.length>0){let D=N.nodes.find(V=>V.id===L[0].target);D&&D.type==="answerNode"&&(c=!0)}}}catch(N){console.error("Error determining next node for streaming:",N)}let p=G(e.data.template,e,s,t,{sessionEnv:o});(!p||!p.trim())&&(p="Answer straight forward to the user, dont offer any other option to continue");let f=p,u="";if((b=o.memoryConfig)!=null&&b.enabled){let N=await((F=o.getContextIndex)==null?void 0:F.call(o))??[];u=Wt(N),p+=u}let m=G(e.data.user_template||"",e,s,t,{sessionEnv:o}),l=N=>N&&Object.fromEntries(Object.keys(N).map(L=>[L,"[redacted]"])),d=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:l(o.secrets),userAuth:l(o.userAuth)}:o,a=G(e.data.template,e,s,void 0,{sessionEnv:d})||f;a+=u;let y=G(e.data.user_template||"",e,s,void 0,{sessionEnv:d});t==null||t({type:`info:llmNodeRunner:${e.id}`,content:a}),t==null||t({type:`info:llmNodeRunner:${e.id}`,content:y});let w=(k=e==null?void 0:e.data)==null?void 0:k.window_size,h=Number(w);(!Number.isInteger(h)||h<=0)&&(h=5);let g=Re(e,s),x=xe(e,s),R=(await((A=o.getMessages)==null?void 0:A.call(o))??[]).slice(-h),$=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 O=no($,m,g,x);await so(p,O,o.conn,t,e,c,n,s,r,o,i)}async function so(o,e,s,t,n,r,i,c,p,f,u){var l;let m=Date.now();if(!((l=f.env)!=null&&l.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(d,a)=>{var A,N,L,D,V,Q,Z;let y,w={},h,g="none",x=!1,I,R=!1,$=!1,O=0,M=0,b=(A=n==null?void 0:n.data)==null?void 0:A.sendReasoning,F=b!==!1;try{let j=(N=n==null?void 0:n.data)==null?void 0:N.model,z=Array.isArray(j)?j[0]:j||"gpt_5_nano",T=Et(n==null?void 0:n.data),_=await it(z,f,T);if(!_)throw new Error(`Model '${z}' not found in registry`);y=_.modelHandle,w=_.effectiveParams||{},g=_.reasoning.kind;let C=Kt(_.reasoning,(L=n==null?void 0:n.data)==null?void 0:L.reasoningEffort);x=F&&Vt(_.reasoning);let E=typeof((D=n==null?void 0:n.data)==null?void 0:D.reasoningMaxTokens)=="number"?n.data.reasoningMaxTokens:void 0;h=Jt(_.provider,{effort:C,exposeReasoning:x,maxTokens:E}),C&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:C})),console.log(`[reasoning] ${JSON.stringify({model:z,provider:_.provider,capability:_.reasoning,requestedEffort:((V=n==null?void 0:n.data)==null?void 0:V.reasoningEffort)??null,resolvedEffort:C??null,sendReasoning:F,exposeReasoning:x,providerOptions:h??null},null,2)}`);for(let H of _.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:H});t==null||t({type:"info:llmNodeRunner:model",content:z}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(Q=n==null?void 0:n.data)!=null&&Q.generationPreset?{preset:n.data.generationPreset}:{},...w,...g!=="none"?{reasoning:g,configuredSendReasoning:b,sendReasoning:F,exposeReasoning:x,...C?{effort:C}:{}}:{}}})}catch(j){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(j)}`}),j}let k=await oo(f,c,n,t);if((Z=f.memoryConfig)!=null&&Z.enabled){let{recall:j}=await import("./recall-IABRCSHY.js");k.recall=j(f,c,void 0,t)}console.log(`[tools] node ${n.id} loaded ${Object.keys(k).length}: ${Object.keys(k).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:n.id,tools:Object.keys(k)}});try{let j=ve({model:y,system:o,messages:e,stopWhen:(()=>{var H;let _=!!k.readSkillRef?10:5,C=Number(((H=n.data)==null?void 0:H.max_steps)??_),E=Number.isFinite(C)?Math.max(1,Math.min(30,C)):_;return Se(E)})(),...qt(w),...h?{providerOptions:h}:{},tools:k,onFinish:async T=>{var Dt,Ut;let _=T.text||"",C=T.reasoningText??((Dt=T.reasoning)==null?void 0:Dt.text)??"";if(console.log(`[reasoning] done: deltas=${O} chars=${M} result.reasoningText=${C.length} finishReason=${T.finishReason??"n/a"} reasoningTokens=${((Ut=T.usage)==null?void 0:Ut.reasoningTokens)??"n/a"}`),F&&x&&!R&&C&&s){R=!0;try{U(s,P.SERVER_REASONING_STREAM,C)}catch(ze){console.warn("Failed to send finished reasoning over connection",ze)}}let E={id:to(),role:"assistant",type:"text",content:_,ts:Date.now()};r&&(f.setMessages?await f.setMessages(E):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),s&&F&&R&&!$&&($=!0,U(s,P.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),r&&s&&U(s,P.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),i==null||i((n==null?void 0:n.id)||"llm_result",_),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(T)});let H=Date.now()-m,Ge=I?I-m:void 0;u==null||u({type:"llm_telemetry",payload:{nodeId:n.id,totalLatency:H,timeToFirstToken:Ge,model:T.response.modelId,usage:T.usage}}),u==null||u({type:"llm_result",payload:{result:T}})},onStepFinish:async T=>{let _=(C,E=200)=>{let H=typeof C=="string"?C:JSON.stringify(C);return H?H.length>E?`${H.slice(0,E)}\u2026(+${H.length-E})`:H:""};if(T.toolCalls&&T.toolCalls.length>0){for(let C of T.toolCalls)console.log(`[tools] \u2192 ${C.toolName}(${_(C.args??C.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${n.id}`,content:JSON.stringify(T.toolCalls)})}if(T.toolResults&&T.toolResults.length>0){for(let C of T.toolResults)console.log(`[tools] \u2190 ${C.toolName} \u2192 ${_(C.result??C.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${n.id}`,content:JSON.stringify(T.toolResults)})}await eo(T,n,f,t)},experimental_onToolCallStart:T=>{var _;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(_=T==null?void 0:T.toolCall)==null?void 0:_.toolName,status:"start"}})},experimental_onToolCallFinish:T=>{var _,C;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(_=T==null?void 0:T.toolCall)==null?void 0:_.toolName,status:((C=T==null?void 0:T.toolOutput)==null?void 0:C.type)==="tool-error"?"error":"success"}})},onError:T=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),a(T)},onChunk:T=>{if(T.chunk.type==="reasoning-delta"){let C=T.chunk.text??T.chunk.delta??"";if(C&&(R=!0,O+=1,M+=C.length,O===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),F&&s&&C)try{U(s,P.SERVER_REASONING_STREAM,C)}catch(E){console.warn("Failed to send reasoning chunk over connection",E)}return}if(T.chunk.type==="text-delta"){if(I||(I=Date.now()),s&&F&&R&&!$){$=!0;try{U(s,P.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(C){console.warn("Failed to send reasoning complete over connection",C)}}return}u==null||u({type:T.chunk.type,payload:{nodeId:n.id,chunk:T.chunk}});let _=`llm_chunk:${T.chunk.type}`;t==null||t({type:_,content:{...T}})}}),z=async()=>{let T="";for await(let _ of j.fullStream)if(_.type==="text-delta"){if(T+=_.text,r&&s)try{U(s,P.SERVER_TEXT_STREAM,_.text)}catch(C){console.warn("Failed to send chunk over connection",C)}}else if(_.type==="finish-step"&&_.finishReason==="tool-calls"){if(r&&s&&T.trim())try{U(s,P.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(C){console.warn("Failed to flush text segment over connection",C)}T=""}};await Promise.all([j,z()]),d(),t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"success"}})}catch(j){t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"error",error:String(j)}}),a(j)}})}function no(o,e,s,t){let n=!!(s&&s.length>0),r=!!t,i=n||r,p=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,f=u=>{let m=[],l="";if(r&&(l+=`[Attached files]
|
|
30
|
+
`:"")+l)}}return s}function xe(o,e){var t,n,r,i,c,p;let s=[];if((t=o.data)!=null&&t.varMapping&&Array.isArray(o.data.varMapping))for(let f of o.data.varMapping){let u=f.from;if(!u)continue;let m=!1;if(u==="images")m=!0;else{let l=u.indexOf(".");if(l!==-1){let d=u.substring(0,l),a=u.substring(l+1).split(".")[0],y=(i=(r=(n=e.flowData)==null?void 0:n.state)==null?void 0:r.nodes)==null?void 0:i.find(w=>w.id===d);if(y){let h=ct(y).find(g=>g.name===a);(h==null?void 0:h.type)==="image"&&(m=!0)}}}if(m){let l=lt(u,{context:e.context||{},results:e.results||{},nodes:((p=(c=e.flowData)==null?void 0:c.state)==null?void 0:p.nodes)||[]});Array.isArray(l)&&s.push(...l)}}return s}var Qe=st({"../tools/composioTool.ts":()=>import("./composioTool-44B637WM.js"),"../tools/convertTempMessure.ts":()=>import("./convertTempMessure-5CAGRLBY.js"),"../tools/httpTool.ts":()=>import("./httpTool-SFK4FG4Q.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 Ze=st({});function Ot(o,e,s,t,n){var i;if(!((i=t.memoryConfig)!=null&&i.enabled)||!t.memoryConfig.toolCache||!s.cacheable||!e||typeof e.execute!="function")return e;let r=e.execute.bind(e);return e.execute=async(c,...p)=>{var l;if(!t.getContextIndex)return r(c,...p);let f=await wt(c),m=(await t.getContextIndex()).find(d=>{if(d.domain!=="tool")return!1;let a=xt(d.meta);return a.toolName===o&&a.paramsHash===f});if(m){let d=await((l=t.getContext)==null?void 0:l.call(t,m.ref));if((d==null?void 0:d.data)!=null&&xt(d.meta).truncated!==!0){n==null||n({type:"info:memory:cacheHit",content:{ref:d.ref,toolName:o}});try{return JSON.parse(d.data)}catch{return d.data}}}return r(c,...p)},e}async function eo(o,e,s,t){var u,m;if(!((u=s.memoryConfig)!=null&&u.enabled)||!s.setContext||s.cycle==null)return;let n=o.toolCalls??[],r=o.toolResults??[];if(!n.length||!r.length)return;let i=new Map;for(let l of r)l!=null&&l.toolCallId&&i.set(l.toolCallId,l);let c=Array.isArray((m=e==null?void 0:e.data)==null?void 0:m.tools)?e.data.tools:[],p=new Map;for(let l of c)l&&typeof l.id=="string"&&p.set(l.id,l);let f=new Map;for(let l of Object.values(s.toolDefs??{}))l&&l.name&&f.set(l.name,l);for(let l of n){let d=l.toolCallId,a=l.toolName,y=i.get(d);if(!a||!y||a==="readSkillRef")continue;let w=l.args??l.input,h=y.result??y.output,g=!1,x="",I="tool",R="",$=f.get(a);$&&$.kind==="skill"&&(g=!0,x=`skill:${a}`,I="skill",R=`Skill instructions for ${a}`),x||(x=await Xt(a,w),R=Jt(w,h));let O=p.get(a)??c.find(F=>F.id===a),M=await wt(w),b=typeof h=="string"?h:JSON.stringify(h??null);await s.setContext({ref:x,domain:I,description:R,data:b,cycle:s.cycle,meta:JSON.stringify({toolName:a,paramsHash:M,cacheable:(O==null?void 0:O.cacheable)===!0})}),t==null||t({type:"info:memory:updated",content:{ref:x}})}}async function oo(o,e,s,t){var m;let n=Array.isArray((m=s==null?void 0:s.data)==null?void 0:m.tools)?s.data.tools:[];if(n.length===0)return{};let r={},i=l=>{var x,I;let d=typeof(l==null?void 0:l.description)=="string"?l.description:"",a=l==null?void 0:l.inputSchema,y;try{let R=(a==null?void 0:a.shape)??(typeof((x=a==null?void 0:a._def)==null?void 0:x.shape)=="function"?a._def.shape():(I=a==null?void 0:a._def)==null?void 0:I.shape);R&&typeof R=="object"&&(y=R)}catch{}let w=y?Object.keys(y):[],h=d?`description="${d.length>120?d.slice(0,120)+"\u2026":d}"`:"description=(none)",g=w.length?`inputSchema={${w.join(", ")}}`:"inputSchema=(none)";return`${h} ${g}`},c=(()=>{let l=[],d=[],a=[],y=[];for(let h=0;h<n.length;h++){let g=n[h];!g||typeof g!="object"||typeof g.id!="string"?y.push(h):g.kind==="builtin"?l.push(g.id):g.kind==="skill"?a.push(g.id):g.kind==="http"||g.kind==="mcp"||g.kind==="composio"?d.push(g.id):y.push(h)}let w=[];return l.length&&w.push(`builtin[${l.join(", ")}]`),d.length&&w.push(`custom[${d.join(", ")}]`),a.length&&w.push(`skill[${a.join(", ")}]`),y.length&&w.push(`invalid@[${y.join(", ")}]`),w.join(" ")||"(none)"})();console.log(`[tools] node ${s.id} requested (${n.length}): ${c}`);let p=!1,f=async()=>{if(p&&o.toolDefs)return o.toolDefs;if(!o.env)return o.toolDefs=o.toolDefs||{},p=!0,o.toolDefs;try{let l=await ee(o.env),d={};for(let a of l)a&&a.id&&(d[a.id]=a);o.toolDefs=d}catch(l){t==null||t({type:"error:llmNodeRunner",content:`Failed to load custom tool defs: ${String(l)}`}),o.toolDefs=o.toolDefs||{}}return p=!0,o.toolDefs},u=[];for(let l=0;l<n.length;l++){let d=n[l];if(!d||typeof d!="object"||typeof d.id!="string"||d.kind!=="builtin"&&d.kind!=="http"&&d.kind!=="mcp"&&d.kind!=="composio"&&d.kind!=="skill"){t==null||t({type:"error:llmNodeRunner",content:`Invalid tool descriptor at index ${l}: expected { kind: 'http'|'mcp'|'composio'|'builtin'|'skill', id: string, params?: any }`});continue}let a=d;if(a.kind!=="builtin"){let w=(await f())[a.id];if(!w){console.error(`[tools] \u2717 custom '${a.id}': not found for tenant`),t==null||t({type:"error:llmNodeRunner",content:`custom tool '${a.id}' not found for this tenant`});continue}if(a.kind==="composio"){try{let g=await St(w,o,e,t),x=Object.keys(g);for(let[I,R]of Object.entries(g))r[I]=Ot(I,R,a,o,t);console.log(`[tools] \u2713 composio '${a.id}' \u2192 ${x.length} tool(s)`)}catch(g){console.error(`[tools] \u2717 composio '${a.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading composio tool '${a.id}': ${String(g)}`})}continue}if(a.kind==="skill"){if(w.kind!=="skill"){console.error(`[tools] \u2717 skill '${a.id}': row is of kind '${w.kind}', not 'skill'`),t==null||t({type:"error:llmNodeRunner",content:`tool '${a.id}' is not a skill`});continue}let g=w.name;if(r[g]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${g}' \u2014 builtin/other already registered, skipping skill '${a.id}'`});continue}try{r[g]=oe(w,o,e,t),u.push(w);let x=typeof w.execution=="string"?JSON.parse(w.execution):w.execution||{},I=Array.isArray(x.references)?x.references.map(R=>R==null?void 0:R.name):[];console.log(`[tools] \u2713 skill '${a.id}' \u2192 '${g}' (refs: ${I.join(", ")||"none"})`),t==null||t({type:"info:skill:registered",content:{skill:g,refCount:I.length,refs:I}})}catch(x){console.error(`[tools] \u2717 skill '${a.id}': ${String(x)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading skill tool '${a.id}': ${String(x)}`})}continue}let h=w.name;if(r[h]){t==null||t({type:"warn:llmNodeRunner",content:`tool name collision on '${h}' \u2014 builtin already registered, skipping custom tool '${a.id}'`});continue}try{let g=te(w,o,e,t);r[h]=Ot(h,g,a,o,t),console.log(`[tools] \u2713 custom '${a.id}' \u2192 '${h}'`),console.log(`[tools] ${i(r[h])}`)}catch(g){console.error(`[tools] \u2717 custom '${a.id}': ${String(g)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading custom tool '${a.id}': ${String(g)}`})}continue}if(!Zt[a.id]){console.error(`[tools] \u2717 builtin '${a.id}': not in registry`),t==null||t({type:"error:llmNodeRunner",content:`Tool '${a.id}' not found in registry`});continue}try{let y;try{y=await Qe(`../tools/${a.id}.ts`)}catch{y=await Ze(`../tools/${a.id}.js`)}let w;if(y[a.id])w=y[a.id];else if(y.default)w=y.default;else if(y.create)w=y.create;else{let O=Object.values(y);O.length>0&&(w=O[0])}if(!w){t==null||t({type:"error:llmNodeRunner",content:`No factory export found for tool '${a.id}'`});continue}let h,g,x={};if(a.params&&typeof a.params=="object"){if(typeof a.params.description=="string"?h=a.params.description:a.params.description!==void 0&&(t==null||t({type:"error:llmNodeRunner",content:`Invalid description for tool '${a.id}' \u2014 must be a string`})),a.params.inputSchema!==void 0){let O=a.params.inputSchema;typeof O=="object"&&(typeof O.safeParse=="function"||O._def)?g=O:typeof O=="object"&&O!==null&&O.type==="object"&&O.properties?(g=vt(O),g||t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${a.id}' \u2014 must be a Zod schema or JSON Schema object`})):t==null||t({type:"error:llmNodeRunner",content:`Invalid inputSchema for tool '${a.id}' \u2014 must be a Zod schema or JSON Schema object`})}a.params.defaults!==void 0?typeof a.params.defaults=="object"&&a.params.defaults!==null&&!Array.isArray(a.params.defaults)?x=a.params.defaults:(t==null||t({type:"error:llmNodeRunner",content:`Invalid defaults for tool '${a.id}' \u2014 must be an object`}),x={}):a.params.source!==void 0||a.params.target!==void 0?(t==null||t({type:"error:llmNodeRunner",content:`Invalid params for tool '${a.id}' \u2014 legacy top-level source/target not supported; use params.defaults instead`}),x={}):x={}}let I=w(o,e,x,t);h&&I&&typeof I=="object"&&(I.description=h),g&&I&&typeof I=="object"&&(I.inputSchema=g),r[a.id]=Ot(a.id,I,a,o,t);let R=[];h&&R.push("description"),g&&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 '${a.id}'${$}`),console.log(`[tools] ${i(I)}`)}catch(y){console.error(`[tools] \u2717 builtin '${a.id}': ${String(y)}`),t==null||t({type:"error:llmNodeRunner",content:`Error loading tool '${a.id}': ${String(y)}`});continue}}if(u.length>0)if(r.readSkillRef)t==null||t({type:"warn:llmNodeRunner",content:"tool name collision on 'readSkillRef' \u2014 builtin/other already registered, skipping readSkillRef tool"});else try{r.readSkillRef=se(o,u,e,t),console.log(`[tools] \u2713 registered readSkillRef tool for ${u.length} skill(s)`),t==null||t({type:"info:skill:readSkillRefRegistered",content:{skills:u.map(l=>l.name)}})}catch(l){console.error(`[tools] \u2717 failed to load readSkillRef tool: ${String(l)}`)}return r}async function $t(o,e,s,t,n,r,i){var M,b,F,k,A;`${e.id}`,t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c=!1;try{let N=(M=s.flowData)==null?void 0:M.state;if(N&&N.edges&&N.nodes){let L=N.edges.filter(D=>D.source===e.id);if(L.length>0){let D=N.nodes.find(q=>q.id===L[0].target);D&&D.type==="answerNode"&&(c=!0)}}}catch(N){console.error("Error determining next node for streaming:",N)}let p=G(e.data.template,e,s,t,{sessionEnv:o});(!p||!p.trim())&&(p="Answer straight forward to the user, dont offer any other option to continue");let f=p,u="";if((b=o.memoryConfig)!=null&&b.enabled){let N=await((F=o.getContextIndex)==null?void 0:F.call(o))??[];u=zt(N),p+=u}let m=G(e.data.user_template||"",e,s,t,{sessionEnv:o}),l=N=>N&&Object.fromEntries(Object.keys(N).map(L=>[L,"[redacted]"])),d=o!=null&&o.secrets||o!=null&&o.userAuth?{...o,secrets:l(o.secrets),userAuth:l(o.userAuth)}:o,a=G(e.data.template,e,s,void 0,{sessionEnv:d})||f;a+=u;let y=G(e.data.user_template||"",e,s,void 0,{sessionEnv:d});t==null||t({type:`info:llmNodeRunner:${e.id}`,content:a}),t==null||t({type:`info:llmNodeRunner:${e.id}`,content:y});let w=(k=e==null?void 0:e.data)==null?void 0:k.window_size,h=Number(w);(!Number.isInteger(h)||h<=0)&&(h=5);let g=xe(e,s),x=we(e,s),R=(await((A=o.getMessages)==null?void 0:A.call(o))??[]).slice(-h),$=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 O=no($,m,g,x);await so(p,O,o.conn,t,e,c,n,s,r,o,i)}async function so(o,e,s,t,n,r,i,c,p,f,u){var l;let m=Date.now();if(!((l=f.env)!=null&&l.AI))throw new Error("AI binding is required for LLM node");return new Promise(async(d,a)=>{var A,N,L,D,q,Q,Z;let y,w={},h,g="none",x=!1,I,R=!1,$=!1,O=0,M=0,b=(A=n==null?void 0:n.data)==null?void 0:A.sendReasoning,F=b!==!1;try{let j=(N=n==null?void 0:n.data)==null?void 0:N.model,z=Array.isArray(j)?j[0]:j||"gpt_5_nano",T=Ht(n==null?void 0:n.data),_=await it(z,f,T);if(!_)throw new Error(`Model '${z}' not found in registry`);y=_.modelHandle,w=_.effectiveParams||{},g=_.reasoning.kind;let C=Vt(_.reasoning,(L=n==null?void 0:n.data)==null?void 0:L.reasoningEffort);x=F&&qt(_.reasoning);let E=typeof((D=n==null?void 0:n.data)==null?void 0:D.reasoningMaxTokens)=="number"?n.data.reasoningMaxTokens:void 0;h=Kt(_.provider,{effort:C,exposeReasoning:x,maxTokens:E}),C&&(t==null||t({type:"info:llmNodeRunner:reasoningEffort",content:C})),console.log(`[reasoning] ${JSON.stringify({model:z,provider:_.provider,capability:_.reasoning,requestedEffort:((q=n==null?void 0:n.data)==null?void 0:q.reasoningEffort)??null,resolvedEffort:C??null,sendReasoning:F,exposeReasoning:x,providerOptions:h??null},null,2)}`);for(let H of _.paramAdjustments??[])t==null||t({type:"warn:llmNodeRunner",content:H});t==null||t({type:"info:llmNodeRunner:model",content:z}),t==null||t({type:"info:llmNodeRunner:generationParams",content:{...(Q=n==null?void 0:n.data)!=null&&Q.generationPreset?{preset:n.data.generationPreset}:{},...w,...g!=="none"?{reasoning:g,configuredSendReasoning:b,sendReasoning:F,exposeReasoning:x,...C?{effort:C}:{}}:{}}})}catch(j){throw t==null||t({type:"error:llmNodeRunner",content:`Model error: ${String(j)}`}),j}let k=await oo(f,c,n,t);if((Z=f.memoryConfig)!=null&&Z.enabled){let{recall:j}=await import("./recall-IABRCSHY.js");k.recall=j(f,c,void 0,t)}console.log(`[tools] node ${n.id} loaded ${Object.keys(k).length}: ${Object.keys(k).join(", ")||"(none)"}`),t==null||t({type:"info:llmNodeRunner:toolsLoaded",content:{nodeId:n.id,tools:Object.keys(k)}});try{let j=ve({model:y,system:o,messages:e,stopWhen:(()=>{var H;let _=!!k.readSkillRef?10:5,C=Number(((H=n.data)==null?void 0:H.max_steps)??_),E=Number.isFinite(C)?Math.max(1,Math.min(30,C)):_;return Se(E)})(),...Et(w),...h?{providerOptions:h}:{},tools:k,onFinish:async T=>{var Pt,Dt;let _=T.text||"",C=T.reasoningText??((Pt=T.reasoning)==null?void 0:Pt.text)??"";if(console.log(`[reasoning] done: deltas=${O} chars=${M} result.reasoningText=${C.length} finishReason=${T.finishReason??"n/a"} reasoningTokens=${((Dt=T.usage)==null?void 0:Dt.reasoningTokens)??"n/a"}`),F&&x&&!R&&C&&s){R=!0;try{U(s,P.SERVER_REASONING_STREAM,C)}catch(ze){console.warn("Failed to send finished reasoning over connection",ze)}}let E={id:to(),role:"assistant",type:"text",content:_,ts:Date.now()};r&&(f.setMessages?await f.setMessages(E):t==null||t({type:"error:llmNodeRunner",content:"setMessages callback missing"})),s&&F&&R&&!$&&($=!0,U(s,P.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))),r&&s&&U(s,P.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({})),i==null||i((n==null?void 0:n.id)||"llm_result",_),t==null||t({type:"info:llmNodeRunner:onFinish",content:JSON.stringify(T)});let H=Date.now()-m,Ge=I?I-m:void 0;u==null||u({type:"llm_telemetry",payload:{nodeId:n.id,totalLatency:H,timeToFirstToken:Ge,model:T.response.modelId,usage:T.usage}}),u==null||u({type:"llm_result",payload:{result:T}})},onStepFinish:async T=>{let _=(C,E=200)=>{let H=typeof C=="string"?C:JSON.stringify(C);return H?H.length>E?`${H.slice(0,E)}\u2026(+${H.length-E})`:H:""};if(T.toolCalls&&T.toolCalls.length>0){for(let C of T.toolCalls)console.log(`[tools] \u2192 ${C.toolName}(${_(C.args??C.input)})`);t==null||t({type:`info:llmNodeRunner:toolCalls:${n.id}`,content:JSON.stringify(T.toolCalls)})}if(T.toolResults&&T.toolResults.length>0){for(let C of T.toolResults)console.log(`[tools] \u2190 ${C.toolName} \u2192 ${_(C.result??C.output)}`);t==null||t({type:`info:llmNodeRunner:toolResults:${n.id}`,content:JSON.stringify(T.toolResults)})}await eo(T,n,f,t)},experimental_onToolCallStart:T=>{var _;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(_=T==null?void 0:T.toolCall)==null?void 0:_.toolName,status:"start"}})},experimental_onToolCallFinish:T=>{var _,C;t==null||t({type:"tool:execution",content:{nodeId:n.id,toolName:(_=T==null?void 0:T.toolCall)==null?void 0:_.toolName,status:((C=T==null?void 0:T.toolOutput)==null?void 0:C.type)==="tool-error"?"error":"success"}})},onError:T=>{t==null||t({type:"error:llmNodeRunner",content:"Execution error"}),a(T)},onChunk:T=>{if(T.chunk.type==="reasoning-delta"){let C=T.chunk.text??T.chunk.delta??"";if(C&&(R=!0,O+=1,M+=C.length,O===1&&console.log("[reasoning] \u2713 first reasoning-delta received")),F&&s&&C)try{U(s,P.SERVER_REASONING_STREAM,C)}catch(E){console.warn("Failed to send reasoning chunk over connection",E)}return}if(T.chunk.type==="text-delta"){if(I||(I=Date.now()),s&&F&&R&&!$){$=!0;try{U(s,P.SERVER_REASONING_STREAM_COMPLETE,JSON.stringify({}))}catch(C){console.warn("Failed to send reasoning complete over connection",C)}}return}u==null||u({type:T.chunk.type,payload:{nodeId:n.id,chunk:T.chunk}});let _=`llm_chunk:${T.chunk.type}`;t==null||t({type:_,content:{...T}})}}),z=async()=>{let T="";for await(let _ of j.fullStream)if(_.type==="text-delta"){if(T+=_.text,r&&s)try{U(s,P.SERVER_TEXT_STREAM,_.text)}catch(C){console.warn("Failed to send chunk over connection",C)}}else if(_.type==="finish-step"&&_.finishReason==="tool-calls"){if(r&&s&&T.trim())try{U(s,P.SERVER_TEXT_STREAM_COMPLETE,JSON.stringify({}))}catch(C){console.warn("Failed to flush text segment over connection",C)}T=""}};await Promise.all([j,z()]),d(),t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"success"}})}catch(j){t==null||t({type:"node:execution",content:{nodeId:n.id,nodeType:n.type,status:"error",error:String(j)}}),a(j)}})}function no(o,e,s,t){let n=!!(s&&s.length>0),r=!!t,i=n||r,p=o.length>0&&o[o.length-1].role==="user"?o[o.length-1]:void 0,f=u=>{let m=[],l="";if(r&&(l+=`[Attached files]
|
|
31
31
|
${t}
|
|
32
32
|
[End of attached files]
|
|
33
33
|
|
|
34
|
-
`),u&&(l+=u),l&&m.push({type:"text",text:l}),n)for(let d of s)m.push({type:"image",image:d.data,mimeType:d.mimeType});return m};return e&&p&&p.content===e?[...o.slice(0,-1).map(m=>({role:m.role,content:m.content})),{role:"user",content:f(e)}]:e?[...o.map(u=>({role:u.role,content:u.content})),{role:"user",content:f(e)}]:i&&p?[...o.slice(0,-1).map(m=>({role:m.role,content:m.content})),{role:"user",content:f(p.content)}]:o.map(u=>({role:u.role,content:u.content}))}async function
|
|
34
|
+
`),u&&(l+=u),l&&m.push({type:"text",text:l}),n)for(let d of s)m.push({type:"image",image:d.data,mimeType:d.mimeType});return m};return e&&p&&p.content===e?[...o.slice(0,-1).map(m=>({role:m.role,content:m.content})),{role:"user",content:f(e)}]:e?[...o.map(u=>({role:u.role,content:u.content})),{role:"user",content:f(e)}]:i&&p?[...o.slice(0,-1).map(m=>({role:m.role,content:m.content})),{role:"user",content:f(p.content)}]:o.map(u=>({role:u.role,content:u.content}))}async function kt(o,e,s,t,n,r,i){var f,u,m,l;console.log(`**** MEMO Node id: ${e.id} ****`),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"start"}});let c="",p=Date.now();try{if(t==null||t({type:"info:memoNodeRunner",content:"Starting memo node execution"}),((f=s==null?void 0:s.context)==null?void 0:f[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 d=((u=s==null?void 0:s.context)==null?void 0:u[e.data.query_key])||"";t==null||t({type:"info:memoNodeRunner",content:`Query text: ${d}`}),t==null||t({type:"info:memoNodeRunner",content:"Generating embedding for query"});let a=await Ut(o,d,!0);t==null||t({type:"info:memoNodeRunner",content:`Embedding generated successfully, length: ${a.data[0].length}`});let y=Array.isArray(e.data.rag_id)?e.data.rag_id:[e.data.rag_id],w=[];for(let I of y){t==null||t({type:"info:memoNodeRunner",content:`Executing RAG query with namespace: ${I}`});let R=await o.env[`VDB_${(m=s.flowData)==null?void 0:m.tenant}_1024`].query(a.data[0],{namespace:I,topK:e.data.topk,returnMetadata:"all"});t==null||t({type:"info:memoNodeRunner",content:`RAG query completed for namespace ${I}, matches: ${((l=R.matches)==null?void 0:l.length)||0}`}),Array.isArray(R.matches)&&w.push(...R.matches)}let h=Date.now()-p;c=w.map(I=>{var R;return(R=I.metadata)==null?void 0:R.value}).filter(I=>typeof I=="string").join(`
|
|
35
35
|
|
|
36
|
-
`),i==null||i({type:"memo_search",payload:{nodeId:e.id,searchLatencyMs:h,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(d){console.error("Error processing MemoNode:",d),t==null||t({type:"error:memoNodeRunner",content:`Memo node execution failed: ${d}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(d)}})}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
|
|
36
|
+
`),i==null||i({type:"memo_search",payload:{nodeId:e.id,searchLatencyMs:h,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(d){console.error("Error processing MemoNode:",d),t==null||t({type:"error:memoNodeRunner",content:`Memo node execution failed: ${d}`}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"error",error:String(d)}})}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 Ft(o,e,s,t,n,r,i){var u,m,l,d,a,y,w;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}),i==null||i({type:"start_node",payload:{userMessage:(u=s==null?void 0:s.context)==null?void 0:u.user_input}});let c=((m=e.data)==null?void 0:m.allow_images)!==!1,p=((l=e.data)==null?void 0:l.allow_documents)!==!1;!c&&(s!=null&&s.context)&&(s.context.user_images=[],r==null||r({...s})),!p&&(s!=null&&s.context)&&(s.context.files="",r==null||r({...s}));let f={};for(let h of Y(e.data))f[h.name]=(d=s==null?void 0:s.context)==null?void 0:d[h.name];n==null||n(e.id,{...f,user_input:(a=s==null?void 0:s.context)==null?void 0:a.user_input,images:c?(y=s==null?void 0:s.context)==null?void 0:y.user_images:[],files:p?(w=s==null?void 0:s.context)==null?void 0:w.files:""}),t==null||t({type:"node:execution",content:{nodeId:e.id,nodeType:e.type,status:"success"}})}function Ie(o,e,s){let t=e;async function n(p){let f=p;for(t.executedNodes=t.executedNodes||[],t.context=t.context||{},t.results=t.results||{};f&&f.id;)await r(f),f=ao(f,t.flowData,t)}async function r(p){var d;let f=c[p.type];if(!f){(d=s==null?void 0:s.onError)==null||d.call(s,`Unknown node type: ${p.type}`);return}let u=a=>{var y;return(y=s==null?void 0:s.onServerEvent)==null?void 0:y.call(s,{...a,ts:Date.now()})},m=a=>{var y,w;if((y=s==null?void 0:s.onTelemetry)==null||y.call(s,a),a.type==="llm_telemetry"||a.type==="class_telemetry"){let h=(w=a.payload)==null?void 0:w.usage;h&&(t.tokenUsage=t.tokenUsage||{promptTokens:0,completionTokens:0,totalTokens:0},t.tokenUsage.promptTokens+=h.promptTokens||0,t.tokenUsage.completionTokens+=h.completionTokens||0,t.tokenUsage.totalTokens+=h.totalTokens||0)}};return await f(o,p,t,u,(a,y)=>{t.results[a]=y},s==null?void 0:s.onChangeState,m)}let i=async p=>{var l,d,a,y,w,h;let f=Date.now(),u="completed",m;try{let g=typeof p=="string"?rt(p):p,x=(g==null?void 0:g.text)||"",I=(g==null?void 0:g.images)||[],R=(g==null?void 0:g.documents)||[],$=await ge(R,o.env),O=$.length>0?$.map(F=>`--- file: ${F.name} ---
|
|
37
37
|
${F.text}`).join(`
|
|
38
38
|
|
|
39
|
-
`):"";t.context={user_input:x,user_images:I,files:O},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},(l=s==null?void 0:s.onServerEvent)==null||l.call(s,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:M,error:b}=ro(t.flowData);if(!M)u="failed",m=b||"Flow Format Error",(d=s==null?void 0:s.onError)==null||d.call(s,m);else{let F=Y(M.data),{values:k,errors:A}=Lt(F,g==null?void 0:g.inputs);if(A.length>0)return u="failed",m=`Invalid flow inputs: ${A.join("; ")}`,(a=s==null?void 0:s.onError)==null||a.call(s,m),{status:u,error:m};t.context={...t.context,inputs:k,...k},t.context.user_input||(t.context.user_input=x),await n(M),(y=s==null?void 0:s.onServerEvent)==null||y.call(s,{type:"agent:telemetry",content:{durationMs:Date.now()-f,tokenUsage:t.tokenUsage},timestamp:Date.now()})}}catch(g){u="failed",m=g instanceof Error?g.message:"Agent execution failed",(w=s==null?void 0:s.onError)==null||w.call(s,m)}finally{(h=s==null?void 0:s.onServerEvent)==null||h.call(s,{type:"agent:complete",content:{status:u,durationMs:Date.now()-f},timestamp:Date.now()})}return{status:u,error:m}},c={startNode:Mt,classifierNode:Ot,llmNode:kt,memoNode:Ft,answerNode:Ct,apiNode:_t};return i}function ro(o){var u;let e=(o==null?void 0:o.state)??o;if(!e||!e.nodes||!e.edges||e.edges.length===0)return{error:"Flow is missing state, nodes, or edges."};let s=e.nodes.filter(m=>m.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(m=>m.type==="answerNode");if(n.length===0)return{error:"Flow must include at least one ANSWER node."};let r=new Map;for(let m of e.edges)r.has(m.source)||r.set(m.source,[]),r.get(m.source).push(m.target);let i=new Map;for(let m of e.edges)i.has(m.target)||i.set(m.target,[]),i.get(m.target).push(m.source);let c=Ie(t.id,r),p=new Set;for(let m of n){let l=Ie(m.id,i);for(let d of l)p.add(d)}let f=[];for(let m of c)if(!p.has(m)){let l=e.nodes.find(d=>d.id===m);if(l){let d=((u=l.data)==null?void 0:u.label)||"";f.push(`${m}(${d},${l.type})`)}}return f.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${f.join(", ")}`}:{startNode:t}}function Ie(o,e){let s=new Set,t=[o];for(s.add(o);t.length>0;){let n=t.shift(),r=e.get(n)||[];for(let i of r)s.has(i)||(s.add(i),t.push(i))}return s}function io(o,e){var s;return((s=o.state)==null?void 0:s.nodes.find(t=>t.id===e))||null}function ao(o,e,s){var c;let t=e==null?void 0:e.state;if(!t)return null;let n=t.edges.filter(p=>p.source===o.id);if(n.length===0)return null;let r=n[0].target;if(o.type==="classifierNode"&&((c=s==null?void 0:s.context)!=null&&c.classified_id)){let p=s.context.classified_id,f=n.find(u=>u.sourceHandle===`source-${p}`);f?r=f.target:console.log(`No matching edge, falling back to first: ${r}`)}return io(e,r)}async function Ne(o,e){var t,n;let s=(t=e==null?void 0:e.flowData)==null?void 0:t.flowId;if(!(o!=null&&o.HX_CORE_URL)||!s)return{engineState:e,refreshed:!1};try{let r=await W(s,o),i={...e,flowData:{...r,tenant:e.flowData.tenant,flowId:s,chatId:e.flowData.chatId}},c=r==null?void 0:r.stateVersion,p=typeof c=="number"&&c!==((n=e.flowData)==null?void 0:n.stateVersion);return{engineState:i,refreshed:p}}catch(r){return console.error(`[flowRefresh] fetch failed for flow ${s}:`,r),{engineState:e,refreshed:!1}}}function Ce(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 Ae=async(o,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),`${JSON.stringify(o)}`};async function tt(o,e){var r,i;let s=o.id||o.name||"",[t,n]=String(s).split("::");if(!t||!n)return null;try{let p=(r=(await K(t,e)).metadata)==null?void 0:r.tenant,f=await W(t,e),u=(i=o.state)==null?void 0:i.user,m={flowData:{...f,tenant:p,flowId:t,chatId:n},executedNodes:[],context:u?{user:u}:{}};return o.setState({...o.state,engineState:m}),m}catch(c){return console.error("Failed to initialize engine state:",c),null}}async function et(o){var O,M,b,F,k;let{agent:e,env:s,ctx:t,payload:n,connection:r}=o,i=Date.now(),c=[],p=async()=>await J(e),f=async A=>{await re(e,A)},u=async A=>{if(e.state.modelsCache&&e.state.modelsCache[A])return e.state.modelsCache[A];try{let{fetchOraModel:N}=await import("./oraApi-YIJGMXX7.js"),L=await N(A,s);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[A]:L}}),L}catch(N){throw console.error(`Error fetching model ${A}:`,N),N}},m={id:co(),role:"user",type:"text",content:n.text,images:n.images,ts:Date.now()};await f(m);let l={onChangeState:A=>{e.setState({...e.state,engineState:A})},onServerEvent:async A=>{var N;await((N=o.onServerEvent)==null?void 0:N.call(o,A)),c.push(A)},onTelemetry:async A=>{var N,L,D,V,Q,Z;await Ae({...A,userId:o.resolveUserId(),tenant:((L=(N=e.state.engineState)==null?void 0:N.flowData)==null?void 0:L.tenant)||"",flowId:((V=(D=e.state.engineState)==null?void 0:D.flowData)==null?void 0:V.flowId)||"",sessionId:((Z=(Q=e.state.engineState)==null?void 0:Q.flowData)==null?void 0:Z.chatId)||""},s)},onError:A=>{var N;(N=o.onError)==null||N.call(o,A),e.setState({...e.state,error:A})}},d=e.state.engineState?{...e.state.engineState}:null;if(d){let{engineState:A,refreshed:N}=await Ne(s,d);d=A,N&&e.setState({...e.state,engineState:d,modelsCache:{}})}else if(d=await tt(e,s),!d){let A="Failed to initialize agent";return l.onError(A),{status:"failed",error:A}}let a=o.secrets;if(!a||Object.keys(a).length===0){let A=(O=d.flowData)==null?void 0:O.tenant;a=A?await ht(s,A):{},(M=o.onSecretsLoaded)==null||M.call(o,a)}let y=o.user??e.state.user??void 0;y&&!((b=d.context)!=null&&b.user)&&(d.context={...d.context||{},user:y});let w=at(v(d)),h=typeof d.cycle=="number"?d.cycle:0;w.enabled&&(h=await me(e,d),d.cycle=h,e.setState({...e.state,engineState:d}));let g=ge(e,{env:s,ctx:t,conn:r,getMessages:p,setMessages:f,getOraModel:u,secrets:a,userAuth:o.userAuth,user:y,composioSessions:o.composioSessions,publicOrigin:o.publicOrigin,skillRefCache:o.skillRefCache},d,h,o.onMemoryRef),x=await Te(g,d,l)(n),{tenant:I,flowId:R,chatId:$}=d.flowData??{};return I&&R&&$&&t.waitUntil(Ce(s,{id:`${R}::${$}`,tenant:I,flowId:R,sessionId:$,userId:o.resolveUserId(),title:(F=n.text)==null?void 0:F.slice(0,120),turnTs:i,events:c})),x.status==="completed"&&((k=g.memoryConfig)!=null&&k.enabled)&&g.memoryConfig.mode==="summarize"&&t&&t.waitUntil(Bt(e,g,h)),e.setState({...e.state,lastUpdated:new Date}),{status:x.status,error:x.error,engineState:d}}import{nanoid as lo}from"nanoid";function uo(o){let e=o.headers.get("X-User-Payload");if(!e)return null;try{let s=JSON.parse(e),t=typeof(s==null?void 0:s.email)=="string"?S(s.email):null;return t?{...s,email:t}:null}catch{return null}}async function _e(o,e,s,t){var n;try{let r=await e.json(),i=r.message;if(!i||typeof i!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let c=typeof r.userId=="string"?S(r.userId):null,p=uo(e),f=p==null?void 0:p.email;p?o.setState({...o.state,user:p,injectedUserId:f}):c&&!((n=o.state.user)!=null&&n.email)&&o.setState({...o.state,injectedUserId:c});let u=()=>f??c??o.state.injectedUserId??void 0;o.skillRefCache||(o.skillRefCache=new Map);let m=r.inputs&&typeof r.inputs=="object"?r.inputs:void 0;if(!o.state.engineState&&!await tt(o,s))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let l=f?`run-${lo(12)}`:null;l&&await o.registerManualRun(l,i,f);let d=await et({agent:o,env:s,ctx:t,payload:{text:i,inputs:m},skillRefCache:o.skillRefCache,user:p??void 0,resolveUserId:u});if(l&&t.waitUntil(o.completeManualRun(l,d.status==="completed"?"succeeded":"failed",d.error)),d.status==="failed")return new Response(JSON.stringify({error:d.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});let y=(await J(o)).reverse().find(w=>w.role==="assistant");return new Response(JSON.stringify({answer:(y==null?void 0:y.content)||""}),{headers:{"content-type":"application/json"}})}catch(r){return new Response(JSON.stringify({error:r.message}),{status:500,headers:{"content-type":"application/json"}})}}async function Oe(o){try{return await ut(o),await mt(o),o.skillRefCache&&o.skillRefCache.clear(),o.setState({...o.state,error:"",engineState:void 0,modelsCache:{},lastUpdated:new Date}),new Response(JSON.stringify({success:!0,messages:[]}),{headers:{"content-type":"application/json"}})}catch(e){return new Response(JSON.stringify({error:e.message}),{status:500,headers:{"content-type":"application/json"}})}}var $e="trigger:nonce:",mo=900*1e3,ke=class extends po{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 J(this);return new Response(JSON.stringify(t),{headers:{"content-type":"application/json"}})}if(s.pathname.endsWith("/context")){let t={"content-type":"application/json","access-control-allow-origin":"*"};if(!e.headers.get("X-User-Payload"))return new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:t});let n=s.searchParams.get("ref");if(n){let i=await ft(this,n);return i?new Response(JSON.stringify({entry:i}),{headers:t}):new Response(JSON.stringify({error:"Not found"}),{status:404,headers:t})}let r=await pt(this);return new Response(JSON.stringify({entries:r}),{headers:t})}return e.method==="POST"&&s.pathname.endsWith("/message")?_e(this,e,this.env,this.ctx):e.method==="DELETE"&&s.pathname.endsWith("/clear")?Oe(this):new Response("Ready to assist.")}async onConnect(e,s){var l,d,a,y,w;let[t,n]=e.server.split("::"),i=(l=(await K(t,this.env)).metadata)==null?void 0:l.tenant;this.secrets=await ht(this.env,i),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 h=s.request.headers.get("X-User-Payload");if(h)try{c=JSON.parse(h)}catch(g){console.warn("Failed to parse X-User-Payload",g)}}let p=await W(t,this.env);this.setState({...this.state,user:c||null,sessionId:n,engineState:{flowData:{...p,tenant:i,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 J(this);U(e,P.SERVER_HISTORY,JSON.stringify({messages:f}));let m=(((d=p==null?void 0:p.state)==null?void 0:d.nodes)??(p==null?void 0:p.nodes)??[]).find(h=>h.type==="startNode");if(m){let h={allow_images:((a=m.data)==null?void 0:a.allow_images)??!1,allow_documents:((y=m.data)==null?void 0:y.allow_documents)??!1,greeting:(w=m.data)==null?void 0:w.greeting};U(e,P.SERVER_CONFIG,JSON.stringify(h))}}async onMessage(e,s){if(typeof s!="string")return;let t=s.indexOf(":");if(t===-1)return;let n=s.substring(0,t),r=s.substring(t+1);if(!n||!r)return;let c={[P.USER_MESSAGE]:p=>this.onUserMessage(e,p),[P.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[P.USER_AUTH]:p=>this.onUserAuth(e,p),[P.USER_IDENTITY]:p=>this.onUserIdentity(e,p)}[n];c&&await c(r)}async onUserMessage(e,s){let t=rt(s),n=this.hasAuditableUser()?`run-${fo(12)}`:null;n&&await this.registerManualRun(n,t.text);let r=await et({agent:this,env:this.env,ctx:this.ctx,payload:t,connection:e,secrets:this.secrets,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:this.state.user,resolveUserId:()=>this.resolveSessionUserId(),onServerEvent:i=>{U(e,P.SERVER_EVENT,JSON.stringify(i))},onError:i=>{U(e,P.SERVER_ERROR,i)},onMemoryRef:i=>{U(e,P.SERVER_EVENT,JSON.stringify({type:"info:memory:updated",content:{ref:i}}))},onSecretsLoaded:i=>{this.secrets=i}});n&&this.ctx.waitUntil(this.completeManualRun(n,r.status==="completed"?"succeeded":"failed",r.error))}hasAuditableUser(e){var s;return!!(e||(s=this.state.user)!=null&&s.email)}registerManualRun(e,s,t){var p,f;let{tenant:n,flowId:r,chatId:i}=((p=this.state.engineState)==null?void 0:p.flowData)??{},c=t||((f=this.state.user)==null?void 0:f.email);return!n||!r||!i||!c?Promise.resolve():fe(this.env,{id:e,tenant:n,flowId:r,userId:c,sessionId:i,triggerType:"manual",label:s==null?void 0:s.slice(0,120)})}completeManualRun(e,s,t){return yt(this.env,e,{status:s,error:t})}async enqueueTrigger(e){var n;if(!(e!=null&&e.runId)||!(e!=null&&e.flowId))return{queued:!1};if(e.nonce&&!await this.claimTriggerNonce(e.nonce))return console.warn(`[AgentDO] rejected replayed trigger nonce ${e.nonce}`),{queued:!1,duplicate:!0};let s=e.userId;return s&&!((n=this.state.user)!=null&&n.email)&&this.state.injectedUserId!==s&&this.setState({...this.state,injectedUserId:s}),{queued:!0,taskId:await this.queue("processTrigger",e)}}async claimTriggerNonce(e){let s=`${$e}${e}`;if(await this.ctx.storage.get(s))return!1;let t=Date.now();await this.ctx.storage.put(s,t);let r=[...(await this.ctx.storage.list({prefix:$e})).entries()].filter(([,i])=>t-i>mo).map(([i])=>i);return r.length>0&&await this.ctx.storage.delete(r),!0}async processTrigger(e){if(!(await pe(this.env,e.runId)).claimed){console.warn(`[AgentDO] trigger ${e.triggerId} skipped \u2014 run ${e.runId} already claimed`);return}try{this.state.engineState||await tt(this,this.env);let t=Y(v(this.state.engineState)),n=jt(t,e.inputs||{},e.label),r=await et({agent:this,env:this.env,ctx:this.ctx,payload:{text:n,inputs:e.inputs||{}},secrets:this.secrets,composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>e.userId||this.resolveSessionUserId(),onSecretsLoaded:i=>{this.secrets=i}});await yt(this.env,e.runId,{status:r.status==="completed"?"succeeded":"failed",error:r.error})}catch(t){let n=t instanceof Error?t.message:"Trigger execution failed";throw await yt(this.env,e.runId,{status:"failed",error:n}),t}}async onUserIdentity(e,s){let t=S(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=Ht(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 ut(this),await mt(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear();let s=this.state.engineState?{...this.state.engineState,cycle:void 0}:void 0;this.setState({...this.state,error:"",engineState:s,modelsCache:{},lastUpdated:new Date}),e&&U(e,P.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await ue(this);let e=await J(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 rr(o){let e=o.state;if(!e)return null;let s=["startNode","answerNode"];for(let t of s)if(!e.nodes.some(r=>r.type===t))return!1;return e.nodes.find(t=>t.type==="startNode")}import{importSPKI as go,jwtVerify as yo}from"jose";function Fe(o){let e={};if(!o)return e;let s=o.split(";");for(let t of s){let n=t.indexOf("=");if(n>-1){let r=t.slice(0,n).trim(),i=t.slice(n+1).trim();r&&(e[r]=decodeURIComponent(i))}}return e}function ho(o){return(typeof o.email=="string"?o.email.trim():"")||null}async function X(o,e,s){let t=Fe(o.headers.get("cookie")),n=new URL(o.url),r=t.access_token||n.searchParams.get("access_token"),i=await wo(e,r);if(i.ok){let c=i.payload,p=ho(c);return p?{id:c.sub,email:p,name:c.name,first_name:c.given_name,last_name:c.family_name,tenant:c.tenant,roles:c["ora-roles"],db_name:c.db_name||null,user_id:c.user_id||null}:null}return null}async function wo(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
|
+
`):"";t.context={user_input:x,user_images:I,files:O},t.tokenUsage={promptTokens:0,completionTokens:0,totalTokens:0},(l=s==null?void 0:s.onServerEvent)==null||l.call(s,{type:"agent:start",content:"Execution started",timestamp:Date.now()});let{startNode:M,error:b}=ro(t.flowData);if(!M)u="failed",m=b||"Flow Format Error",(d=s==null?void 0:s.onError)==null||d.call(s,m);else{let F=Y(M.data),{values:k,errors:A}=bt(F,g==null?void 0:g.inputs);if(A.length>0)return u="failed",m=`Invalid flow inputs: ${A.join("; ")}`,(a=s==null?void 0:s.onError)==null||a.call(s,m),{status:u,error:m};t.context={...t.context,inputs:k,...k},t.context.user_input||(t.context.user_input=x),await n(M),(y=s==null?void 0:s.onServerEvent)==null||y.call(s,{type:"agent:telemetry",content:{durationMs:Date.now()-f,tokenUsage:t.tokenUsage},timestamp:Date.now()})}}catch(g){u="failed",m=g instanceof Error?g.message:"Agent execution failed",(w=s==null?void 0:s.onError)==null||w.call(s,m)}finally{(h=s==null?void 0:s.onServerEvent)==null||h.call(s,{type:"agent:complete",content:{status:u,durationMs:Date.now()-f},timestamp:Date.now()})}return{status:u,error:m}},c={startNode:Ft,classifierNode:_t,llmNode:$t,memoNode:kt,answerNode:Nt,apiNode:At};return i}function ro(o){var u;let e=(o==null?void 0:o.state)??o;if(!e||!e.nodes||!e.edges||e.edges.length===0)return{error:"Flow is missing state, nodes, or edges."};let s=e.nodes.filter(m=>m.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(m=>m.type==="answerNode");if(n.length===0)return{error:"Flow must include at least one ANSWER node."};let r=new Map;for(let m of e.edges)r.has(m.source)||r.set(m.source,[]),r.get(m.source).push(m.target);let i=new Map;for(let m of e.edges)i.has(m.target)||i.set(m.target,[]),i.get(m.target).push(m.source);let c=Re(t.id,r),p=new Set;for(let m of n){let l=Re(m.id,i);for(let d of l)p.add(d)}let f=[];for(let m of c)if(!p.has(m)){let l=e.nodes.find(d=>d.id===m);if(l){let d=((u=l.data)==null?void 0:u.label)||"";f.push(`${m}(${d},${l.type})`)}}return f.length>0?{error:`The following nodes reachable from START do not lead to any ANSWER node: ${f.join(", ")}`}:{startNode:t}}function Re(o,e){let s=new Set,t=[o];for(s.add(o);t.length>0;){let n=t.shift(),r=e.get(n)||[];for(let i of r)s.has(i)||(s.add(i),t.push(i))}return s}function io(o,e){var s;return((s=o.state)==null?void 0:s.nodes.find(t=>t.id===e))||null}function ao(o,e,s){var c;let t=e==null?void 0:e.state;if(!t)return null;let n=t.edges.filter(p=>p.source===o.id);if(n.length===0)return null;let r=n[0].target;if(o.type==="classifierNode"&&((c=s==null?void 0:s.context)!=null&&c.classified_id)){let p=s.context.classified_id,f=n.find(u=>u.sourceHandle===`source-${p}`);f?r=f.target:console.log(`No matching edge, falling back to first: ${r}`)}return io(e,r)}async function Te(o,e){var t,n;let s=(t=e==null?void 0:e.flowData)==null?void 0:t.flowId;if(!(o!=null&&o.HX_CORE_URL)||!s)return{engineState:e,refreshed:!1};try{let r=await W(s,o),i={...e,flowData:{...r,tenant:e.flowData.tenant,flowId:s,chatId:e.flowData.chatId}},c=r==null?void 0:r.stateVersion,p=typeof c=="number"&&c!==((n=e.flowData)==null?void 0:n.stateVersion);return{engineState:i,refreshed:p}}catch(r){return console.error(`[flowRefresh] fetch failed for flow ${s}:`,r),{engineState:e,refreshed:!1}}}function Ne(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 Ce=async(o,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),`${JSON.stringify(o)}`};async function tt(o,e){var r,i;let s=o.id||o.name||"",[t,n]=String(s).split("::");if(!t||!n)return null;try{let p=(r=(await K(t,e)).metadata)==null?void 0:r.tenant,f=await W(t,e),u=(i=o.state)==null?void 0:i.user,m={flowData:{...f,tenant:p,flowId:t,chatId:n},executedNodes:[],context:u?{user:u}:{}};return o.setState({...o.state,engineState:m}),m}catch(c){return console.error("Failed to initialize engine state:",c),null}}async function et(o){var O,M,b,F,k;let{agent:e,env:s,ctx:t,payload:n,connection:r}=o,i=Date.now(),c=[],p=async()=>await J(e),f=async A=>{await ne(e,A)},u=async A=>{if(e.state.modelsCache&&e.state.modelsCache[A])return e.state.modelsCache[A];try{let{fetchOraModel:N}=await import("./oraApi-YIJGMXX7.js"),L=await N(A,s);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[A]:L}}),L}catch(N){throw console.error(`Error fetching model ${A}:`,N),N}},m={id:co(),role:"user",type:"text",content:n.text,images:n.images,ts:Date.now()};await f(m);let l={onChangeState:A=>{e.setState({...e.state,engineState:A})},onServerEvent:async A=>{var N;await((N=o.onServerEvent)==null?void 0:N.call(o,A)),c.push(A)},onTelemetry:async A=>{var N,L,D,q,Q,Z;await Ce({...A,userId:o.resolveUserId(),tenant:((L=(N=e.state.engineState)==null?void 0:N.flowData)==null?void 0:L.tenant)||"",flowId:((q=(D=e.state.engineState)==null?void 0:D.flowData)==null?void 0:q.flowId)||"",sessionId:((Z=(Q=e.state.engineState)==null?void 0:Q.flowData)==null?void 0:Z.chatId)||""},s)},onError:A=>{var N;(N=o.onError)==null||N.call(o,A),e.setState({...e.state,error:A})}},d=e.state.engineState?{...e.state.engineState}:null;if(d){let{engineState:A,refreshed:N}=await Te(s,d);d=A,N&&e.setState({...e.state,engineState:d,modelsCache:{}})}else if(d=await tt(e,s),!d){let A="Failed to initialize agent";return l.onError(A),{status:"failed",error:A}}let a=o.secrets;if(!a||Object.keys(a).length===0){let A=(O=d.flowData)==null?void 0:O.tenant;a=A?await ht(s,A):{},(M=o.onSecretsLoaded)==null||M.call(o,a)}let y=o.user??e.state.user??void 0;y&&!((b=d.context)!=null&&b.user)&&(d.context={...d.context||{},user:y});let w=at(v(d)),h=typeof d.cycle=="number"?d.cycle:0;w.enabled&&(h=await fe(e,d),d.cycle=h,e.setState({...e.state,engineState:d}));let g=me(e,{env:s,ctx:t,conn:r,getMessages:p,setMessages:f,getOraModel:u,secrets:a,userAuth:o.userAuth,user:y,composioSessions:o.composioSessions,publicOrigin:o.publicOrigin,skillRefCache:o.skillRefCache},d,h,o.onMemoryRef),x=await Ie(g,d,l)(n),{tenant:I,flowId:R,chatId:$}=d.flowData??{};return I&&R&&$&&t.waitUntil(Ne(s,{id:`${R}::${$}`,tenant:I,flowId:R,sessionId:$,userId:o.resolveUserId(),title:(F=n.text)==null?void 0:F.slice(0,120),turnTs:i,events:c})),x.status==="completed"&&((k=g.memoryConfig)!=null&&k.enabled)&&g.memoryConfig.mode==="summarize"&&t&&t.waitUntil(Wt(e,g,h)),e.setState({...e.state,lastUpdated:new Date}),{status:x.status,error:x.error,engineState:d}}import{nanoid as lo}from"nanoid";function uo(o){let e=o.headers.get("X-User-Payload");if(!e)return null;try{let s=JSON.parse(e),t=typeof(s==null?void 0:s.email)=="string"?S(s.email):null;return t?{...s,email:t}:null}catch{return null}}async function Ae(o,e,s,t){var n;try{let r=await e.json(),i=r.message;if(!i||typeof i!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let c=typeof r.userId=="string"?S(r.userId):null,p=uo(e),f=p==null?void 0:p.email;p?o.setState({...o.state,user:p,injectedUserId:f}):c&&!((n=o.state.user)!=null&&n.email)&&o.setState({...o.state,injectedUserId:c});let u=()=>f??c??o.state.injectedUserId??void 0;o.skillRefCache||(o.skillRefCache=new Map);let m=r.inputs&&typeof r.inputs=="object"?r.inputs:void 0;if(!o.state.engineState&&!await tt(o,s))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let l=f?`run-${lo(12)}`:null;l&&await o.registerManualRun(l,i,f);let d=await et({agent:o,env:s,ctx:t,payload:{text:i,inputs:m},skillRefCache:o.skillRefCache,user:p??void 0,resolveUserId:u});if(l&&t.waitUntil(o.completeManualRun(l,d.status==="completed"?"succeeded":"failed",d.error)),d.status==="failed")return new Response(JSON.stringify({error:d.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});let y=(await J(o)).reverse().find(w=>w.role==="assistant");return new Response(JSON.stringify({answer:(y==null?void 0:y.content)||""}),{headers:{"content-type":"application/json"}})}catch(r){return new Response(JSON.stringify({error:r.message}),{status:500,headers:{"content-type":"application/json"}})}}async function _e(o){try{return await ut(o),await mt(o),o.skillRefCache&&o.skillRefCache.clear(),o.setState({...o.state,error:"",engineState:void 0,modelsCache:{},lastUpdated:new Date}),new Response(JSON.stringify({success:!0,messages:[]}),{headers:{"content-type":"application/json"}})}catch(e){return new Response(JSON.stringify({error:e.message}),{status:500,headers:{"content-type":"application/json"}})}}var Oe="trigger:nonce:",mo=900*1e3,$e=class extends po{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 J(this);return new Response(JSON.stringify(t),{headers:{"content-type":"application/json"}})}if(s.pathname.endsWith("/context")){let t={"content-type":"application/json","access-control-allow-origin":"*"};if(!e.headers.get("X-User-Payload"))return new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:t});let n=s.searchParams.get("ref");if(n){let i=await ft(this,n);return i?new Response(JSON.stringify({entry:i}),{headers:t}):new Response(JSON.stringify({error:"Not found"}),{status:404,headers:t})}let r=await pt(this);return new Response(JSON.stringify({entries:r}),{headers:t})}return e.method==="POST"&&s.pathname.endsWith("/message")?Ae(this,e,this.env,this.ctx):e.method==="DELETE"&&s.pathname.endsWith("/clear")?_e(this):new Response("Ready to assist.")}async onConnect(e,s){var l,d,a,y,w;let[t,n]=e.server.split("::"),i=(l=(await K(t,this.env)).metadata)==null?void 0:l.tenant;this.secrets=await ht(this.env,i),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 h=s.request.headers.get("X-User-Payload");if(h)try{c=JSON.parse(h)}catch(g){console.warn("Failed to parse X-User-Payload",g)}}let p=await W(t,this.env);this.setState({...this.state,user:c||null,sessionId:n,engineState:{flowData:{...p,tenant:i,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 J(this);U(e,P.SERVER_HISTORY,JSON.stringify({messages:f}));let m=(((d=p==null?void 0:p.state)==null?void 0:d.nodes)??(p==null?void 0:p.nodes)??[]).find(h=>h.type==="startNode");if(m){let h={allow_images:((a=m.data)==null?void 0:a.allow_images)??!1,allow_documents:((y=m.data)==null?void 0:y.allow_documents)??!1,greeting:(w=m.data)==null?void 0:w.greeting};U(e,P.SERVER_CONFIG,JSON.stringify(h))}}async onMessage(e,s){if(typeof s!="string")return;let t=s.indexOf(":");if(t===-1)return;let n=s.substring(0,t),r=s.substring(t+1);if(!n||!r)return;let c={[P.USER_MESSAGE]:p=>this.onUserMessage(e,p),[P.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[P.USER_AUTH]:p=>this.onUserAuth(e,p),[P.USER_IDENTITY]:p=>this.onUserIdentity(e,p)}[n];c&&await c(r)}async onUserMessage(e,s){let t=rt(s),n=this.hasAuditableUser()?`run-${fo(12)}`:null;n&&await this.registerManualRun(n,t.text);let r=await et({agent:this,env:this.env,ctx:this.ctx,payload:t,connection:e,secrets:this.secrets,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:this.state.user,resolveUserId:()=>this.resolveSessionUserId(),onServerEvent:i=>{U(e,P.SERVER_EVENT,JSON.stringify(i))},onError:i=>{U(e,P.SERVER_ERROR,i)},onMemoryRef:i=>{U(e,P.SERVER_EVENT,JSON.stringify({type:"info:memory:updated",content:{ref:i}}))},onSecretsLoaded:i=>{this.secrets=i}});n&&this.ctx.waitUntil(this.completeManualRun(n,r.status==="completed"?"succeeded":"failed",r.error))}hasAuditableUser(e){var s;return!!(e||(s=this.state.user)!=null&&s.email)}registerManualRun(e,s,t){var p,f;let{tenant:n,flowId:r,chatId:i}=((p=this.state.engineState)==null?void 0:p.flowData)??{},c=t||((f=this.state.user)==null?void 0:f.email);return!n||!r||!i||!c?Promise.resolve():pe(this.env,{id:e,tenant:n,flowId:r,userId:c,sessionId:i,label:s==null?void 0:s.slice(0,120)})}completeManualRun(e,s,t){return yt(this.env,e,{status:s,error:t})}async enqueueTrigger(e){var n;if(!(e!=null&&e.runId)||!(e!=null&&e.flowId))return{queued:!1};if(e.nonce&&!await this.claimTriggerNonce(e.nonce))return console.warn(`[AgentDO] rejected replayed trigger nonce ${e.nonce}`),{queued:!1,duplicate:!0};let s=e.runAsUserId;return s&&!((n=this.state.user)!=null&&n.email)&&this.state.injectedUserId!==s&&this.setState({...this.state,injectedUserId:s}),{queued:!0,taskId:await this.queue("processTrigger",e)}}async claimTriggerNonce(e){let s=`${Oe}${e}`;if(await this.ctx.storage.get(s))return!1;let t=Date.now();await this.ctx.storage.put(s,t);let r=[...(await this.ctx.storage.list({prefix:Oe})).entries()].filter(([,i])=>t-i>mo).map(([i])=>i);return r.length>0&&await this.ctx.storage.delete(r),!0}async processTrigger(e){if(!(await ue(this.env,e.runId)).claimed){console.warn(`[AgentDO] activation ${e.activationId} skipped \u2014 run ${e.runId} already claimed`);return}try{this.state.engineState||await tt(this,this.env);let t=Y(v(this.state.engineState)),n=Lt(t,e.inputs||{},e.label),r=await et({agent:this,env:this.env,ctx:this.ctx,payload:{text:n,inputs:e.inputs||{}},secrets:this.secrets,composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>e.runAsUserId||this.resolveSessionUserId(),onSecretsLoaded:i=>{this.secrets=i}});await yt(this.env,e.runId,{status:r.status==="completed"?"succeeded":"failed",error:r.error})}catch(t){let n=t instanceof Error?t.message:"Trigger execution failed";throw await yt(this.env,e.runId,{status:"failed",error:n}),t}}async onUserIdentity(e,s){let t=S(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=jt(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 ut(this),await mt(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear();let s=this.state.engineState?{...this.state.engineState,cycle:void 0}:void 0;this.setState({...this.state,error:"",engineState:s,modelsCache:{},lastUpdated:new Date}),e&&U(e,P.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await de(this);let e=await J(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 or(o){let e=o.state;if(!e)return null;let s=["startNode","answerNode"];for(let t of s)if(!e.nodes.some(r=>r.type===t))return!1;return e.nodes.find(t=>t.type==="startNode")}import{importSPKI as go,jwtVerify as yo}from"jose";function ke(o){let e={};if(!o)return e;let s=o.split(";");for(let t of s){let n=t.indexOf("=");if(n>-1){let r=t.slice(0,n).trim(),i=t.slice(n+1).trim();r&&(e[r]=decodeURIComponent(i))}}return e}function ho(o){return(typeof o.email=="string"?o.email.trim():"")||null}async function X(o,e,s){let t=ke(o.headers.get("cookie")),n=new URL(o.url),r=t.access_token||n.searchParams.get("access_token"),i=await wo(e,r);if(i.ok){let c=i.payload,p=ho(c);return p?{id:c.sub,email:p,name:c.name,first_name:c.given_name,last_name:c.family_name,tenant:c.tenant,roles:c["ora-roles"],db_name:c.db_name||null,user_id:c.user_id||null}:null}return null}async function wo(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 go(s,"RS256");try{let{payload:n,protectedHeader:r}=await yo(e,t);return{ok:!0,payload:n,protectedHeader:r}}catch(n){return console.error("JWT verification failed:",n),{ok:!1,payload:null,protectedHeader:null}}}async function
|
|
42
|
-
`)}async function je(o,e){let s=await crypto.subtle.importKey("raw",Me.encode(o),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return Io(await crypto.subtle.sign("HMAC",s,Me.encode(e)))}function No(o,e){if(o.length!==e.length)return!1;let s=0;for(let t=0;t<o.length;t++)s|=o.charCodeAt(t)^e.charCodeAt(t);return s===0}async function wr(o){let e=String(o.timestamp??Math.floor(Date.now()/1e3)),s=await je(o.secret,Le({timestamp:e,nonce:o.nonce,tenant:o.tenant,destination:o.destination,body:o.body}));return{"content-type":"application/json",[be]:o.tenant,[De]:e,[Ue]:o.nonce,[Pe]:`v1=${s}`}}async function He(o){var f,u,m,l,d;if(!((f=o.secret)!=null&&f.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(u=o.headers.get(be))==null?void 0:u.trim(),s=(m=o.headers.get(De))==null?void 0:m.trim(),t=(l=o.headers.get(Ue))==null?void 0:l.trim(),n=(d=o.headers.get(Pe))==null?void 0:d.trim();if(!e||!s||!t||!n)return{ok:!1,error:"missing signature headers"};if(!n.startsWith("v1="))return{ok:!1,error:"unsupported signature version"};let r=Number(s);if(!Number.isFinite(r))return{ok:!1,error:"invalid timestamp"};let i=Math.floor((o.now??Date.now())/1e3),c=o.toleranceSeconds??300;if(Math.abs(i-r)>c)return{ok:!1,error:"stale timestamp"};let p=await je(o.secret.trim(),Le({timestamp:s,nonce:t,tenant:e,destination:o.url,body:o.body}));return No(n.slice(3),p)?{ok:!0,tenant:e,nonce:t,timestamp:r}:{ok:!1,error:"signature mismatch"}}var Co=["manual","qstash","execute_now","hook"],q=(o,e=200)=>new Response(JSON.stringify(o),{status:e,headers:{"content-type":"application/json"}});async function Ee(o,e,s){var f;if(new URL(o.url).pathname!=="/api/triggers/dispatch")return;if(o.method!=="POST")return q({error:"Method not allowed"},405);let n=await o.text(),r=await He({secret:e.HX_API_KEY,body:n,url:o.url,headers:o.headers});if(!r.ok)return console.warn(`[triggers] rejected dispatch: ${r.error}`),q({error:"Invalid signature"},401);let i;try{i=JSON.parse(n)}catch{return q({error:"Invalid payload"},400)}if(!(i!=null&&i.runId)||!(i!=null&&i.flowId)||!(i!=null&&i.userId)||!(i!=null&&i.tenant))return q({error:"runId, flowId, userId and tenant are required"},400);if(i.tenant!==r.tenant)return q({error:"Tenant mismatch"},403);if(!Co.includes(i.triggerType))return q({error:"Unsupported triggerType"},400);let c;try{c=await K(i.flowId,e)}catch{return q({error:"Flow not found"},404)}if(!((f=c==null?void 0:c.metadata)!=null&&f.tenant)||c.metadata.tenant!==i.tenant)return console.warn(`[triggers] flow ${i.flowId} does not belong to tenant ${i.tenant}`),q({error:"Tenant mismatch"},403);let p=await wt(e,{triggerType:i.triggerType,tenant:i.tenant,scheduleId:i.scheduleId,flowId:i.flowId,userId:i.userId,sessionId:i.sessionId,runId:i.runId,inputs:i.inputs||{},idempotencyKey:i.idempotencyKey,label:i.label,nonce:r.nonce});return p.status==="error"?q({error:p.error},502):p.status==="deduped"?q({deduped:!0,runId:p.runId},200):q({accepted:!0,runId:p.runId,taskId:p.taskId},202)}var Ao=/^[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 $r(o,e,s){var r,i,c,p;let t=new URL(o.url),n=await Ee(o,e,s);if(n instanceof Response)return n;if(t.pathname.startsWith("/a/")){let f=t.pathname.split("/"),u=f[2],m=f[3];try{if(!u)return Response.redirect(new URL("/",t.origin).toString(),302);let l;try{l=await K(u,e)}catch{return new Response("Flow not found",{status:404})}if(!l.metadata||((r=l.metadata)==null?void 0:r.status)!=="active")return new Response("NO chat",{status:404});if(((i=l.metadata)==null?void 0:i.visibility)==="private"&&!await X(o,e,s)){let a=new URL("/login",t.origin);return a.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(a.toString(),302)}if(!m){let d=crypto.randomUUID(),a=new URL(`/a/${u}/${d}`,t.origin);return Response.redirect(a.toString(),302)}if(!Ao.test(m))return new Response("Id del chat no v\xE1lido",{status:400})}catch(l){return console.error("Error accessing flow KV:",l),new Response("Flow error",{status:500})}}if(t.pathname.startsWith("/api/agent/flow")){let f=t.pathname.split("/"),u=f[4],m=f[5],l=`${u}::${m}`;try{let d=await X(o,e,s);if(!d){let g=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${g}) \u2014 Composio connections from tool editor will not apply`)}let a=new Headers(o.headers);a.delete("X-User-Payload"),d&&a.set("X-User-Payload",JSON.stringify(d));let y=new Request(o,{headers:a});return(await qe(e.AGENT,l)).fetch(y)}catch(d){return console.error("Error accessing agent:",d),new Response("Agent error",{status:500})}}if(t.pathname.startsWith("/api/ora/connect")){let f=t.pathname.split("/"),u=f[4],m=f[5];if(!u||!m)return new Response("Missing flowId or sessionId",{status:400});let l=o.headers.get("Authorization")||t.searchParams.get("authorization");if(!l)return new Response("Missing Authorization header",{status:401});try{let d=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${u}`,y=await(await fetch(d,{method:"GET",headers:{Authorization:l}})).json();if(((c=y.payload)==null?void 0:c.flowId)!==u)return console.error("FlowId mismatch:",(p=y.payload)==null?void 0:p.flowId,"!==",u),new Response("Validation error",{status:403});let w=`${u}::${m}`,h=await X(o,e,s);if(!h){let $=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${$}) \u2014 Composio connections from tool editor will not apply`)}let g=new Headers(o.headers);g.delete("X-User-Payload"),h&&g.set("X-User-Payload",JSON.stringify(h));let x=new Request(o,{headers:g});return(await qe(e.AGENT,w)).fetch(x)}catch(d){return console.error("Error in /api/ora/connect:",d),new Response("Internal error",{status:500})}}}function ot(o,e){return e.split(".").reduce((s,t)=>{if(s&&typeof s=="object")return s[t]},o)}function Pt(o,e){let s={payload:o.payload};for(let[t,n]of Object.entries(e.inputPaths||{})){let r=ot(o.payload,n);r!==void 0&&(s[t]=r)}return s}var Ve={provider:"telegram",deliveryId:o=>{let e=ot(o.payload,"update_id");return e===void 0?void 0:`telegram-${String(e)}`},toInputs:(o,e)=>{let s=ot(o.payload,"message.text");return{...Pt(o,e),...typeof s=="string"?{user_input:s}:{}}}},Ke={provider:"composio",deliveryId:o=>{let e=ot(o.payload,"id")??ot(o.payload,"data.id");return e===void 0?void 0:`composio-${String(e)}`},toInputs:Pt},Je={provider:"http",deliveryId:o=>{var e,s;return((e=o.headers)==null?void 0:e["x-delivery-id"])||((s=o.headers)==null?void 0:s["x-request-id"])},toInputs:Pt},Xe=new Map([[Ve.provider,Ve],[Ke.provider,Ke],[Je.provider,Je]]);function Mr(o){Xe.set(o.provider,o)}function _o(o){return Xe.get(o)}async function Pr(o,e,s){var n;let t=_o(e.provider);return t?wt(o,{triggerType:"hook",tenant:e.tenant,flowId:e.flowId,userId:e.userId,inputs:t.toInputs(s,e),idempotencyKey:s.deliveryId||((n=t.deliveryId)==null?void 0:n.call(t,s)),label:e.label||`${e.provider} hook`}):{status:"error",error:`No adapter registered for provider ${e.provider}`}}async function br(o,e,s){let t=new URL(o.url),n=o.method;if(!t.pathname.startsWith("/api/instances"))return;let r=await X(o,e,s);if(!r)return new Response("Unauthorized",{status:401});let i=e.HX_CORE_URL,c=e.HX_API_KEY;if(!i||!c)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let f=t.pathname.slice("/api/instances".length);f.startsWith("/")&&(f=f.slice(1)),f.endsWith("/")&&(f=f.slice(0,-1));let u="/ora/instances";f&&(u+=`/${f}`);let m=i.endsWith("/")?i.slice(0,-1):i,l=new URL(`${m}${u}`);t.searchParams.forEach((y,w)=>{l.searchParams.set(w,y)}),n==="GET"&&!f&&l.searchParams.set("filter_user_id",r.email);let d=new Headers;d.set("Authorization",c),d.set("Content-Type","application/json"),d.set("X-User-Payload",JSON.stringify(r));let a={method:n,headers:d};if(["POST","PATCH","PUT"].includes(n))try{a.body=await o.text()}catch(y){console.error("Error reading request body:",y)}try{let y=await fetch(l.toString(),a),w=await y.text();return new Response(w,{status:y.status,headers:{"Content-Type":"application/json"}})}catch(y){return console.error("Error proxying to flow instance backend:",y),new Response("Internal Server Error",{status:500})}}async function Hr(o,e,s){let t=new URL(o.url);if(o.method==="POST"&&t.pathname==="/auth/login")try{let n=await o.formData(),r=n.get("username"),i=n.get("password"),c=n.get("nextURL")||"/";if(!r||!i)return new Response("Missing username or password",{status:400});let p=new URLSearchParams;p.append("username",r),p.append("password",i),p.append("grant_type","password"),p.append("client_id",e.KC_CLIENT_ID),p.append("client_secret",e.KC_CLIENT_SECRET);let f=await fetch(`${e.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:p});if(!f.ok)return new Response("Unauthorized",{status:401});let u=await f.json(),m=new Response(null,{status:302,headers:{Location:c}}),l=(d,a,y)=>{m.headers.append("Set-Cookie",`${d}=${a}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${y}`)};return u.access_token&&l("access_token",u.access_token,u.expires_in),u.refresh_token&&l("refresh_token",u.refresh_token,u.refresh_expires_in||3600*24*30),u.id_token&&l("id_token",u.id_token,u.expires_in),m}catch(n){return console.error("Auth error:",n),new Response("Internal Server Error",{status:500})}if(t.pathname==="/auth/logout"){let n=new Response(null,{status:302,headers:{Location:"/login"}}),r=i=>{n.headers.append("Set-Cookie",`${i}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return r("access_token"),r("refresh_token"),r("id_token"),n}if(t.pathname.startsWith("/s/")){let n=await X(o,e,s);if(!n){let r=new URL("/login",t.origin);return r.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(r.toString(),302)}return{user:n}}}export{ke as AgentDO,Uo as FLOW_INPUT_NAME_RE,Lo as GENERATION_PARAM_KEYS,Ho as GENERATION_PRESETS,bo as MAX_USER_IDENTITY_LENGTH,es as MODEL_REGISTRY_SNAPSHOT,B as NodeType,jo as PRESET_PARAM_KEYS,Bo as REASONING_EFFORT_LEVELS,St as TOOL_REGISTRY_SNAPSHOT,Ue as TRIGGER_NONCE_HEADER,Pe as TRIGGER_SIGNATURE_HEADER,hr as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,be as TRIGGER_TENANT_HEADER,De as TRIGGER_TIMESTAMP_HEADER,Vo as applyPresetToOverrides,Jt as buildReasoningProviderOptions,wr as buildSignedTriggerHeaders,jt as buildTriggerMessageText,Fo as buildUrl,ho as canonicalUserEmail,pe as claimRun,mt as clearAllContext,ut as clearAllMessages,yt as completeRun,Oo as convertTempMessure,Tt as createRun,le as deleteContextToolsUpToCycle,Eo as deriveParamSupport,Pr as dispatchHookEvent,wt as dispatchTrigger,bt as embedText,ue as ensureAgentTables,Be as ensureContextTable,We as ensureMessagesTable,J as getAllMessages,ft as getContext,ae as getContextData,pt as getContextIndex,ts as getDefaultOutVars,ct as getEffectiveOutVars,Y as getFlowInputDefs,_o as getHookAdapter,de as getMaxContextCycle,os as getModelEntry,$r as handleAgentsRoutes,Hr as handleAuthRoutes,ur as handleCommonRoutes,br as handleIntancesRoutes,Ee as handleTriggerRoutes,Po as hashText,tt as initializeEngineState,te as jsonSchemaToZod,nt as logc,P as messageTypes,To as normalizeDestination,Ko as normalizeEffectiveParams,Lt as normalizeFlowInputs,Zo as normalizeModelEntry,Yo as normalizeReasoning,Xo as openAiReasoningParamSupport,Jo as openAiStandardParamSupport,Fe as parseCookies,Ht as parseUserAuth,rt as parseUserMessage,Et as pickNodeOverrides,Qo as reasoningEffortLevels,Vt as reasoningExposable,fe as recordRun,Mr as registerHookAdapter,So as registerProvider,ce as resolveContextRef,it as resolveModelById,lt as resolveOutVarRef,qo as resolvePreset,Kt as resolveReasoningEffort,Qt as resolveTemplate,et as runAgentTurn,ko as safeParseJSON,S as sanitizeUserIdentity,Ae as sendEvent,U as serverSend,ie as setContext,re as setMessage,je as signTriggerMaterial,Te as startEngine,Wo as stripUnsupportedFromNodeData,$o as tempTool,No as timingSafeEqualHex,qt as toStreamTextSettings,Le as triggerSignatureMaterial,Mo as twitter,rr as validateFlowStart,Do as vectorize,wo as verifyToken,He as verifyTriggerRequest,X as verifyUser,vo as walkPath,zo as workersAiParamSupport,Go as xaiParamSupport};
|
|
41
|
+
-----END PUBLIC KEY-----`,t=await go(s,"RS256");try{let{payload:n,protectedHeader:r}=await yo(e,t);return{ok:!0,payload:n,protectedHeader:r}}catch(n){return console.error("JWT verification failed:",n),{ok:!1,payload:null,protectedHeader:null}}}async function cr(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 qe}from"agents";import{getAgentByName as xo}from"agents";async function Fe(o,e){let s=e.sessionId||e.runAsUserId,t=e.inputs||{},n=e.runId;if(!n){let p=await It(o,{tenant:e.tenant,flowId:e.flowId,userId:e.runAsUserId,sessionId:s,triggerId:e.triggerId,triggerKind:e.triggerKind,invocationMode:e.invocationMode,activationId:e.activationId,deliveryId:void 0,externalDeliveryId:e.externalDeliveryId,correlationKey:e.correlationKey,inputs:t,label:e.label});if(!p)return{status:"error",error:"Failed to register run"};if(!p.created&&p.run.status!=="queued")return{status:"deduped",runId:p.run.id};n=p.run.id}let r={...e,sessionId:s,runId:n,inputs:t},c=await(await xo(o.AGENT,`${e.flowId}::${s}`)).enqueueTrigger(r);return c.duplicate?{status:"deduped",runId:n}:c.queued?{status:"queued",runId:n,activation:r,taskId:c.taskId}:{status:"error",error:"Failed to queue trigger"}}var Pe="x-ora-signature",De="x-ora-timestamp",Ue="x-ora-nonce",be="x-ora-tenant",fr=300,Me=new TextEncoder;function Ro(o){return[...new Uint8Array(o)].map(e=>e.toString(16).padStart(2,"0")).join("")}function Io(o){try{let e=new URL(o);return`${e.origin}${e.pathname.replace(/\/$/,"")}`}catch{return o.replace(/\/$/,"")}}function Le(o){return["v1",o.timestamp,o.nonce,o.tenant,Io(o.destination),o.body].join(`
|
|
42
|
+
`)}async function je(o,e){let s=await crypto.subtle.importKey("raw",Me.encode(o),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return Ro(await crypto.subtle.sign("HMAC",s,Me.encode(e)))}function To(o,e){if(o.length!==e.length)return!1;let s=0;for(let t=0;t<o.length;t++)s|=o.charCodeAt(t)^e.charCodeAt(t);return s===0}async function mr(o){let e=String(o.timestamp??Math.floor(Date.now()/1e3)),s=await je(o.secret,Le({timestamp:e,nonce:o.nonce,tenant:o.tenant,destination:o.destination,body:o.body}));return{"content-type":"application/json",[be]:o.tenant,[De]:e,[Ue]:o.nonce,[Pe]:`v1=${s}`}}async function He(o){var f,u,m,l,d;if(!((f=o.secret)!=null&&f.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(u=o.headers.get(be))==null?void 0:u.trim(),s=(m=o.headers.get(De))==null?void 0:m.trim(),t=(l=o.headers.get(Ue))==null?void 0:l.trim(),n=(d=o.headers.get(Pe))==null?void 0:d.trim();if(!e||!s||!t||!n)return{ok:!1,error:"missing signature headers"};if(!n.startsWith("v1="))return{ok:!1,error:"unsupported signature version"};let r=Number(s);if(!Number.isFinite(r))return{ok:!1,error:"invalid timestamp"};let i=Math.floor((o.now??Date.now())/1e3),c=o.toleranceSeconds??300;if(Math.abs(i-r)>c)return{ok:!1,error:"stale timestamp"};let p=await je(o.secret.trim(),Le({timestamp:s,nonce:t,tenant:e,destination:o.url,body:o.body}));return To(n.slice(3),p)?{ok:!0,tenant:e,nonce:t,timestamp:r}:{ok:!1,error:"signature mismatch"}}var V=(o,e=200)=>new Response(JSON.stringify(o),{status:e,headers:{"content-type":"application/json"}});async function Ee(o,e,s){var f;if(new URL(o.url).pathname!=="/api/triggers/dispatch")return;if(o.method!=="POST")return V({error:"Method not allowed"},405);let n=await o.text(),r=await He({secret:e.HX_API_KEY,body:n,url:o.url,headers:o.headers});if(!r.ok)return console.warn(`[triggers] rejected dispatch: ${r.error}`),V({error:"Invalid signature"},401);let i;try{i=JSON.parse(n)}catch{return V({error:"Invalid payload"},400)}if(!(i!=null&&i.runId)||!(i!=null&&i.flowId)||!(i!=null&&i.runAsUserId)||!(i!=null&&i.tenant)||!(i!=null&&i.activationId)||!(i!=null&&i.triggerId)||!(i!=null&&i.triggerKind)||!(i!=null&&i.invocationMode))return V({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(i.tenant!==r.tenant)return V({error:"Tenant mismatch"},403);let c;try{c=await K(i.flowId,e)}catch{return V({error:"Flow not found"},404)}if(!((f=c==null?void 0:c.metadata)!=null&&f.tenant)||c.metadata.tenant!==i.tenant)return console.warn(`[triggers] flow ${i.flowId} does not belong to tenant ${i.tenant}`),V({error:"Tenant mismatch"},403);let p=await Fe(e,{...i,sessionId:i.sessionId||i.runAsUserId,nonce:r.nonce});return p.status==="error"?V({error:p.error},502):p.status==="deduped"?V({deduped:!0,runId:p.runId},200):V({accepted:!0,runId:p.runId,taskId:p.taskId},202)}var No=/^[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 Cr(o,e,s){var r,i,c,p;let t=new URL(o.url),n=await Ee(o,e,s);if(n instanceof Response)return n;if(t.pathname.startsWith("/a/")){let f=t.pathname.split("/"),u=f[2],m=f[3];try{if(!u)return Response.redirect(new URL("/",t.origin).toString(),302);let l;try{l=await K(u,e)}catch{return new Response("Flow not found",{status:404})}if(!l.metadata||((r=l.metadata)==null?void 0:r.status)!=="active")return new Response("NO chat",{status:404});if(((i=l.metadata)==null?void 0:i.visibility)==="private"&&!await X(o,e,s)){let a=new URL("/login",t.origin);return a.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(a.toString(),302)}if(!m){let d=crypto.randomUUID(),a=new URL(`/a/${u}/${d}`,t.origin);return Response.redirect(a.toString(),302)}if(!No.test(m))return new Response("Id del chat no v\xE1lido",{status:400})}catch(l){return console.error("Error accessing flow KV:",l),new Response("Flow error",{status:500})}}if(t.pathname.startsWith("/api/agent/flow")){let f=t.pathname.split("/"),u=f[4],m=f[5],l=`${u}::${m}`;try{let d=await X(o,e,s);if(!d){let g=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${g}) \u2014 Composio connections from tool editor will not apply`)}let a=new Headers(o.headers);a.delete("X-User-Payload"),d&&a.set("X-User-Payload",JSON.stringify(d));let y=new Request(o,{headers:a});return(await qe(e.AGENT,l)).fetch(y)}catch(d){return console.error("Error accessing agent:",d),new Response("Agent error",{status:500})}}if(t.pathname.startsWith("/api/ora/connect")){let f=t.pathname.split("/"),u=f[4],m=f[5];if(!u||!m)return new Response("Missing flowId or sessionId",{status:400});let l=o.headers.get("Authorization")||t.searchParams.get("authorization");if(!l)return new Response("Missing Authorization header",{status:401});try{let d=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${u}`,y=await(await fetch(d,{method:"GET",headers:{Authorization:l}})).json();if(((c=y.payload)==null?void 0:c.flowId)!==u)return console.error("FlowId mismatch:",(p=y.payload)==null?void 0:p.flowId,"!==",u),new Response("Validation error",{status:403});let w=`${u}::${m}`,h=await X(o,e,s);if(!h){let $=new URL(o.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${$}) \u2014 Composio connections from tool editor will not apply`)}let g=new Headers(o.headers);g.delete("X-User-Payload"),h&&g.set("X-User-Payload",JSON.stringify(h));let x=new Request(o,{headers:g});return(await qe(e.AGENT,w)).fetch(x)}catch(d){return console.error("Error in /api/ora/connect:",d),new Response("Internal error",{status:500})}}}function ot(o,e){return e.split(".").reduce((s,t)=>{if(s&&typeof s=="object")return s[t]},o)}function Mt(o,e){let s={payload:o.payload};for(let[t,n]of Object.entries(e.inputPaths||{})){let r=ot(o.payload,n);r!==void 0&&(s[t]=r)}return s}var Ve={provider:"telegram",deliveryId:o=>{let e=ot(o.payload,"update_id");return e===void 0?void 0:`telegram-${String(e)}`},toInputs:(o,e)=>{let s=ot(o.payload,"message.text");return{...Mt(o,e),...typeof s=="string"?{user_input:s}:{}}}},Ke={provider:"composio",deliveryId:o=>{let e=ot(o.payload,"id")??ot(o.payload,"data.id");return e===void 0?void 0:`composio-${String(e)}`},toInputs:Mt},Je={provider:"http",deliveryId:o=>{var e,s;return((e=o.headers)==null?void 0:e["x-delivery-id"])||((s=o.headers)==null?void 0:s["x-request-id"])},toInputs:Mt},Xe=new Map([[Ve.provider,Ve],[Ke.provider,Ke],[Je.provider,Je]]);function _r(o){Xe.set(o.provider,o)}function Or(o){return Xe.get(o)}async function $r(o,e,s){return{status:"error",error:`Hook triggers (${e.provider}) are not available in Trigger Core phase 0`}}async function Mr(o,e,s){let t=new URL(o.url),n=o.method;if(!t.pathname.startsWith("/api/instances"))return;let r=await X(o,e,s);if(!r)return new Response("Unauthorized",{status:401});let i=e.HX_CORE_URL,c=e.HX_API_KEY;if(!i||!c)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let f=t.pathname.slice("/api/instances".length);f.startsWith("/")&&(f=f.slice(1)),f.endsWith("/")&&(f=f.slice(0,-1));let u="/ora/instances";f&&(u+=`/${f}`);let m=i.endsWith("/")?i.slice(0,-1):i,l=new URL(`${m}${u}`);t.searchParams.forEach((y,w)=>{l.searchParams.set(w,y)}),n==="GET"&&!f&&l.searchParams.set("filter_user_id",r.email);let d=new Headers;d.set("Authorization",c),d.set("Content-Type","application/json"),d.set("X-User-Payload",JSON.stringify(r));let a={method:n,headers:d};if(["POST","PATCH","PUT"].includes(n))try{a.body=await o.text()}catch(y){console.error("Error reading request body:",y)}try{let y=await fetch(l.toString(),a),w=await y.text();return new Response(w,{status:y.status,headers:{"Content-Type":"application/json"}})}catch(y){return console.error("Error proxying to flow instance backend:",y),new Response("Internal Server Error",{status:500})}}async function Ur(o,e,s){let t=new URL(o.url);if(o.method==="POST"&&t.pathname==="/auth/login")try{let n=await o.formData(),r=n.get("username"),i=n.get("password"),c=n.get("nextURL")||"/";if(!r||!i)return new Response("Missing username or password",{status:400});let p=new URLSearchParams;p.append("username",r),p.append("password",i),p.append("grant_type","password"),p.append("client_id",e.KC_CLIENT_ID),p.append("client_secret",e.KC_CLIENT_SECRET);let f=await fetch(`${e.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:p});if(!f.ok)return new Response("Unauthorized",{status:401});let u=await f.json(),m=new Response(null,{status:302,headers:{Location:c}}),l=(d,a,y)=>{m.headers.append("Set-Cookie",`${d}=${a}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${y}`)};return u.access_token&&l("access_token",u.access_token,u.expires_in),u.refresh_token&&l("refresh_token",u.refresh_token,u.refresh_expires_in||3600*24*30),u.id_token&&l("id_token",u.id_token,u.expires_in),m}catch(n){return console.error("Auth error:",n),new Response("Internal Server Error",{status:500})}if(t.pathname==="/auth/logout"){let n=new Response(null,{status:302,headers:{Location:"/login"}}),r=i=>{n.headers.append("Set-Cookie",`${i}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return r("access_token"),r("refresh_token"),r("id_token"),n}if(t.pathname.startsWith("/s/")){let n=await X(o,e,s);if(!n){let r=new URL("/login",t.origin);return r.searchParams.set("nextURL",`${t.pathname}${t.search}`),Response.redirect(r.toString(),302)}return{user:n}}}export{$e as AgentDO,Mo as FLOW_INPUT_NAME_RE,Do as GENERATION_PARAM_KEYS,bo as GENERATION_PRESETS,Po as MAX_USER_IDENTITY_LENGTH,So as MODEL_REGISTRY_SNAPSHOT,B as NodeType,Uo as PRESET_PARAM_KEYS,Go as REASONING_EFFORT_LEVELS,Zt as TOOL_REGISTRY_SNAPSHOT,Ue as TRIGGER_NONCE_HEADER,Pe as TRIGGER_SIGNATURE_HEADER,fr as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,be as TRIGGER_TENANT_HEADER,De as TRIGGER_TIMESTAMP_HEADER,Ho as applyPresetToOverrides,Kt as buildReasoningProviderOptions,mr as buildSignedTriggerHeaders,Lt as buildTriggerMessageText,Oo as buildUrl,ho as canonicalUserEmail,ue as claimRun,mt as clearAllContext,ut as clearAllMessages,yt as completeRun,Co as convertTempMessure,It as createRun,ce as deleteContextToolsUpToCycle,Lo as deriveParamSupport,$r as dispatchHookEvent,Fe as dispatchTrigger,Ut as embedText,de as ensureAgentTables,Be as ensureContextTable,We as ensureMessagesTable,J as getAllMessages,ft as getContext,ie as getContextData,pt as getContextIndex,Zo as getDefaultOutVars,ct as getEffectiveOutVars,Y as getFlowInputDefs,Or as getHookAdapter,le as getMaxContextCycle,vo as getModelEntry,Cr as handleAgentsRoutes,Ur as handleAuthRoutes,cr as handleCommonRoutes,Mr as handleIntancesRoutes,Ee as handleTriggerRoutes,ko as hashText,tt as initializeEngineState,vt as jsonSchemaToZod,nt as logc,P as messageTypes,Io as normalizeDestination,Eo as normalizeEffectiveParams,bt as normalizeFlowInputs,Bo as normalizeModelEntry,zo as normalizeReasoning,Vo as openAiReasoningParamSupport,qo as openAiStandardParamSupport,ke as parseCookies,jt as parseUserAuth,rt as parseUserMessage,Ht as pickNodeOverrides,Wo as reasoningEffortLevels,qt as reasoningExposable,pe as recordRun,_r as registerHookAdapter,Yo as registerProvider,ae as resolveContextRef,it as resolveModelById,lt as resolveOutVarRef,jo as resolvePreset,Vt as resolveReasoningEffort,Yt as resolveTemplate,et as runAgentTurn,_o as safeParseJSON,S as sanitizeUserIdentity,Ce as sendEvent,U as serverSend,re as setContext,ne as setMessage,je as signTriggerMaterial,Ie as startEngine,Xo as stripUnsupportedFromNodeData,Ao as tempTool,To as timingSafeEqualHex,Et as toStreamTextSettings,Le as triggerSignatureMaterial,$o as twitter,or as validateFlowStart,Fo as vectorize,wo as verifyToken,He as verifyTriggerRequest,X as verifyUser,Qo as walkPath,Jo as workersAiParamSupport,Ko as xaiParamSupport};
|
|
@@ -1,10 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Internal trigger surface of the tenant runtime.
|
|
3
|
-
*
|
|
4
|
-
* Every external provider (QStash today, hooks next) enters through the hx-ora gateway, which
|
|
5
|
-
* owns the provider credentials, resolves the tenant and registers the run. What arrives here is a
|
|
6
|
-
* request signed with this tenant runtime's `HX_API_KEY` and bound to this destination: the runtime authenticates
|
|
7
|
-
* it, confirms the flow really belongs to the claimed tenant and persists the work in the agent's
|
|
8
|
-
* FIFO queue, answering `202` without waiting for the agent.
|
|
3
|
+
* Receives a signed TriggerActivation from hx-ora and enqueues it in the agent FIFO queue.
|
|
9
4
|
*/
|
|
10
5
|
export declare function handleTriggerRoutes(request: Request, env: Env, _ctx: ExecutionContext): Promise<Response | undefined>;
|
|
@@ -2,7 +2,7 @@ import { Agent, type Connection, type ConnectionContext, type WSMessage } from '
|
|
|
2
2
|
import type { UserInterface } from 'lib/common/types/user-types';
|
|
3
3
|
import { type Message } from '../../common/types/agent-types';
|
|
4
4
|
import type { ContextIndexEntry, ContextRow, ContextUpsertInput, MemoryConfig } from '../../common/types/memory-types';
|
|
5
|
-
import type {
|
|
5
|
+
import type { TriggerActivation } from '../../common/types/trigger-types';
|
|
6
6
|
import type { FlowEngineState } from '../logic/FlowEngine';
|
|
7
7
|
import type { ComposioSessionMeta } from '../utils/composio';
|
|
8
8
|
import { type SecretsMap } from '../utils/secrets';
|
|
@@ -78,7 +78,7 @@ export declare class AgentDO extends Agent<Env, State> {
|
|
|
78
78
|
* The DO is the right place for the nonce: it is single-threaded per session and durable, so two
|
|
79
79
|
* concurrent replays of the same signed request cannot both get through.
|
|
80
80
|
*/
|
|
81
|
-
enqueueTrigger(
|
|
81
|
+
enqueueTrigger(activation: TriggerActivation): Promise<{
|
|
82
82
|
queued: boolean;
|
|
83
83
|
duplicate?: boolean;
|
|
84
84
|
taskId?: string;
|
|
@@ -96,7 +96,7 @@ export declare class AgentDO extends Agent<Env, State> {
|
|
|
96
96
|
* A failing claim throws instead of returning quietly: the Agents SDK retries the callback, so a
|
|
97
97
|
* momentary hx-ora outage delays the run rather than dropping it.
|
|
98
98
|
*/
|
|
99
|
-
processTrigger(
|
|
99
|
+
processTrigger(activation: TriggerActivation): Promise<void>;
|
|
100
100
|
/**
|
|
101
101
|
* Store a client-supplied session identity in persisted DO state.
|
|
102
102
|
* Used as `sessions.userId` fallback when no JWT user is present; JWT always wins.
|
|
@@ -1,29 +1,10 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
export interface DispatchTriggerInput {
|
|
3
|
-
triggerType: TriggerType;
|
|
4
|
-
tenant: string;
|
|
5
|
-
flowId: string;
|
|
6
|
-
/** Session owner email. Always resolved server-side, never from a provider payload. */
|
|
7
|
-
userId: string;
|
|
8
|
-
/** Defaults to `userId`, which is the operational session shared by schedules and hooks. */
|
|
9
|
-
sessionId?: string;
|
|
10
|
-
scheduleId?: string;
|
|
11
|
-
inputs?: FlowInputValues;
|
|
12
|
-
/** Provider delivery id; a repeat of the same key resolves to the same run. */
|
|
13
|
-
idempotencyKey?: string;
|
|
14
|
-
label?: string;
|
|
15
|
-
/**
|
|
16
|
-
* Run already registered upstream (the gateway registers it before dispatching). When omitted
|
|
17
|
-
* the run is reserved here, which is the path hooks handled inside the tenant take.
|
|
18
|
-
*/
|
|
19
|
-
runId?: string;
|
|
20
|
-
/** Single-use id of the signed request, rejected by the agent if it repeats. */
|
|
21
|
-
nonce?: string;
|
|
1
|
+
import type { TriggerActivation } from '../../common/types/trigger-types';
|
|
2
|
+
export interface DispatchTriggerInput extends TriggerActivation {
|
|
22
3
|
}
|
|
23
4
|
export type DispatchTriggerResult = {
|
|
24
5
|
status: 'queued';
|
|
25
6
|
runId: string;
|
|
26
|
-
|
|
7
|
+
activation: TriggerActivation;
|
|
27
8
|
taskId?: string;
|
|
28
9
|
} | {
|
|
29
10
|
status: 'deduped';
|
|
@@ -33,10 +14,6 @@ export type DispatchTriggerResult = {
|
|
|
33
14
|
error: string;
|
|
34
15
|
};
|
|
35
16
|
/**
|
|
36
|
-
* Single entry point that turns
|
|
37
|
-
*
|
|
38
|
-
* The run is reserved before queueing, but a reserved-yet-unqueued run is *not* treated as a
|
|
39
|
-
* duplicate: a delivery that failed between both steps would otherwise stay `queued` forever.
|
|
40
|
-
* Only a run that already left `queued` collapses into a dedupe.
|
|
17
|
+
* Single entry point that turns a normalized activation into queued work.
|
|
41
18
|
*/
|
|
42
19
|
export declare function dispatchTrigger(env: Env, input: DispatchTriggerInput): Promise<DispatchTriggerResult>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { FlowInputValues } from '../../common/types/trigger-types';
|
|
2
|
-
import {
|
|
2
|
+
import type { DispatchTriggerResult } from './dispatch';
|
|
3
3
|
/**
|
|
4
4
|
* Configuration stored when a hook is created. The `userId` is fixed here — provider payloads are
|
|
5
5
|
* never trusted to name the user, so a compromised or spoofed event cannot execute as someone else.
|
|
@@ -35,4 +35,4 @@ export declare function getHookAdapter(provider: string): HookAdapter | undefine
|
|
|
35
35
|
* run, idempotency and notification machinery as schedules. Provider-specific transports and
|
|
36
36
|
* their configuration UI live outside this contract.
|
|
37
37
|
*/
|
|
38
|
-
export declare function dispatchHookEvent(
|
|
38
|
+
export declare function dispatchHookEvent(_env: Env, binding: HookBinding, _event: HookEvent): Promise<DispatchTriggerResult>;
|
|
@@ -1,42 +1,36 @@
|
|
|
1
|
-
import type { FlowInputValues, RunStatus,
|
|
1
|
+
import type { FlowInputValues, RunStatus, TriggerKind, InvocationMode } from '../../common/types/trigger-types';
|
|
2
2
|
export interface RunRecord {
|
|
3
3
|
id: string;
|
|
4
4
|
tenant: string;
|
|
5
|
-
scheduleId?: string | null;
|
|
6
5
|
flowId: string;
|
|
7
6
|
userId: string;
|
|
8
7
|
sessionId: string;
|
|
9
|
-
|
|
8
|
+
triggerId?: string | null;
|
|
9
|
+
triggerKind?: TriggerKind | null;
|
|
10
|
+
invocationMode?: InvocationMode | null;
|
|
10
11
|
status: RunStatus;
|
|
11
12
|
inputs?: FlowInputValues | null;
|
|
12
13
|
}
|
|
13
14
|
export interface CreateRunInput {
|
|
14
15
|
id?: string;
|
|
15
16
|
tenant: string;
|
|
16
|
-
scheduleId?: string;
|
|
17
17
|
flowId: string;
|
|
18
18
|
userId: string;
|
|
19
19
|
sessionId: string;
|
|
20
|
-
|
|
20
|
+
triggerId?: string | null;
|
|
21
|
+
triggerKind?: TriggerKind | null;
|
|
22
|
+
invocationMode?: InvocationMode | null;
|
|
23
|
+
activationId?: string | null;
|
|
24
|
+
deliveryId?: string | null;
|
|
25
|
+
externalDeliveryId?: string | null;
|
|
26
|
+
correlationKey?: string | null;
|
|
21
27
|
inputs?: FlowInputValues;
|
|
22
|
-
idempotencyKey?: string;
|
|
23
28
|
label?: string;
|
|
24
29
|
}
|
|
25
|
-
/**
|
|
26
|
-
* Creates the run row, or returns the existing one when `idempotencyKey` was already seen
|
|
27
|
-
* (a retried delivery). `created: false` plus a still-`queued` status means the previous attempt
|
|
28
|
-
* never reached the queue, so the caller may safely queue it again.
|
|
29
|
-
*/
|
|
30
30
|
export declare function createRun(env: Env, input: CreateRunInput): Promise<{
|
|
31
31
|
run: RunRecord;
|
|
32
32
|
created: boolean;
|
|
33
33
|
} | null>;
|
|
34
|
-
/**
|
|
35
|
-
* Atomically moves `queued → running`. A losing caller gets `claimed: false` and must not execute.
|
|
36
|
-
*
|
|
37
|
-
* A transport or server error is *not* a lost claim: it throws so the queue callback fails and the
|
|
38
|
-
* Agents SDK retries it, instead of silently dropping work the run row still expects.
|
|
39
|
-
*/
|
|
40
34
|
export declare function claimRun(env: Env, runId: string): Promise<{
|
|
41
35
|
claimed: boolean;
|
|
42
36
|
run?: RunRecord;
|
|
@@ -46,12 +40,5 @@ export interface CompleteRunBody {
|
|
|
46
40
|
error?: string;
|
|
47
41
|
summary?: string;
|
|
48
42
|
}
|
|
49
|
-
/**
|
|
50
|
-
* Terminal transition; also flips the run's notification back to unread.
|
|
51
|
-
*
|
|
52
|
-
* Retried a few times because the turn already happened: re-running the callback would execute the
|
|
53
|
-
* flow twice. If every attempt fails the run stays `running` and hx-ora's stale sweep closes it.
|
|
54
|
-
*/
|
|
55
43
|
export declare function completeRun(env: Env | undefined, runId: string, body: CompleteRunBody, attempts?: number): Promise<boolean>;
|
|
56
|
-
/** Registers a manual run before execution so its eventual completion cannot race ahead of it. */
|
|
57
44
|
export declare function recordRun(env: Env | undefined, input: CreateRunInput): Promise<unknown>;
|