@hugex/ai 3.2.0-canary.2 → 3.2.0-canary.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import{a as k,b as Kn,c as Ce,d as Pe,e as gr,f as $e,g as yr,h as Fe,i as wr}from"./chunk-DEW7U7V7.js";import"./chunk-V35SRZAO.js";import{c as qn}from"./chunk-ZYIULB2P.js";import"./chunk-6AZ7RATD.js";import"./chunk-XXB57DMN.js";import"./chunk-3K4IMMLP.js";import{a as Rr,b as Sr}from"./chunk-RFWFJGER.js";import{A as Vn,B as Jn,C as Yn,D as Bn,E as Zn,F as Qn,G as er,H as tr,I as nr,J as rr,K as sr,L as or,M as Ne,N as ar,O as ir,P as cr,Q as lr,R as ur,S as dr,T as fr,U as pr,V as mr,W as Me,X as De,Y as hr,a as I,b as Ee,c as fn,d as P,e as Ie,f as pn,g as mn,h as gn,i as yn,j as hn,k as xe,l as L,m as wn,n as Te,o as ke,p as Ae,q as Ue,r as _e,s as be,t as J,u as Oe,v as ve,w as Gn,x as Wn,y as Xn,z as zn}from"./chunk-6JUKM6LT.js";import{A as Hn,B as jn,a as F,b as un,c as Re,d as dn,e as Se,f as Rn,g as Sn,h as En,i as In,j as xn,k as Tn,l as kn,m as An,n as Un,o as _n,p as bn,q as On,r as vn,s as Cn,t as Pn,u as Nn,v as Mn,w as Dn,x as $n,y as Fn,z as Ln}from"./chunk-QEZQZG6Z.js";import{a as tn}from"./chunk-RYHQGPX5.js";import{a as nn}from"./chunk-R6EKV3WR.js";import{a as on}from"./chunk-6HY7QUMP.js";import{a as rn,b as sn}from"./chunk-V6JSMX5A.js";import{a as ln}from"./chunk-Q7QHJJGR.js";import{a as b,b as C,c as an,d as cn}from"./chunk-YLDLDEUP.js";import{a as we}from"./chunk-U56YWPSI.js";import"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";import{Agent as Be}from"agents";import{nanoid as Mt}from"nanoid";async function pt(t){t.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 Le(t,e){t.sql`INSERT INTO messages (id, role, type, content, ts) VALUES (${e.id}, ${e.role}, ${e.type}, ${e.content}, ${e.ts})`}async function O(t){return t.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function H(t){t.sql`DELETE FROM messages`}async function He(t){await pt(t)}function Y(t){return{"Content-Type":"application/json",Authorization:t.HX_API_KEY}}function j(t){return!!(t!=null&&t.HX_ORA_URL)&&!!(t!=null&&t.HX_API_KEY)}var mt="anonymous:";function je(t,e){return(t==null?void 0:t.trim())||`${mt}${e}`}async function B(t,e){if(!j(t))return null;let r=await fetch(`${t.HX_ORA_URL}/internal/runs`,{method:"POST",headers:Y(t),body:JSON.stringify(e)});return r.ok?await r.json():(console.error("[oraTriggers] createRun failed",r.status,await r.text().catch(()=>"")),null)}async function N(t,e){if(!j(t))return{claimed:!0};let r=await fetch(`${t.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/claim`,{method:"POST",headers:Y(t)});if(!r.ok){let n=await r.text().catch(()=>"");throw new Error(`claimRun ${e} failed with ${r.status}: ${n}`)}return await r.json()}async function K(t,e,r,n=3){if(!j(t))return!0;for(let s=1;s<=n;s++){try{let a=await fetch(`${t.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/complete`,{method:"POST",headers:Y(t),body:JSON.stringify(r)});if(a.ok||a.status===409)return!0;if(a.status===404)return console.error(`[oraTriggers] completeRun ${e} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${e} attempt ${s} failed with ${a.status}`)}catch(a){console.warn(`[oraTriggers] completeRun ${e} attempt ${s} threw`,a)}s<n&&await new Promise(a=>setTimeout(a,250*s))}return console.error(`[oraTriggers] completeRun ${e} exhausted ${n} attempts; hx-ora will time the run out`),!1}async function Ke(t,e){if(!j(t))return Promise.resolve();try{return await B(t,e)}catch(r){return console.error("[oraTriggers] recordRun failed",r),null}}var Z=Object.freeze({}),gt="__SYSTEM_";function Q(t){return t.startsWith(gt)}function yt(t){let e={};for(let[r,n]of Object.entries(t))Q(r)||(e[r]=n);return Object.freeze(e)}function q(t){return(typeof t=="string"?t.trim():"")||"default"}async function qe(t,e,r){if(!e)return Z;let n=q(r);if(t.HX_ORA_URL&&t.HX_API_KEY)try{let a=new URL(`${t.HX_ORA_URL.replace(/\/$/,"")}/internal/secrets`);a.searchParams.set("org",n);let o=await fetch(a,{headers:{Authorization:t.HX_API_KEY}});if(o.ok){let i=await o.json();if(i.secrets)return yt(i.secrets)}else console.warn(`[secrets] API failed with status ${o.status}, falling back to KV`)}catch(a){console.error("[secrets] API request failed, falling back to KV",a)}let s=t.ORA_SECRETS;if(!s)return Z;try{let a={};return await ht(s,`${e}:${n}:`,a),n==="default"&&await wt(s,e,a),Object.freeze(a)}catch(a){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,org:n,err:a}),Z}}async function ht(t,e,r){let n=await t.list({prefix:e,limit:1e3});n.list_complete===!1&&console.warn(`[secrets] prefix=${e} exceeded list page; truncating to first 1000 keys`);let s=n.keys.filter(o=>{let i=o.name.slice(e.length);return i.length>0&&!i.includes(":")&&!Q(i)}),a=await Promise.all(s.map(async o=>{let i=await t.get(o.name);return i!==null?[o.name.slice(e.length),i]:null}));for(let o of a){if(!o)continue;let[i,c]=o;i&&(r[i]=c)}}async function wt(t,e,r){let n=`${e}:`,s=await t.list({prefix:n,limit:1e3});s.list_complete===!1&&console.warn(`[secrets] tenant=${e} legacy secrets exceeded list page; truncating to first 1000 keys`);let a=s.keys.filter(i=>{let c=i.name.slice(n.length);return c.length>0&&!c.includes(":")&&!Q(c)}),o=await Promise.all(a.map(async i=>{let c=i.name.slice(n.length);if(c in r)return null;let l=await t.get(i.name);return l!==null?[c,l]:null}));for(let i of o){if(!i)continue;let[c,l]=i;c&&(r[c]=l)}}function G(t){var s;let e=((s=t==null?void 0:t.flowData)==null?void 0:s.state)??(t==null?void 0:t.flowData),n=((e==null?void 0:e.nodes)??[]).find(a=>a.type==="startNode");return n==null?void 0:n.data}import{nanoid as vt}from"nanoid";import{streamText as Rt}from"ai";var St={short:`Up to ${L("short")} markdown lines (one fact or bullet per line). Keep constraints, working agreements, and the outline of anything already settled.`,medium:`Up to ${L("medium")} markdown lines. Group bullets by whatever this session is about (actors, constraints, decisions, current plan/state, open work). Under-remembering is worse than a few extra lines.`,long:`Up to ${L("long")} markdown lines. Same as medium, with one-line context on a decision or plan block when later turns will need it.`},Et=12,It=400,Ge=700;function xt(t,e=Et){let r=t.filter(s=>s.role==="user"||s.role==="assistant").slice(-e),n=[];for(let s of r){let a=typeof s.content=="string"?s.content:JSON.stringify(s.content??""),o=s.role==="assistant"?Ge:It,i=a.trim().replace(/\s+/g," ").slice(0,o);i&&n.push(`${s.role==="user"?"U":"A"}: ${i}`)}return n.join(`
2
- `)}function Tt(t){let e=t??{},r=e.promptTokens??e.inputTokens??0,n=e.completionTokens??e.outputTokens??0,s=e.totalTokens??r+n;return{promptTokens:r,completionTokens:n,totalTokens:s}}function kt(t){var e;for(let r=t.length-1;r>=0;r--)if(((e=t[r])==null?void 0:e.role)==="assistant"&&typeof t[r].content=="string")return t[r].content;return""}function At(t){var s,a;let e=((s=t.flowData)==null?void 0:s.state)??t.flowData,r=(e==null?void 0:e.nodes)??[],n=[];for(let o of r){if(o.type!=="answerNode")continue;let i=(a=t.results)==null?void 0:a[o.id];i!=null&&n.push(typeof i=="string"?i:JSON.stringify(i))}return n.join(`
3
- `)}function Ut(t){var n;let e=["You maintain a KEYPOINT memory for one agent session so later turns can continue without re-asking.",`Hard limit: ${t.maxTokens} tokens.`,St[t.length],"The session domain is unknown: personal, operational, technical, or mixed. Do not assume a personal-coaching frame.","Store facts that will still matter: who/what is in play, constraints and invariants, preferences, decisions, current state of the work, and the outline of anything the user accepted or asked to keep.","When something was confirmed (a plan, a process, a design, a sequence), keep a compact outline \u2014 enough to resume the next part \u2014 not the assistant\u2019s full wording.","Keep earlier facts unless the user superseded them. Merge, update, dedupe. Do not collapse memory to a single identity line plus one decision.","Never copy the conversation. Never write User:/Assistant:/U:/A: lines. Drop greetings, filler, and unanswered assistant questions.","If this turn added nothing durable, return the current memory unchanged.","If memory is empty and nothing durable happened, return exactly: (none)","Use the same language as the user. Return only the bullet list \u2014 no preamble."].join(" "),r=["Current keypoint memory:",'"""',t.previous.trim()||"(empty)",'"""',"","Recent session (for extraction only; do not transcribe):",'"""',((n=t.recentTurns)==null?void 0:n.trim())||"(none)",'"""',"","This turn:",`User said: ${t.userText.trim()||"(empty)"}`,t.assistantText.trim()?`Latest assistant reply (extract accepted plan/facts only): ${t.assistantText.trim().slice(0,Ge)}`:"",t.answers.trim()?`Answer outputs:
1
+ import{a as k,b as jn,c as Pe,d as Ne,e as mr,f as Fe,g as gr,h as Le,i as hr}from"./chunk-DEW7U7V7.js";import"./chunk-V35SRZAO.js";import{c as Kn}from"./chunk-ZYIULB2P.js";import"./chunk-6AZ7RATD.js";import"./chunk-XXB57DMN.js";import"./chunk-3K4IMMLP.js";import{a as wr,b as Rr}from"./chunk-RFWFJGER.js";import{A as zn,B as Vn,C as Jn,D as Yn,E as Bn,F as Zn,G as Qn,H as er,I as tr,J as nr,K as rr,L as sr,M as Me,N as or,O as ar,P as ir,Q as cr,R as lr,S as ur,T as dr,U as pr,V as fr,W as De,X as $e,Y as yr,a as I,b as Ie,c as dn,d as P,e as xe,f as pn,g as fn,h as mn,i as gn,j as yn,k as Te,l as L,m as hn,n as ke,o as Ae,p as Ue,q as _e,r as be,s as Oe,t as J,u as ve,v as Ce,w as qn,x as Gn,y as Wn,z as Xn}from"./chunk-6JUKM6LT.js";import{A as Ln,B as Hn,a as F,b as ln,c as Se,d as un,e as Ee,f as wn,g as Rn,h as Sn,i as En,j as In,k as xn,l as Tn,m as kn,n as An,o as Un,p as _n,q as bn,r as On,s as vn,t as Cn,u as Pn,v as Nn,w as Mn,x as Dn,y as $n,z as Fn}from"./chunk-QEZQZG6Z.js";import{a as en}from"./chunk-RYHQGPX5.js";import{a as tn}from"./chunk-R6EKV3WR.js";import{a as sn}from"./chunk-6HY7QUMP.js";import{a as nn,b as rn}from"./chunk-V6JSMX5A.js";import{a as cn}from"./chunk-Q7QHJJGR.js";import{a as b,b as C,c as on,d as an}from"./chunk-YLDLDEUP.js";import{a as Re}from"./chunk-U56YWPSI.js";import"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";import{Agent as Ze}from"agents";import{nanoid as Dt}from"nanoid";async function mt(t){t.sql`CREATE TABLE IF NOT EXISTS messages (id TEXT PRIMARY KEY, role TEXT NOT NULL, type TEXT NOT NULL, content TEXT NOT NULL, ts INTEGER NOT NULL)`}async function He(t,e){t.sql`INSERT INTO messages (id, role, type, content, ts) VALUES (${e.id}, ${e.role}, ${e.type}, ${e.content}, ${e.ts})`}async function O(t){return t.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function H(t){t.sql`DELETE FROM messages`}async function je(t){await mt(t)}function Y(t){return{"Content-Type":"application/json",Authorization:t.HX_API_KEY}}function j(t){return!!(t!=null&&t.HX_ORA_URL)&&!!(t!=null&&t.HX_API_KEY)}var gt="anonymous:";function Ke(t,e){return(t==null?void 0:t.trim())||`${gt}${e}`}async function B(t,e){if(!j(t))return null;let r=await fetch(`${t.HX_ORA_URL}/internal/runs`,{method:"POST",headers:Y(t),body:JSON.stringify(e)});return r.ok?await r.json():(console.error("[oraTriggers] createRun failed",r.status,await r.text().catch(()=>"")),null)}async function N(t,e){if(!j(t))return{claimed:!0};let r=await fetch(`${t.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/claim`,{method:"POST",headers:Y(t)});if(!r.ok){let n=await r.text().catch(()=>"");throw new Error(`claimRun ${e} failed with ${r.status}: ${n}`)}return await r.json()}async function K(t,e,r,n=3){if(!j(t))return!0;for(let s=1;s<=n;s++){try{let a=await fetch(`${t.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/complete`,{method:"POST",headers:Y(t),body:JSON.stringify(r)});if(a.ok||a.status===409)return!0;if(a.status===404)return console.error(`[oraTriggers] completeRun ${e} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${e} attempt ${s} failed with ${a.status}`)}catch(a){console.warn(`[oraTriggers] completeRun ${e} attempt ${s} threw`,a)}s<n&&await new Promise(a=>setTimeout(a,250*s))}return console.error(`[oraTriggers] completeRun ${e} exhausted ${n} attempts; hx-ora will time the run out`),!1}async function qe(t,e){if(!j(t))return Promise.resolve();try{return await B(t,e)}catch(r){return console.error("[oraTriggers] recordRun failed",r),null}}var Z=Object.freeze({}),yt="__SYSTEM_";function Q(t){return t.startsWith(yt)}function ht(t){let e={};for(let[r,n]of Object.entries(t))Q(r)||(e[r]=n);return Object.freeze(e)}function q(t){return(typeof t=="string"?t.trim():"")||"default"}async function Ge(t,e,r){if(!e)return Z;let n=q(r);if(t.HX_ORA_URL&&t.HX_API_KEY)try{let a=new URL(`${t.HX_ORA_URL.replace(/\/$/,"")}/internal/secrets`);a.searchParams.set("org",n);let o=await fetch(a,{headers:{Authorization:t.HX_API_KEY}});if(o.ok){let i=await o.json();if(i.secrets)return ht(i.secrets)}else console.warn(`[secrets] API failed with status ${o.status}, falling back to KV`)}catch(a){console.error("[secrets] API request failed, falling back to KV",a)}let s=t.ORA_SECRETS;if(!s)return Z;try{let a={};return await wt(s,`${e}:${n}:`,a),n==="default"&&await Rt(s,e,a),Object.freeze(a)}catch(a){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,org:n,err:a}),Z}}async function wt(t,e,r){let n=await t.list({prefix:e,limit:1e3});n.list_complete===!1&&console.warn(`[secrets] prefix=${e} exceeded list page; truncating to first 1000 keys`);let s=n.keys.filter(o=>{let i=o.name.slice(e.length);return i.length>0&&!i.includes(":")&&!Q(i)}),a=await Promise.all(s.map(async o=>{let i=await t.get(o.name);return i!==null?[o.name.slice(e.length),i]:null}));for(let o of a){if(!o)continue;let[i,c]=o;i&&(r[i]=c)}}async function Rt(t,e,r){let n=`${e}:`,s=await t.list({prefix:n,limit:1e3});s.list_complete===!1&&console.warn(`[secrets] tenant=${e} legacy secrets exceeded list page; truncating to first 1000 keys`);let a=s.keys.filter(i=>{let c=i.name.slice(n.length);return c.length>0&&!c.includes(":")&&!Q(c)}),o=await Promise.all(a.map(async i=>{let c=i.name.slice(n.length);if(c in r)return null;let l=await t.get(i.name);return l!==null?[c,l]:null}));for(let i of o){if(!i)continue;let[c,l]=i;c&&(r[c]=l)}}function G(t){var s;let e=((s=t==null?void 0:t.flowData)==null?void 0:s.state)??(t==null?void 0:t.flowData),n=((e==null?void 0:e.nodes)??[]).find(a=>a.type==="startNode");return n==null?void 0:n.data}import{nanoid as Ct}from"nanoid";import{streamText as St}from"ai";var Et={short:`Up to ${L("short")} markdown lines (one fact or bullet per line). Keep constraints, working agreements, and the outline of anything already settled.`,medium:`Up to ${L("medium")} markdown lines. Group bullets by whatever this session is about (actors, constraints, decisions, current plan/state, open work). Under-remembering is worse than a few extra lines.`,long:`Up to ${L("long")} markdown lines. Same as medium, with one-line context on a decision or plan block when later turns will need it.`},It=12,xt=400,We=700;function Tt(t,e=It){let r=t.filter(s=>s.role==="user"||s.role==="assistant").slice(-e),n=[];for(let s of r){let a=typeof s.content=="string"?s.content:JSON.stringify(s.content??""),o=s.role==="assistant"?We:xt,i=a.trim().replace(/\s+/g," ").slice(0,o);i&&n.push(`${s.role==="user"?"U":"A"}: ${i}`)}return n.join(`
2
+ `)}function kt(t){let e=t??{},r=e.promptTokens??e.inputTokens??0,n=e.completionTokens??e.outputTokens??0,s=e.totalTokens??r+n;return{promptTokens:r,completionTokens:n,totalTokens:s}}function At(t){var e;for(let r=t.length-1;r>=0;r--)if(((e=t[r])==null?void 0:e.role)==="assistant"&&typeof t[r].content=="string")return t[r].content;return""}function Ut(t){var s,a;let e=((s=t.flowData)==null?void 0:s.state)??t.flowData,r=(e==null?void 0:e.nodes)??[],n=[];for(let o of r){if(o.type!=="answerNode")continue;let i=(a=t.results)==null?void 0:a[o.id];i!=null&&n.push(typeof i=="string"?i:JSON.stringify(i))}return n.join(`
3
+ `)}function _t(t){var n;let e=["You maintain a KEYPOINT memory for one agent session so later turns can continue without re-asking.",`Hard limit: ${t.maxTokens} tokens.`,Et[t.length],"The session domain is unknown: personal, operational, technical, or mixed. Do not assume a personal-coaching frame.","Store facts that will still matter: who/what is in play, constraints and invariants, preferences, decisions, current state of the work, and the outline of anything the user accepted or asked to keep.","When something was confirmed (a plan, a process, a design, a sequence), keep a compact outline \u2014 enough to resume the next part \u2014 not the assistant\u2019s full wording.","Keep earlier facts unless the user superseded them. Merge, update, dedupe. Do not collapse memory to a single identity line plus one decision.","Never copy the conversation. Never write User:/Assistant:/U:/A: lines. Drop greetings, filler, and unanswered assistant questions.","If this turn added nothing durable, return the current memory unchanged.","If memory is empty and nothing durable happened, return exactly: (none)","Use the same language as the user. Return only the bullet list \u2014 no preamble."].join(" "),r=["Current keypoint memory:",'"""',t.previous.trim()||"(empty)",'"""',"","Recent session (for extraction only; do not transcribe):",'"""',((n=t.recentTurns)==null?void 0:n.trim())||"(none)",'"""',"","This turn:",`User said: ${t.userText.trim()||"(empty)"}`,t.assistantText.trim()?`Latest assistant reply (extract accepted plan/facts only): ${t.assistantText.trim().slice(0,We)}`:"",t.answers.trim()?`Answer outputs:
4
4
  ${t.answers.trim()}`:""].filter(Boolean).join(`
5
- `);return{system:e,user:r}}function _t(t){return ve(t.previous,Oe(t.userText),t.maxTokens)}async function bt(t){let e="",r;for await(let n of t.fullStream)n.type==="text-delta"&&(e+=n.text??n.delta??""),n.type==="error"&&(r=n.error instanceof Error?n.error.message:String(n.error??"stream error"));return{text:e.trim(),error:r}}async function Ot(t){if(t.fullStream&&typeof t.fullStream[Symbol.asyncIterator]=="function")return bt({fullStream:t.fullStream});try{return{text:((typeof t.text=="string"?t.text:await t.text)||"").trim()}}catch(e){return{text:"",error:e instanceof Error?e.message:String(e)}}}async function We(t){var l;let e=G(t.engineState);if(!e)return{status:"skipped",reason:"start_node_missing"};if(!ke(e))return{status:"skipped",reason:"memory_disabled"};let r=Ue(e),n=xe(r),s=Ae(e),a=J(t.previousContent||""),o=kt(t.messages),i=At(t.engineState),c=u=>{let m=_t({previous:a,userText:t.userText,maxTokens:n});return{status:"written",content:m,truncated:!1,modelId:s,fallback:!0,error:m?void 0:u}};try{let u=await $e(s,t.sessionEnv,{maxOutputTokens:n});if(!u)throw new Error(`Memory model '${s}' not found in registry`);let m=_e(r,(l=u.reasoning)==null?void 0:l.kind),{system:p,user:f}=Ut({previous:a,userText:t.userText,assistantText:o,answers:i,length:r,maxTokens:n,recentTurns:xt(t.messages)}),g=Me(u.reasoning),y=De(u.provider,{effort:g,exposeReasoning:!1,maxTokens:m}),w=Rt({model:u.modelHandle,system:p,messages:[{role:"user",content:f}],...Ne({...u.effectiveParams??{},maxOutputTokens:m}),...y?{providerOptions:y}:{}}),R=await Ot(w),S=Tt(await w.usage),U=J(R.text);if(be(U)&&(U=""),!U)return{...c(R.error||"Memory model returned empty text"),usage:S};let T=Te(U,n);return{status:"written",content:T.content,truncated:T.truncated,usage:S,modelId:s}}catch(u){let m=u instanceof Error?u.message:"Memory update failed";return console.error("Memory update failed:",u),c(m)}}async function Xe(t,e){var n,s;let r=(n=e==null?void 0:e.flowData)==null?void 0:n.flowId;if(!(t!=null&&t.HX_CORE_URL)||!r)return{engineState:e,refreshed:!1};try{let a=await C(r,t),o={...e,flowData:{...a,tenant:e.flowData.tenant,flowId:r,chatId:e.flowData.chatId}},i=a==null?void 0:a.stateVersion,c=typeof i=="number"&&i!==((s=e.flowData)==null?void 0:s.stateVersion);return{engineState:o,refreshed:c}}catch(a){return console.error(`[flowRefresh] fetch failed for flow ${r}:`,a),{engineState:e,refreshed:!1}}}function ze(t,e){return!t||!t.HX_ORA_URL||!t.HX_API_KEY?Promise.resolve():fetch(`${t.HX_ORA_URL}/internal/sessions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t.HX_API_KEY},body:JSON.stringify(e)}).catch(r=>{console.error("[sessionIndex] failed to index session",r)})}var Ve=async(t,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),`${JSON.stringify(t)}`};async function M(t,e){var a;let r=t.id||t.name||"",[n,s]=String(r).split("::");if(!n||!s)return null;try{let i=(a=(await b(n,e)).metadata)==null?void 0:a.tenant,l={flowData:{...await C(n,e),tenant:i,flowId:n,chatId:s},executedNodes:[],context:{}};return t.setState({...t.state,engineState:l}),l}catch(o){return console.error("Failed to initialize engine state:",o),null}}async function Ct(t,e,r){var n;if(e&&t.HX_CORE_URL&&t.HX_API_KEY)try{let s=await b(e,t),a=(n=s==null?void 0:s.metadata)==null?void 0:n.org;if(typeof a=="string"&&a.trim())return q(a)}catch(s){console.warn(`[secrets] could not read org for flow ${e}`,s)}return q(r)}async function D(t){var ne,re,se,oe,ae,ie,ce,le,ue,de,fe;let{agent:e,env:r,ctx:n,payload:s,connection:a}=t,o=Date.now(),i=[],c=t.runId?Ce():void 0,l=async()=>await O(e),u=async d=>{await Le(e,d)},m=async d=>{if(e.state.modelsCache&&e.state.modelsCache[d])return e.state.modelsCache[d];try{let{fetchOraModel:h}=await import("./oraApi-YIJGMXX7.js"),x=await h(d,r);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[d]:x}}),x}catch(h){throw console.error(`Error fetching model ${d}:`,h),h}},p={id:vt(),role:"user",type:"text",content:s.text,images:s.images,ts:Date.now()};await u(p);let f={onChangeState:d=>{e.setState({...e.state,engineState:d})},onServerEvent:async d=>{var h;await((h=t.onServerEvent)==null?void 0:h.call(t,d)),i.push(d)},onTelemetry:async d=>{var _,pe,me,ge,ye,he;let h=t.user,x=typeof(h==null?void 0:h.org)=="string"&&h.org.trim()?h.org.trim():"default";await Ve({...d,userId:t.resolveUserId(),tenant:((pe=(_=e.state.engineState)==null?void 0:_.flowData)==null?void 0:pe.tenant)||"",org:x,flowId:((ge=(me=e.state.engineState)==null?void 0:me.flowData)==null?void 0:ge.flowId)||"",sessionId:((he=(ye=e.state.engineState)==null?void 0:ye.flowData)==null?void 0:he.chatId)||""},r)},onError:d=>{var h;(h=t.onError)==null||h.call(t,d),e.setState({...e.state,error:d})},shouldStop:t.shouldStop},g=e.state.engineState?{...e.state.engineState}:null;if(g){let{engineState:d,refreshed:h}=await Xe(r,g);g=d,h&&e.setState({...e.state,engineState:g,modelsCache:{}})}else if(g=await M(e,r),!g){let d="Failed to initialize agent";return f.onError(d),{status:"failed",error:d}}let y=t.user??void 0,w=(ne=g.flowData)==null?void 0:ne.tenant,R=await Ct(r,(re=g.flowData)==null?void 0:re.flowId,y==null?void 0:y.org),S=w?await qe(r,w,R):{};(se=t.onSecretsLoaded)==null||se.call(t,S),g={...g,context:{...g.context||{},user:y}},e.setState({...e.state,user:y,engineState:g});let U={env:r,ctx:n,conn:a,getMessages:l,setMessages:u,getOraModel:m,secrets:S,userAuth:t.userAuth,user:y,composioSessions:t.composioSessions,publicOrigin:t.publicOrigin,skillRefCache:t.skillRefCache,runId:t.runId,outputCollector:c,agentMemory:typeof((oe=e.state.memory)==null?void 0:oe.content)=="string"?e.state.memory.content:"",shouldStop:t.shouldStop,workerStack:(ae=g.flowData)!=null&&ae.flowId?[g.flowData.flowId]:[],workerCalls:{count:0}},T=await Fe(U,g,f)(s),E=e.state.engineState??g;if(T.status==="completed")try{let d=await We({sessionEnv:U,engineState:E,previousContent:typeof((ie=e.state.memory)==null?void 0:ie.content)=="string"?e.state.memory.content:"",userText:s.text||"",messages:await l()});if(d.status==="skipped")await f.onServerEvent({type:"agent:memory",content:{skipped:!0,reason:d.reason},timestamp:Date.now()});else if(!d.content.trim())await f.onServerEvent({type:"agent:memory",content:{updated:!1,empty:!0,error:d.error,fallback:d.fallback},timestamp:Date.now()});else{let h={promptTokens:((ce=E.tokenUsage)==null?void 0:ce.promptTokens)??0,completionTokens:((le=E.tokenUsage)==null?void 0:le.completionTokens)??0,totalTokens:((ue=E.tokenUsage)==null?void 0:ue.totalTokens)??0};d.usage&&(h.promptTokens+=d.usage.promptTokens,h.completionTokens+=d.usage.completionTokens,h.totalTokens+=d.usage.totalTokens),E={...E,tokenUsage:h},e.setState({...e.state,engineState:E,memory:{content:d.content,updatedTs:Date.now(),...d.error?{lastError:d.error}:{},...d.fallback?{fallback:!0}:{}}}),await f.onTelemetry({type:"memory_update",payload:{model:d.modelId,truncated:d.truncated,usage:d.usage,fallback:d.fallback,error:d.error}}),await f.onServerEvent({type:"agent:memory",content:{updated:!0,truncated:d.truncated,fallback:d.fallback,error:d.error},timestamp:Date.now()})}}catch(d){let h=d instanceof Error?d.message:"Memory update failed";console.error("Memory update failed:",d),await f.onServerEvent({type:"agent:memory",content:{error:h},timestamp:Date.now()})}if(T.status==="completed"&&t.runId&&(c!=null&&c.hasOutputs())){let{flowId:d,chatId:h}=E.flowData??{};if(!d||!h)T={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await Pe(r,{flowId:d,sessionId:h,runId:t.runId,createdAt:new Date(o).toISOString(),data:c.snapshotData(),answerNodeIds:c.answerNodeIds()});let x={...E.results||{}};for(let _ of c.answerNodeIds())x[_]={...x[_]||{},persisted:!0,runId:t.runId};E={...E,results:x},e.setState({...e.state,engineState:E})}catch(x){let _=x instanceof Error?x.message:"Structured output persistence failed";f.onError(_),await f.onServerEvent({type:"error:answer-output",content:{runId:t.runId,error:_},timestamp:Date.now()}),T={status:"failed",error:_}}}let{tenant:$,flowId:z,chatId:V}=E.flowData??{},ft=(de=E.flowData)==null?void 0:de.org;return $&&z&&V&&n.waitUntil(ze(r,{id:`${z}::${V}`,tenant:$,org:ft,flowId:z,sessionId:V,userId:t.resolveUserId(),title:(fe=s.text)==null?void 0:fe.slice(0,120),turnTs:o,events:i})),e.setState({...e.state,lastUpdated:new Date}),{status:T.status,error:T.error,engineState:E}}import{nanoid as Pt}from"nanoid";function Nt(t){let e=t.headers.get("X-User-Payload");if(!e)return null;try{let r=JSON.parse(e),n=typeof(r==null?void 0:r.email)=="string"?P(r.email):null;return n?{...r,email:n}:null}catch{return null}}async function Je(t,e,r,n){var s;try{let a=await e.json(),o=a.message;if(!o||typeof o!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let i=typeof a.userId=="string"?P(a.userId):null,c=Nt(e),l=c==null?void 0:c.email;c?t.setState({...t.state,user:c,injectedUserId:l}):i&&!((s=t.state.user)!=null&&s.email)&&t.setState({...t.state,injectedUserId:i});let u=()=>l??i??t.state.injectedUserId??void 0;t.skillRefCache||(t.skillRefCache=new Map);let m=a.inputs&&typeof a.inputs=="object"?a.inputs:void 0;if(!t.state.engineState&&!await M(t,r))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let p=`run-${Pt(12)}`;await t.registerManualRun(p,o,u()),await N(r,p).catch(w=>{console.warn(`[AgentHTTP] could not mark manual run ${p} as running`,w)});let f;try{f=await D({agent:t,env:r,ctx:n,payload:{text:o,inputs:m},skillRefCache:t.skillRefCache,user:c??void 0,resolveUserId:u,runId:p,shouldStop:()=>t.isRunStopRequested(p)}),n.waitUntil(t.completeManualRun(p,f.status==="completed"?"succeeded":f.status==="stopped"?"skipped":"failed",f.error))}finally{await t.clearRunStopRequest(p)}if(f.status==="failed")return new Response(JSON.stringify({error:f.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});if(f.status==="stopped")return new Response(JSON.stringify({error:f.error||"Stopped by user"}),{status:409,headers:{"content-type":"application/json"}});let y=(await O(t)).reverse().find(w=>w.role==="assistant");return new Response(JSON.stringify({answer:(y==null?void 0:y.content)||""}),{headers:{"content-type":"application/json"}})}catch(a){return new Response(JSON.stringify({error:a.message}),{status:500,headers:{"content-type":"application/json"}})}}async function Ye(t){try{return await H(t),t.skillRefCache&&t.skillRefCache.clear(),t.setState({...t.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 Ze="trigger:nonce:",Dt=900*1e3,ee="run:stop:",Qe=class extends Be{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{},memory:void 0};constructor(e,r){super(e,r),this.requireStateValidation()}validateStateChange(e,r){if(r!=="server")throw new Error("Client state updates are forbidden")}requireStateValidation(){if(typeof Be.prototype.validateStateChange!="function")throw new Error("AgentDO requires agents >= 0.8.7 with validateStateChange; upgrade the tenant SDK")}resolveSessionUserId(){return this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async inspectPersistedSession(e){return e==="state"?{state:this.state}:e==="memory"?{memory:this.state.memory??null}:{messages:await O(this)}}async requestRunStop(e){return e!=null&&e.trim()?(await this.ctx.storage.put(`${ee}${e}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(e){return!!await this.ctx.storage.get(`${ee}${e}`)}async clearRunStopRequest(e){await this.ctx.storage.delete(`${ee}${e}`)}async onRequest(e){this.requireStateValidation();let r=new URL(e.url);if(r.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(r.pathname.endsWith("/history")){let n=await O(this);return new Response(JSON.stringify(n),{headers:{"content-type":"application/json"}})}return e.method==="POST"&&r.pathname.endsWith("/message")?Je(this,e,this.env,this.ctx):e.method==="DELETE"&&r.pathname.endsWith("/clear")?Ye(this):new Response("Ready to assist.")}async onConnect(e,r){var p,f,g,y,w;this.requireStateValidation();let[n,s]=e.server.split("::"),o=(p=(await b(n,this.env)).metadata)==null?void 0:p.tenant;this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let i=null;if(r.request){try{this.publicOrigin=new URL(r.request.url).origin}catch{}let R=r.request.headers.get("X-User-Payload");if(R)try{i=JSON.parse(R)}catch(S){console.warn("Failed to parse X-User-Payload",S)}}e.setState({...e.state,authorizedUser:i});let c=await C(n,this.env);this.setState({...this.state,user:i||null,sessionId:s,engineState:{flowData:{...c,tenant:o,flowId:n,chatId:s},executedNodes:[],context:i?{user:i}:{}}}),i||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let l=await O(this);k(e,I.SERVER_HISTORY,JSON.stringify({messages:l}));let m=(((f=c==null?void 0:c.state)==null?void 0:f.nodes)??(c==null?void 0:c.nodes)??[]).find(R=>R.type==="startNode");if(m){let R={allow_images:((g=m.data)==null?void 0:g.allow_images)??!1,allow_documents:((y=m.data)==null?void 0:y.allow_documents)??!1,greeting:(w=m.data)==null?void 0:w.greeting};k(e,I.SERVER_CONFIG,JSON.stringify(R))}}async onMessage(e,r){if(typeof r!="string")return;let n=r.indexOf(":");if(n===-1)return;let s=r.substring(0,n),a=r.substring(n+1);if(!s||!a)return;let i={[I.USER_MESSAGE]:c=>this.onUserMessage(e,c),[I.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[I.USER_AUTH]:c=>this.onUserAuth(e,c),[I.USER_IDENTITY]:c=>this.onUserIdentity(e,c)}[s];i&&await i(a)}async onUserMessage(e,r){var i;let n=Ee(r),s=((i=e.state)==null?void 0:i.authorizedUser)??void 0,a=()=>(s==null?void 0:s.email)??this.resolveSessionUserId(),o=`run-${Mt(12)}`;await this.registerManualRun(o,n.text,a()),await N(this.env,o).catch(c=>{console.warn(`[AgentDO] could not mark manual run ${o} as running`,c)});try{let c=await D({agent:this,env:this.env,ctx:this.ctx,payload:n,connection:e,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:s,resolveUserId:a,runId:o,shouldStop:()=>this.isRunStopRequested(o),onServerEvent:l=>{k(e,I.SERVER_EVENT,JSON.stringify(l))},onError:l=>{k(e,I.SERVER_ERROR,l)},onSecretsLoaded:l=>{this.secrets=l}});this.ctx.waitUntil(this.completeManualRun(o,c.status==="completed"?"succeeded":c.status==="stopped"?"skipped":"failed",c.error))}finally{await this.clearRunStopRequest(o)}}registerManualRun(e,r,n){var c;let{tenant:s,flowId:a,chatId:o}=((c=this.state.engineState)==null?void 0:c.flowData)??{};if(!s||!a||!o)return Promise.resolve();let i=je(n||this.resolveSessionUserId(),o);return Ke(this.env,{id:e,tenant:s,flowId:a,userId:i,sessionId:o,label:r==null?void 0:r.slice(0,120)})}completeManualRun(e,r,n){return K(this.env,e,{status:r,error:n})}async enqueueTrigger(e){var s;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 r=e.runAsUserId;return r&&!((s=this.state.user)!=null&&s.email)&&this.state.injectedUserId!==r&&this.setState({...this.state,injectedUserId:r}),{queued:!0,taskId:await this.queue("processTrigger",e)}}async claimTriggerNonce(e){let r=`${Ze}${e}`;if(await this.ctx.storage.get(r))return!1;let n=Date.now();await this.ctx.storage.put(r,n);let a=[...(await this.ctx.storage.list({prefix:Ze})).entries()].filter(([,o])=>n-o>Dt).map(([o])=>o);return a.length>0&&await this.ctx.storage.delete(a),!0}async processTrigger(e){if(!(await N(this.env,e.runId)).claimed){console.warn(`[AgentDO] activation ${e.activationId} skipped \u2014 run ${e.runId} already claimed`);return}try{this.state.engineState||await M(this,this.env);let n=Re(G(this.state.engineState)),s=Se(n,e.inputs||{},e.label),a=await D({agent:this,env:this.env,ctx:this.ctx,payload:{text:s,inputs:e.inputs||{}},composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>e.runAsUserId||this.resolveSessionUserId(),runId:e.runId,shouldStop:()=>this.isRunStopRequested(e.runId),onSecretsLoaded:o=>{this.secrets=o}});await K(this.env,e.runId,{status:a.status==="completed"?"succeeded":a.status==="stopped"?"skipped":"failed",error:a.error})}catch(n){let s=n instanceof Error?n.message:"Trigger execution failed";throw await K(this.env,e.runId,{status:"failed",error:s}),n}finally{await this.clearRunStopRequest(e.runId)}}async onUserIdentity(e,r){let n=P(r);if(!n){k(e,I.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:n}),k(e,I.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,r){let n=Ie(r);if(!n){k(e,I.SERVER_ERROR,"Invalid auth payload");return}let s=n.value.trim();s===""?delete this.userAuth[n.name]:this.userAuth[n.name]=n.value,k(e,I.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:n.name,set:s!==""}}))}async onClearHistory(e){await H(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear(),this.setState({...this.state,error:"",engineState:this.state.engineState,memory:this.state.memory,modelsCache:{},lastUpdated:new Date}),e&&k(e,I.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await He(this);let e=await O(this);`${JSON.stringify(e)}`}async onClose(e,r,n,s){console.log(`Session closed: ${this.state.sessionId} ${r} - ${n}`)}async onError(e){console.error("AgentDO encountered an error:",e)}};function Rs(t){let e=t.state;if(!e)return null;let r=["startNode","answerNode"];for(let n of r)if(!e.nodes.some(a=>a.type===n))return!1;return e.nodes.find(n=>n.type==="startNode")}import{importSPKI as $t,jwtVerify as Ft}from"jose";function W(t){let e={};if(!t)return e;let r=t.split(";");for(let n of r){let s=n.indexOf("=");if(s>-1){let a=n.slice(0,s).trim(),o=n.slice(s+1).trim();a&&(e[a]=decodeURIComponent(o))}}return e}function Lt(t){return(typeof t.email=="string"?t.email.trim():"")||null}async function v(t,e,r){let n=W(t.headers.get("cookie")),s=new URL(t.url),a=n.access_token||s.searchParams.get("access_token"),o=await Ht(e,a);if(o.ok){let i=o.payload,c=Lt(i);return c?{id:i.sub,email:c,name:i.name,first_name:i.given_name,last_name:i.family_name,tenant:i.tenant,org:typeof i.org=="string"?i.org:null,roles:i["ora-roles"],db_name:i.db_name||null,user_id:i.user_id||null}:null}return null}async function Ht(t,e){if(!e||typeof e!="string")return{ok:!1,payload:null,protectedHeader:null};if(!t.KC_RS256_PK)throw new Error("PK is not defined");let r=`-----BEGIN PUBLIC KEY-----
5
+ `);return{system:e,user:r}}function bt(t){return Ce(t.previous,ve(t.userText),t.maxTokens)}async function Ot(t){let e="",r;for await(let n of t.fullStream)n.type==="text-delta"&&(e+=n.text??n.delta??""),n.type==="error"&&(r=n.error instanceof Error?n.error.message:String(n.error??"stream error"));return{text:e.trim(),error:r}}async function vt(t){if(t.fullStream&&typeof t.fullStream[Symbol.asyncIterator]=="function")return Ot({fullStream:t.fullStream});try{return{text:((typeof t.text=="string"?t.text:await t.text)||"").trim()}}catch(e){return{text:"",error:e instanceof Error?e.message:String(e)}}}async function Xe(t){var l;let e=G(t.engineState);if(!e)return{status:"skipped",reason:"start_node_missing"};if(!Ae(e))return{status:"skipped",reason:"memory_disabled"};let r=_e(e),n=Te(r),s=Ue(e),a=J(t.previousContent||""),o=At(t.messages),i=Ut(t.engineState),c=u=>{let m=bt({previous:a,userText:t.userText,maxTokens:n});return{status:"written",content:m,truncated:!1,modelId:s,fallback:!0,error:m?void 0:u}};try{let u=await Fe(s,t.sessionEnv,{maxOutputTokens:n});if(!u)throw new Error(`Memory model '${s}' not found in registry`);let m=be(r,(l=u.reasoning)==null?void 0:l.kind),{system:f,user:p}=_t({previous:a,userText:t.userText,assistantText:o,answers:i,length:r,maxTokens:n,recentTurns:Tt(t.messages)}),g=De(u.reasoning),y=$e(u.provider,{effort:g,exposeReasoning:!1,maxTokens:m}),w=St({model:u.modelHandle,system:f,messages:[{role:"user",content:p}],...Me({...u.effectiveParams??{},maxOutputTokens:m}),...y?{providerOptions:y}:{}}),R=await vt(w),S=kt(await w.usage),U=J(R.text);if(Oe(U)&&(U=""),!U)return{...c(R.error||"Memory model returned empty text"),usage:S};let T=ke(U,n);return{status:"written",content:T.content,truncated:T.truncated,usage:S,modelId:s}}catch(u){let m=u instanceof Error?u.message:"Memory update failed";return console.error("Memory update failed:",u),c(m)}}async function ze(t,e){var n,s;let r=(n=e==null?void 0:e.flowData)==null?void 0:n.flowId;if(!(t!=null&&t.HX_CORE_URL)||!r)return{engineState:e,refreshed:!1};try{let a=await C(r,t),o={...e,flowData:{...a,tenant:e.flowData.tenant,flowId:r,chatId:e.flowData.chatId}},i=a==null?void 0:a.stateVersion,c=typeof i=="number"&&i!==((s=e.flowData)==null?void 0:s.stateVersion);return{engineState:o,refreshed:c}}catch(a){return console.error(`[flowRefresh] fetch failed for flow ${r}:`,a),{engineState:e,refreshed:!1}}}function Ve(t,e){return!t||!t.HX_ORA_URL||!t.HX_API_KEY?Promise.resolve():fetch(`${t.HX_ORA_URL}/internal/sessions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t.HX_API_KEY},body:JSON.stringify(e)}).catch(r=>{console.error("[sessionIndex] failed to index session",r)})}var Je=async(t,e)=>{fetch(`${e.DW_URL}/q/telemetry/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),`${JSON.stringify(t)}`};async function M(t,e){var a;let r=t.id||t.name||"",[n,s]=String(r).split("::");if(!n||!s)return null;try{let i=(a=(await b(n,e)).metadata)==null?void 0:a.tenant,l={flowData:{...await C(n,e),tenant:i,flowId:n,chatId:s},executedNodes:[],context:{}};return t.setState({...t.state,engineState:l}),l}catch(o){return console.error("Failed to initialize engine state:",o),null}}async function Pt(t,e,r){var n;if(e&&t.HX_CORE_URL&&t.HX_API_KEY)try{let s=await b(e,t),a=(n=s==null?void 0:s.metadata)==null?void 0:n.org;if(typeof a=="string"&&a.trim())return q(a)}catch(s){console.warn(`[secrets] could not read org for flow ${e}`,s)}return q(r)}async function D(t){var re,se,oe,ae,ie,ce,le,ue,de,pe,fe;let{agent:e,env:r,ctx:n,payload:s,connection:a}=t,o=Date.now(),i=[],c=t.runId?Pe():void 0,l=async()=>await O(e),u=async d=>{await He(e,d)},m=async d=>{if(e.state.modelsCache&&e.state.modelsCache[d])return e.state.modelsCache[d];try{let{fetchOraModel:h}=await import("./oraApi-YIJGMXX7.js"),x=await h(d,r);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[d]:x}}),x}catch(h){throw console.error(`Error fetching model ${d}:`,h),h}},f={id:Ct(),role:"user",type:"text",content:s.text,images:s.images,ts:Date.now()};await u(f);let p={onChangeState:d=>{e.setState({...e.state,engineState:d})},onServerEvent:async d=>{var h;await((h=t.onServerEvent)==null?void 0:h.call(t,d)),i.push(d)},onTelemetry:async d=>{var _,me,ge,ye,he,we;let h=t.user,x=typeof(h==null?void 0:h.org)=="string"&&h.org.trim()?h.org.trim():"default";await Je({...d,userId:t.resolveUserId(),tenant:((me=(_=e.state.engineState)==null?void 0:_.flowData)==null?void 0:me.tenant)||"",org:x,flowId:((ye=(ge=e.state.engineState)==null?void 0:ge.flowData)==null?void 0:ye.flowId)||"",sessionId:((we=(he=e.state.engineState)==null?void 0:he.flowData)==null?void 0:we.chatId)||""},r)},onError:d=>{var h;(h=t.onError)==null||h.call(t,d),e.setState({...e.state,error:d})},shouldStop:t.shouldStop},g=e.state.engineState?{...e.state.engineState}:null;if(g){let{engineState:d,refreshed:h}=await ze(r,g);g=d,h&&e.setState({...e.state,engineState:g,modelsCache:{}})}else if(g=await M(e,r),!g){let d="Failed to initialize agent";return p.onError(d),{status:"failed",error:d}}let y=t.user??void 0,w=(re=g.flowData)==null?void 0:re.tenant,R=await Pt(r,(se=g.flowData)==null?void 0:se.flowId,y==null?void 0:y.org),S=w?await Ge(r,w,R):{};(oe=t.onSecretsLoaded)==null||oe.call(t,S),g={...g,context:{...g.context||{},user:y}},e.setState({...e.state,user:y,engineState:g});let U={env:r,ctx:n,conn:a,getMessages:l,setMessages:u,getOraModel:m,secrets:S,userAuth:t.userAuth,user:y,composioSessions:t.composioSessions,publicOrigin:t.publicOrigin,skillRefCache:t.skillRefCache,runId:t.runId,outputCollector:c,agentMemory:typeof((ae=e.state.memory)==null?void 0:ae.content)=="string"?e.state.memory.content:"",shouldStop:t.shouldStop,workerStack:(ie=g.flowData)!=null&&ie.flowId?[g.flowData.flowId]:[],workerCalls:{count:0}},T=await Le(U,g,p)(s),E=e.state.engineState??g;if(T.status==="completed")try{let d=await Xe({sessionEnv:U,engineState:E,previousContent:typeof((ce=e.state.memory)==null?void 0:ce.content)=="string"?e.state.memory.content:"",userText:s.text||"",messages:await l()});if(d.status==="skipped")await p.onServerEvent({type:"agent:memory",content:{skipped:!0,reason:d.reason},timestamp:Date.now()});else if(!d.content.trim())await p.onServerEvent({type:"agent:memory",content:{updated:!1,empty:!0,error:d.error,fallback:d.fallback},timestamp:Date.now()});else{let h={promptTokens:((le=E.tokenUsage)==null?void 0:le.promptTokens)??0,completionTokens:((ue=E.tokenUsage)==null?void 0:ue.completionTokens)??0,totalTokens:((de=E.tokenUsage)==null?void 0:de.totalTokens)??0};d.usage&&(h.promptTokens+=d.usage.promptTokens,h.completionTokens+=d.usage.completionTokens,h.totalTokens+=d.usage.totalTokens),E={...E,tokenUsage:h},e.setState({...e.state,engineState:E,memory:{content:d.content,updatedTs:Date.now(),...d.error?{lastError:d.error}:{},...d.fallback?{fallback:!0}:{}}}),await p.onTelemetry({type:"memory_update",payload:{model:d.modelId,truncated:d.truncated,usage:d.usage,fallback:d.fallback,error:d.error}}),await p.onServerEvent({type:"agent:memory",content:{updated:!0,truncated:d.truncated,fallback:d.fallback,error:d.error},timestamp:Date.now()})}}catch(d){let h=d instanceof Error?d.message:"Memory update failed";console.error("Memory update failed:",d),await p.onServerEvent({type:"agent:memory",content:{error:h},timestamp:Date.now()})}if(T.status==="completed"&&t.runId&&(c!=null&&c.hasOutputs())){let{flowId:d,chatId:h}=E.flowData??{};if(!d||!h)T={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await Ne(r,{flowId:d,sessionId:h,runId:t.runId,createdAt:new Date(o).toISOString(),data:c.snapshotData(),answerNodeIds:c.answerNodeIds()});let x={...E.results||{}};for(let _ of c.answerNodeIds())x[_]={...x[_]||{},persisted:!0,runId:t.runId};E={...E,results:x},e.setState({...e.state,engineState:E})}catch(x){let _=x instanceof Error?x.message:"Structured output persistence failed";p.onError(_),await p.onServerEvent({type:"error:answer-output",content:{runId:t.runId,error:_},timestamp:Date.now()}),T={status:"failed",error:_}}}let{tenant:$,flowId:z,chatId:V}=E.flowData??{},ft=(pe=E.flowData)==null?void 0:pe.org;return $&&z&&V&&n.waitUntil(Ve(r,{id:`${z}::${V}`,tenant:$,org:ft,flowId:z,sessionId:V,userId:t.resolveUserId(),title:(fe=s.text)==null?void 0:fe.slice(0,120),turnTs:o,events:i})),e.setState({...e.state,lastUpdated:new Date}),{status:T.status,error:T.error,engineState:E}}import{nanoid as Nt}from"nanoid";function Mt(t){let e=t.headers.get("X-User-Payload");if(!e)return null;try{let r=JSON.parse(e),n=typeof(r==null?void 0:r.email)=="string"?P(r.email):null;return n?{...r,email:n}:null}catch{return null}}async function Ye(t,e,r,n){var s;try{let a=await e.json(),o=a.message;if(!o||typeof o!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let i=typeof a.userId=="string"?P(a.userId):null,c=Mt(e),l=c==null?void 0:c.email;c?t.setState({...t.state,user:c,injectedUserId:l}):i&&!((s=t.state.user)!=null&&s.email)&&t.setState({...t.state,injectedUserId:i});let u=()=>l??i??t.state.injectedUserId??void 0;t.skillRefCache||(t.skillRefCache=new Map);let m=a.inputs&&typeof a.inputs=="object"?a.inputs:void 0;if(!t.state.engineState&&!await M(t,r))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let f=`run-${Nt(12)}`;await t.registerManualRun(f,o,u()),await N(r,f).catch(w=>{console.warn(`[AgentHTTP] could not mark manual run ${f} as running`,w)});let p;try{p=await D({agent:t,env:r,ctx:n,payload:{text:o,inputs:m},skillRefCache:t.skillRefCache,user:c??void 0,resolveUserId:u,runId:f,shouldStop:()=>t.isRunStopRequested(f)}),n.waitUntil(t.completeManualRun(f,p.status==="completed"?"succeeded":p.status==="stopped"?"skipped":"failed",p.error))}finally{await t.clearRunStopRequest(f)}if(p.status==="failed")return new Response(JSON.stringify({error:p.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});if(p.status==="stopped")return new Response(JSON.stringify({error:p.error||"Stopped by user"}),{status:409,headers:{"content-type":"application/json"}});let y=(await O(t)).reverse().find(w=>w.role==="assistant");return new Response(JSON.stringify({answer:(y==null?void 0:y.content)||""}),{headers:{"content-type":"application/json"}})}catch(a){return new Response(JSON.stringify({error:a.message}),{status:500,headers:{"content-type":"application/json"}})}}async function Be(t){try{return await H(t),t.skillRefCache&&t.skillRefCache.clear(),t.setState({...t.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 Qe="trigger:nonce:",$t=900*1e3,ee="run:stop:",et=class extends Ze{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{},memory:void 0};constructor(e,r){super(e,r),this.requireStateValidation()}validateStateChange(e,r){if(r!=="server")throw new Error("Client state updates are forbidden")}requireStateValidation(){if(typeof Ze.prototype.validateStateChange!="function")throw new Error("AgentDO requires agents >= 0.8.7 with validateStateChange; upgrade the tenant SDK")}resolveSessionUserId(){return this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async inspectPersistedSession(e){return e==="state"?{state:this.state}:e==="memory"?{memory:this.state.memory??null}:{messages:await O(this)}}async requestRunStop(e){return e!=null&&e.trim()?(await this.ctx.storage.put(`${ee}${e}`,Date.now()),{accepted:!0}):{accepted:!1}}async isRunStopRequested(e){return!!await this.ctx.storage.get(`${ee}${e}`)}async clearRunStopRequest(e){await this.ctx.storage.delete(`${ee}${e}`)}async onRequest(e){this.requireStateValidation();let r=new URL(e.url);if(r.pathname.endsWith("/state"))return new Response(JSON.stringify(this.state),{headers:{"content-type":"application/json"}});if(r.pathname.endsWith("/history")){let n=await O(this);return new Response(JSON.stringify(n),{headers:{"content-type":"application/json"}})}return e.method==="POST"&&r.pathname.endsWith("/message")?Ye(this,e,this.env,this.ctx):e.method==="DELETE"&&r.pathname.endsWith("/clear")?Be(this):new Response("Ready to assist.")}async onConnect(e,r){var f,p,g,y,w;this.requireStateValidation();let[n,s]=e.server.split("::"),o=(f=(await b(n,this.env)).metadata)==null?void 0:f.tenant;this.userAuth={},this.composioSessions={},this.publicOrigin=void 0;let i=null;if(r.request){try{this.publicOrigin=new URL(r.request.url).origin}catch{}let R=r.request.headers.get("X-User-Payload");if(R)try{i=JSON.parse(R)}catch(S){console.warn("Failed to parse X-User-Payload",S)}}e.setState({...e.state,authorizedUser:i});let c=await C(n,this.env);this.setState({...this.state,user:i||null,sessionId:s,engineState:{flowData:{...c,tenant:o,flowId:n,chatId:s},executedNodes:[],context:i?{user:i}:{}}}),i||console.warn("[AgentDO] WebSocket connected without authenticated user \u2014 Composio manual auth requires login (access_token on socket URL)");let l=await O(this);k(e,I.SERVER_HISTORY,JSON.stringify({messages:l}));let m=(((p=c==null?void 0:c.state)==null?void 0:p.nodes)??(c==null?void 0:c.nodes)??[]).find(R=>R.type==="startNode");if(m){let R={allow_images:((g=m.data)==null?void 0:g.allow_images)??!1,allow_documents:((y=m.data)==null?void 0:y.allow_documents)??!1,greeting:(w=m.data)==null?void 0:w.greeting};k(e,I.SERVER_CONFIG,JSON.stringify(R))}}async onMessage(e,r){if(typeof r!="string")return;let n=r.indexOf(":");if(n===-1)return;let s=r.substring(0,n),a=r.substring(n+1);if(!s||!a)return;let i={[I.USER_MESSAGE]:c=>this.onUserMessage(e,c),[I.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[I.USER_AUTH]:c=>this.onUserAuth(e,c),[I.USER_IDENTITY]:c=>this.onUserIdentity(e,c)}[s];i&&await i(a)}async onUserMessage(e,r){var i;let n=Ie(r),s=((i=e.state)==null?void 0:i.authorizedUser)??void 0,a=()=>(s==null?void 0:s.email)??this.resolveSessionUserId(),o=`run-${Dt(12)}`;await this.registerManualRun(o,n.text,a()),await N(this.env,o).catch(c=>{console.warn(`[AgentDO] could not mark manual run ${o} as running`,c)});try{let c=await D({agent:this,env:this.env,ctx:this.ctx,payload:n,connection:e,userAuth:this.userAuth,composioSessions:this.composioSessions,publicOrigin:this.publicOrigin,skillRefCache:this.skillRefCache,user:s,resolveUserId:a,runId:o,shouldStop:()=>this.isRunStopRequested(o),onServerEvent:l=>{k(e,I.SERVER_EVENT,JSON.stringify(l))},onError:l=>{k(e,I.SERVER_ERROR,l)},onSecretsLoaded:l=>{this.secrets=l}});this.ctx.waitUntil(this.completeManualRun(o,c.status==="completed"?"succeeded":c.status==="stopped"?"skipped":"failed",c.error))}finally{await this.clearRunStopRequest(o)}}registerManualRun(e,r,n){var c;let{tenant:s,flowId:a,chatId:o}=((c=this.state.engineState)==null?void 0:c.flowData)??{};if(!s||!a||!o)return Promise.resolve();let i=Ke(n||this.resolveSessionUserId(),o);return qe(this.env,{id:e,tenant:s,flowId:a,userId:i,sessionId:o,label:r==null?void 0:r.slice(0,120)})}completeManualRun(e,r,n){return K(this.env,e,{status:r,error:n})}async enqueueTrigger(e){var s;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 r=e.runAsUserId;return r&&!((s=this.state.user)!=null&&s.email)&&this.state.injectedUserId!==r&&this.setState({...this.state,injectedUserId:r}),{queued:!0,taskId:await this.queue("processTrigger",e)}}async claimTriggerNonce(e){let r=`${Qe}${e}`;if(await this.ctx.storage.get(r))return!1;let n=Date.now();await this.ctx.storage.put(r,n);let a=[...(await this.ctx.storage.list({prefix:Qe})).entries()].filter(([,o])=>n-o>$t).map(([o])=>o);return a.length>0&&await this.ctx.storage.delete(a),!0}async processTrigger(e){if(!(await N(this.env,e.runId)).claimed){console.warn(`[AgentDO] activation ${e.activationId} skipped \u2014 run ${e.runId} already claimed`);return}try{this.state.engineState||await M(this,this.env);let n=Se(G(this.state.engineState)),s=Ee(n,e.inputs||{},e.label),a=await D({agent:this,env:this.env,ctx:this.ctx,payload:{text:s,inputs:e.inputs||{}},composioSessions:this.composioSessions,skillRefCache:this.skillRefCache,resolveUserId:()=>e.runAsUserId||this.resolveSessionUserId(),runId:e.runId,shouldStop:()=>this.isRunStopRequested(e.runId),onSecretsLoaded:o=>{this.secrets=o}});await K(this.env,e.runId,{status:a.status==="completed"?"succeeded":a.status==="stopped"?"skipped":"failed",error:a.error})}catch(n){let s=n instanceof Error?n.message:"Trigger execution failed";throw await K(this.env,e.runId,{status:"failed",error:s}),n}finally{await this.clearRunStopRequest(e.runId)}}async onUserIdentity(e,r){let n=P(r);if(!n){k(e,I.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:n}),k(e,I.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,r){let n=xe(r);if(!n){k(e,I.SERVER_ERROR,"Invalid auth payload");return}let s=n.value.trim();s===""?delete this.userAuth[n.name]:this.userAuth[n.name]=n.value,k(e,I.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:n.name,set:s!==""}}))}async onClearHistory(e){await H(this),this.userAuth={},this.composioSessions={},this.skillRefCache.clear(),this.setState({...this.state,error:"",engineState:this.state.engineState,memory:this.state.memory,modelsCache:{},lastUpdated:new Date}),e&&k(e,I.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await je(this);let e=await O(this);`${JSON.stringify(e)}`}async onClose(e,r,n,s){console.log(`Session closed: ${this.state.sessionId} ${r} - ${n}`)}async onError(e){console.error("AgentDO encountered an error:",e)}};function ws(t){let e=t.state;if(!e)return null;let r=["startNode","answerNode"];for(let n of r)if(!e.nodes.some(a=>a.type===n))return!1;return e.nodes.find(n=>n.type==="startNode")}import{importSPKI as Ft,jwtVerify as Lt}from"jose";function W(t){let e={};if(!t)return e;let r=t.split(";");for(let n of r){let s=n.indexOf("=");if(s>-1){let a=n.slice(0,s).trim(),o=n.slice(s+1).trim();a&&(e[a]=decodeURIComponent(o))}}return e}function Ht(t){return(typeof t.email=="string"?t.email.trim():"")||null}async function v(t,e,r){let n=W(t.headers.get("cookie")),s=new URL(t.url),a=n.access_token||s.searchParams.get("access_token"),o=await jt(e,a);if(o.ok){let i=o.payload,c=Ht(i);return c?{id:i.sub,email:c,name:i.name,first_name:i.given_name,last_name:i.family_name,tenant:i.tenant,org:typeof i.org=="string"?i.org:null,roles:i["ora-roles"],db_name:i.db_name||null,user_id:i.user_id||null}:null}return null}async function jt(t,e){if(!e||typeof e!="string")return{ok:!1,payload:null,protectedHeader:null};if(!t.KC_RS256_PK)throw new Error("PK is not defined");let r=`-----BEGIN PUBLIC KEY-----
6
6
  ${t.KC_RS256_PK}
7
- -----END PUBLIC KEY-----`,n=await $t(r,"RS256");try{let{payload:s,protectedHeader:a}=await Ft(e,n);return{ok:!0,payload:s,protectedHeader:a}}catch(s){return console.error("JWT verification failed:",s),{ok:!1,payload:null,protectedHeader:null}}}async function ks(t,e,r){let n=new URL(t.url);if(n.pathname==="/favicon.ico")return new Response(null,{status:204});if(n.pathname.startsWith("/.well-known/appspecific"))return new Response(null,{status:204})}import{getAgentByName as X}from"agents";import{getAgentByName as jt}from"agents";async function et(t,e){let r=e.sessionId||e.runAsUserId,n=e.inputs||{},s=e.runId;if(!s){let c=await B(t,{tenant:e.tenant,flowId:e.flowId,userId:e.runAsUserId,sessionId:r,triggerId:e.triggerId,triggerKind:e.triggerKind,invocationMode:e.invocationMode,activationId:e.activationId,deliveryId:void 0,externalDeliveryId:e.externalDeliveryId,correlationKey:e.correlationKey,inputs:n,label:e.label});if(!c)return{status:"error",error:"Failed to register run"};if(!c.created&&c.run.status!=="queued")return{status:"deduped",runId:c.run.id};s=c.run.id}let a={...e,sessionId:r,runId:s,inputs:n},i=await(await jt(t.AGENT,`${e.flowId}::${r}`)).enqueueTrigger(a);return i.duplicate?{status:"deduped",runId:s}:i.queued?{status:"queued",runId:s,activation:a,taskId:i.taskId}:{status:"error",error:"Failed to queue trigger"}}var nt="x-ora-signature",rt="x-ora-timestamp",st="x-ora-nonce",ot="x-ora-tenant",Os=300,tt=new TextEncoder;function Kt(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function qt(t){try{let e=new URL(t);return`${e.origin}${e.pathname.replace(/\/$/,"")}`}catch{return t.replace(/\/$/,"")}}function at(t){return["v1",t.timestamp,t.nonce,t.tenant,qt(t.destination),t.body].join(`
8
- `)}async function it(t,e){let r=await crypto.subtle.importKey("raw",tt.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return Kt(await crypto.subtle.sign("HMAC",r,tt.encode(e)))}function Gt(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t.charCodeAt(n)^e.charCodeAt(n);return r===0}async function vs(t){let e=String(t.timestamp??Math.floor(Date.now()/1e3)),r=await it(t.secret,at({timestamp:e,nonce:t.nonce,tenant:t.tenant,destination:t.destination,body:t.body}));return{"content-type":"application/json",[ot]:t.tenant,[rt]:e,[st]:t.nonce,[nt]:`v1=${r}`}}async function ct(t){var l,u,m,p,f;if(!((l=t.secret)!=null&&l.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(u=t.headers.get(ot))==null?void 0:u.trim(),r=(m=t.headers.get(rt))==null?void 0:m.trim(),n=(p=t.headers.get(st))==null?void 0:p.trim(),s=(f=t.headers.get(nt))==null?void 0:f.trim();if(!e||!r||!n||!s)return{ok:!1,error:"missing signature headers"};if(!s.startsWith("v1="))return{ok:!1,error:"unsupported signature version"};let a=Number(r);if(!Number.isFinite(a))return{ok:!1,error:"invalid timestamp"};let o=Math.floor((t.now??Date.now())/1e3),i=t.toleranceSeconds??300;if(Math.abs(o-a)>i)return{ok:!1,error:"stale timestamp"};let c=await it(t.secret.trim(),at({timestamp:r,nonce:n,tenant:e,destination:t.url,body:t.body}));return Gt(s.slice(3),c)?{ok:!0,tenant:e,nonce:n,timestamp:a}:{ok:!1,error:"signature mismatch"}}var A=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}});async function lt(t,e,r){var l;if(new URL(t.url).pathname!=="/api/triggers/dispatch")return;if(t.method!=="POST")return A({error:"Method not allowed"},405);let s=await t.text(),a=await ct({secret:e.HX_API_KEY,body:s,url:t.url,headers:t.headers});if(!a.ok)return console.warn(`[triggers] rejected dispatch: ${a.error}`),A({error:"Invalid signature"},401);let o;try{o=JSON.parse(s)}catch{return A({error:"Invalid payload"},400)}if(!(o!=null&&o.runId)||!(o!=null&&o.flowId)||!(o!=null&&o.runAsUserId)||!(o!=null&&o.tenant)||!(o!=null&&o.activationId)||!(o!=null&&o.triggerId)||!(o!=null&&o.triggerKind)||!(o!=null&&o.invocationMode))return A({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(o.tenant!==a.tenant)return A({error:"Tenant mismatch"},403);let i;try{i=await b(o.flowId,e)}catch{return A({error:"Flow not found"},404)}if(!((l=i==null?void 0:i.metadata)!=null&&l.tenant)||i.metadata.tenant!==o.tenant)return console.warn(`[triggers] flow ${o.flowId} does not belong to tenant ${o.tenant}`),A({error:"Tenant mismatch"},403);let c=await et(e,{...o,sessionId:o.sessionId||o.runAsUserId,nonce:a.nonce});return c.status==="error"?A({error:c.error},502):c.status==="deduped"?A({deduped:!0,runId:c.runId},200):A({accepted:!0,runId:c.runId,taskId:c.taskId},202)}var Wt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function te(t,e,r,n,s,a=!1){let o=(p,f)=>({response:new Response(p,{status:f})});if(!/^[A-Za-z0-9_-]+$/.test(n))return o("Invalid flowId",400);if((!a||s)&&(!s||!Wt.test(s)))return o("Invalid sessionId",400);let i;try{i=await b(n,e)}catch{return o("Flow not found",404)}let c=i==null?void 0:i.metadata;if(!c||!["active","activo"].includes(c.status))return o("Flow not found",404);if(!e.TENANT||c.tenant!==e.TENANT)return o("Forbidden",403);let l=await v(t,e,r),u=l&&typeof l=="object"?l:void 0;if(u&&u.tenant!==e.TENANT)return o("Forbidden",403);if(c.visibility==="public")return{user:u};if(!u){if(!a)return o("Unauthorized",401);let p=new URL(t.url),f=new URL("/login",p.origin);return f.searchParams.set("nextURL",`${p.pathname}${p.search}`),{response:Response.redirect(f.toString(),302)}}if((c.org||"default")!==(u.org||"default"))return o("Forbidden",403);let m=W(t.headers.get("cookie")).access_token||new URL(t.url).searchParams.get("access_token");if(!m)return o("Unauthorized",401);try{let p=await fetch(`${e.HX_CORE_URL}/flows/${encodeURIComponent(n)}`,{headers:{Authorization:m},cache:"no-store"});if(!p.ok||(await p.json()).id!==n)return o("Forbidden",403)}catch{return o("Forbidden",403)}return{user:u}}var Xt=/^[A-Za-z0-9_-]+$/,zt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Vt=new Set(["state","messages","memory"]);async function Jt(t,e){let r=new URL(t.url);if(!r.pathname.startsWith("/api/internal/sessions/"))return;let n=r.pathname.split("/");if(n[6]!=="runs"||n[8]!=="stop"||n.length!==9)return;if(t.method!=="POST")return new Response("Method not allowed",{status:405});if(!e.HX_API_KEY||t.headers.get("Authorization")!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=decodeURIComponent(n[4]||""),a=decodeURIComponent(n[5]||""),o=decodeURIComponent(n[7]||"");if(!s||!a||!o)return new Response("Not found",{status:404});try{let i=await X(e.AGENT,`${s}::${a}`);return Response.json(await i.requestRunStop(o))}catch(i){return console.error("[agents] failed to request run stop",i),Response.json({error:"Failed to stop run"},{status:502})}}async function Yt(t,e){let r=new URL(t.url);if(!r.pathname.startsWith("/api/internal/sessions/"))return;if(t.method!=="GET")return new Response("Method not allowed",{status:405});let n=t.headers.get("Authorization")||"";if(!e.HX_API_KEY||n!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=r.pathname.split("/"),a=decodeURIComponent(s[4]||""),o=decodeURIComponent(s[5]||""),i=s[6];if(!a||!o||!i||!Vt.has(i))return new Response("Not found",{status:404});try{let l=await(await X(e.AGENT,`${a}::${o}`)).inspectPersistedSession(i);return Response.json(l)}catch(c){return console.error("[agents] failed to inspect persisted session",c),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function Ws(t,e,r){var i,c;let n=new URL(t.url),s=await lt(t,e,r);if(s instanceof Response)return s;let a=await Jt(t,e);if(a instanceof Response)return a;let o=await Yt(t,e);if(o instanceof Response)return o;if(n.pathname.startsWith("/a/")){let l=n.pathname.split("/"),u=l[2],m=l[3];try{if(!u)return Response.redirect(new URL("/",n.origin).toString(),302);let p=await te(t,e,r,u,m,!0);if(p.response)return p.response;if(!m){let f=crypto.randomUUID(),g=new URL(`/a/${u}/${f}`,n.origin);return Response.redirect(g.toString(),302)}}catch(p){return console.error("Error accessing flow KV:",p),new Response("Flow error",{status:500})}}if(n.pathname.startsWith("/api/agent/flow/")){let l=n.pathname.split("/"),u=l[4],m=l[5];return ut(t,e,r,u,m)}if(n.pathname.startsWith("/api/ora/connect")){let l=n.pathname.split("/"),u=l[4],m=l[5];if(!u||!m)return new Response("Missing flowId or sessionId",{status:400});let p=t.headers.get("Authorization")||n.searchParams.get("authorization");if(!p)return new Response("Missing Authorization header",{status:401});try{let f=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${u}`,y=await(await fetch(f,{method:"GET",headers:{Authorization:p}})).json();if(((i=y.payload)==null?void 0:i.flowId)!==u)return console.error("FlowId mismatch:",(c=y.payload)==null?void 0:c.flowId,"!==",u),new Response("Validation error",{status:403});let w=`${u}::${m}`,R=await v(t,e,r);if(!R){let $=new URL(t.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 S=new Headers(t.headers);S.delete("X-User-Payload"),R&&S.set("X-User-Payload",JSON.stringify(R));let U=new Request(t,{headers:S});return(await X(e.AGENT,w)).fetch(U)}catch(f){return console.error("Error in /api/ora/connect:",f),new Response("Internal error",{status:500})}}}async function ut(t,e,r,n,s){let a=`${n}::${s}`;try{let o=await te(t,e,r,n,s);if(o.response)return o.response;let i=o.user,c=new Headers(t.headers);c.delete("X-User-Payload"),i&&c.set("X-User-Payload",JSON.stringify(i));let l=new Request(t,{headers:c});return(await X(e.AGENT,a)).fetch(l)}catch(o){return console.error("Error accessing agent:",o),new Response("Agent error",{status:500})}}var Xs=async(t,e,r,n)=>{if(!(n!=null&&n.flowId)||!Xt.test(n.flowId)||!(n!=null&&n.sessionId)||!zt.test(n.sessionId))return new Response("Not found",{status:404});let s=new URL(`/api/agent/flow/${n.flowId}/${n.sessionId}`,t.url),a=new Headers;for(let[c,l]of t.headers.entries())c.toLowerCase().startsWith("x-")||a.append(c,l);let o={method:t.method,headers:a};t.body&&t.method!=="GET"&&t.method!=="HEAD"&&(o.body=t.body,o.duplex="half");let i=new Request(s.toString(),o);return ut(i,e,r,n.flowId,n.sessionId)};async function Js(t,e,r){let n=new URL(t.url),s=t.method;if(!n.pathname.startsWith("/api/instances"))return;let a=await v(t,e,r);if(!a)return new Response("Unauthorized",{status:401});let o=e.HX_CORE_URL,i=e.HX_API_KEY;if(!o||!i)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let l=n.pathname.slice("/api/instances".length);l.startsWith("/")&&(l=l.slice(1)),l.endsWith("/")&&(l=l.slice(0,-1));let u="/ora/instances";l&&(u+=`/${l}`);let m=o.endsWith("/")?o.slice(0,-1):o,p=new URL(`${m}${u}`);n.searchParams.forEach((y,w)=>{p.searchParams.set(w,y)}),s==="GET"&&!l&&p.searchParams.set("filter_user_id",a.email);let f=new Headers;f.set("Authorization",i),f.set("Content-Type","application/json"),f.set("X-User-Payload",JSON.stringify(a));let g={method:s,headers:f};if(["POST","PATCH","PUT"].includes(s))try{g.body=await t.text()}catch(y){console.error("Error reading request body:",y)}try{let y=await fetch(p.toString(),g),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 Zs(t,e,r){let n=new URL(t.url);if(t.method==="POST"&&n.pathname==="/auth/login")try{let s=await t.formData(),a=s.get("username"),o=s.get("password"),i=s.get("nextURL")||"/";if(!a||!o)return new Response("Missing username or password",{status:400});let c=new URLSearchParams;c.append("username",a),c.append("password",o),c.append("grant_type","password"),c.append("client_id",e.KC_CLIENT_ID),c.append("client_secret",e.KC_CLIENT_SECRET);let l=await fetch(`${e.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:c});if(!l.ok)return new Response("Unauthorized",{status:401});let u=await l.json(),m=new Response(null,{status:302,headers:{Location:i}}),f=n.protocol==="https:"?"; Secure":"",g=(y,w,R)=>{m.headers.append("Set-Cookie",`${y}=${w}; Path=/; HttpOnly${f}; SameSite=Lax; Max-Age=${R}`)};return u.access_token&&g("access_token",u.access_token,u.expires_in),u.refresh_token&&g("refresh_token",u.refresh_token,u.refresh_expires_in||3600*24*30),u.id_token&&g("id_token",u.id_token,u.expires_in),m}catch(s){return console.error("Auth error:",s),new Response("Internal Server Error",{status:500})}if(n.pathname==="/auth/logout"){let s=new Response(null,{status:302,headers:{Location:"/login"}}),a=o=>{s.headers.append("Set-Cookie",`${o}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return a("access_token"),a("refresh_token"),a("id_token"),s}if(n.pathname.startsWith("/s/")){let s=await v(t,e,r);if(!s){let a=new URL("/login",n.origin);return a.searchParams.set("nextURL",`${n.pathname}${n.search}`),Response.redirect(a.toString(),302)}return{user:s}}}import{WorkerEntrypoint as Bt}from"cloudflare:workers";import{getAgentByName as Zt}from"agents";var Qt=/^[A-Za-z0-9_-]+$/,en=/^art-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,dt=class extends Bt{async ask(e,r){var n,s,a,o;try{if(!e||typeof e!="string"||!Qt.test(e))throw console.error("[ArtifactWorkerGateway] invalid flowId:",e),new Error("Artifact worker request failed");if(!r||typeof r.message!="string")throw console.error("[ArtifactWorkerGateway] invalid input: message is required"),new Error("Artifact worker request failed");let i;if(r.sessionId!==void 0){if(typeof r.sessionId!="string"||!en.test(r.sessionId))throw console.error("[ArtifactWorkerGateway] invalid sessionId:",r.sessionId),new Error("Artifact worker request failed");i=r.sessionId}else i=`art-${crypto.randomUUID()}`;let c=(s=(n=this.ctx)==null?void 0:n.props)==null?void 0:s.slug,l=(o=(a=this.ctx)==null?void 0:a.props)==null?void 0:o.artifactUuid;if(!c||!l)throw console.error("[ArtifactWorkerGateway] missing slug or artifactUuid in gateway context props"),new Error("Artifact worker request failed");let u=this.env.ARTIFACT;if(!u)throw console.error("[ArtifactWorkerGateway] ARTIFACT binding not configured"),new Error("Artifact worker request failed");let m=u.idFromName(c),f=await u.get(m).allowsWorker({flowId:e,mode:"server",artifactUuid:l});if(!(f!=null&&f.ok))throw console.error(`[ArtifactWorkerGateway] grant check failed for flow ${e} on artifact ${c}`),new Error("Artifact worker request failed");let g=await Zt(this.env.AGENT,`${e}::${i}`),y={message:r.message};r.inputs&&typeof r.inputs=="object"&&(y.inputs=r.inputs);let w=new Request("http://localhost/message",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(y)}),R=await g.fetch(w);if(!R.ok)throw console.error(`[ArtifactWorkerGateway] agent returned status ${R.status}`),new Error("Artifact worker request failed");let S=await R.json();return{text:typeof(S==null?void 0:S.answer)=="string"?S.answer:"",sessionId:i}}catch(i){throw(i==null?void 0:i.message)==="Artifact worker request failed"?i:(console.error("[ArtifactWorkerGateway] unexpected error in ask:",i),new Error("Artifact worker request failed"))}}};export{mt as ANONYMOUS_RUN_USER_PREFIX,Qe as AgentDO,dt as ArtifactWorkerGateway,Xn as CRAWL_DEFAULTS,zn as CRAWL_LIMITS,gn as DEFAULT_MEMORY_LENGTH,yn as DEFAULT_MEMORY_MODEL,un as FLOW_INPUT_NAME_RE,wr as FlowExecutionStoppedError,Zn as GENERATION_PARAM_KEYS,er as GENERATION_PRESETS,fn as MAX_USER_IDENTITY_LENGTH,pn as MEMORY_LENGTH_MD_LINES,mn as MEMORY_LENGTH_TOKENS,Rr as MODEL_REGISTRY_SNAPSHOT,F as NodeType,Rn as OUT_VAR_NAME_RE,Qn as PRESET_PARAM_KEYS,dr as REASONING_EFFORT_LEVELS,Gn as TENANT_ONLY_NODES,hr as TOOL_REGISTRY_SNAPSHOT,st as TRIGGER_NONCE_HEADER,nt as TRIGGER_SIGNATURE_HEADER,Os as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,ot as TRIGGER_TENANT_HEADER,rt as TRIGGER_TIMESTAMP_HEADER,Cn as VariableResolutionError,rr as applyPresetToOverrides,Xs as artifactAgentProxy,Vn as buildCrawlRequestBody,De as buildReasoningProviderOptions,kn as buildScope,vs as buildSignedTriggerHeaders,Se as buildTriggerMessageText,sn as buildUrl,Lt as canonicalUserEmail,Te as capMemoryContent,N as claimRun,H as clearAllMessages,K as completeRun,tn as convertTempMessure,Jn as crawlRequestKey,B as createRun,tr as deriveParamSupport,et as dispatchTrigger,cn as embedText,He as ensureAgentTables,pt as ensureMessagesTable,wn as estimateTokens,Mn as extractOutVarValues,Ln as extractTemplateReferences,Oe as extractUserKeypoints,An as findScopedSourceNode,ut as forwardToAgentFlow,O as getAllMessages,xn as getAncestorNodeIds,Sn as getDefaultOutVars,In as getEffectiveOutVars,Re as getFlowInputDefs,Sr as getModelEntry,Un as getRefTail,Tn as getUpstreamOutVars,Ws as handleAgentsRoutes,Zs as handleAuthRoutes,ks as handleCommonRoutes,Js as handleIntancesRoutes,Yt as handlePersistedSessionInspection,Jt as handleSessionRunControl,lt as handleTriggerRoutes,an as hashText,M as initializeEngineState,_n as isBinaryOutVar,bn as isJsonContentType,Wn as isNodeTypeAllowedForTenant,ke as isStartMemoryEnabled,qn as jsonSchemaToZod,we as logc,be as looksLikeTranscript,_e as memoryGenerationMaxTokens,L as memoryMdLineLimit,xe as memoryTokenLimit,ve as mergeKeypointMemory,I as messageTypes,qt as normalizeDestination,or as normalizeEffectiveParams,dn as normalizeFlowInputs,gr as normalizeModelEntry,fr as normalizeReasoning,ir as openAiReasoningParamSupport,ar as openAiStandardParamSupport,W as parseCookies,hn as parseMemoryLength,On as parsePayloadText,Fn as parseTemplateExpression,Ie as parseUserAuth,Ee as parseUserMessage,sr as pickNodeOverrides,vn as readFetchPayload,pr as reasoningEffortLevels,mr as reasoningExposable,Ke as recordRun,yr as registerProvider,Kn as resolveAnswerMappings,$e as resolveModelById,$n as resolveOutVarRef,Nn as resolveOutVarValue,nr as resolvePreset,Me as resolveReasoningEffort,Dn as resolveReference,je as resolveRunUserId,jn as resolveTemplate,Hn as rewriteTemplateNodeRefs,D as runAgentTurn,Bn as runCrawl,rn as safeParseJSON,J as sanitizeMemoryDocument,P as sanitizeUserIdentity,Ve as sendEvent,k as serverSend,Le as setMessage,Yn as shapeCrawlOutput,it as signTriggerMaterial,Fe as startEngine,Ue as startMemoryLength,Ae as startMemoryModel,ur as stripUnsupportedFromNodeData,nn as tempTool,Gt as timingSafeEqualHex,Ne as toStreamTextSettings,at as triggerSignatureMaterial,on as twitter,Rs as validateFlowStart,En as validateOutVars,ln as vectorize,Ht as verifyToken,ct as verifyTriggerRequest,v as verifyUser,Pn as walkPath,lr as workersAiParamSupport,cr as xaiParamSupport};
7
+ -----END PUBLIC KEY-----`,n=await Ft(r,"RS256");try{let{payload:s,protectedHeader:a}=await Lt(e,n);return{ok:!0,payload:s,protectedHeader:a}}catch(s){return console.error("JWT verification failed:",s),{ok:!1,payload:null,protectedHeader:null}}}async function Ts(t,e,r){let n=new URL(t.url);if(n.pathname==="/favicon.ico")return new Response(null,{status:204});if(n.pathname.startsWith("/.well-known/appspecific"))return new Response(null,{status:204})}import{getAgentByName as X}from"agents";import{getAgentByName as Kt}from"agents";async function tt(t,e){let r=e.sessionId||e.runAsUserId,n=e.inputs||{},s=e.runId;if(!s){let c=await B(t,{tenant:e.tenant,flowId:e.flowId,userId:e.runAsUserId,sessionId:r,triggerId:e.triggerId,triggerKind:e.triggerKind,invocationMode:e.invocationMode,activationId:e.activationId,deliveryId:void 0,externalDeliveryId:e.externalDeliveryId,correlationKey:e.correlationKey,inputs:n,label:e.label});if(!c)return{status:"error",error:"Failed to register run"};if(!c.created&&c.run.status!=="queued")return{status:"deduped",runId:c.run.id};s=c.run.id}let a={...e,sessionId:r,runId:s,inputs:n},i=await(await Kt(t.AGENT,`${e.flowId}::${r}`)).enqueueTrigger(a);return i.duplicate?{status:"deduped",runId:s}:i.queued?{status:"queued",runId:s,activation:a,taskId:i.taskId}:{status:"error",error:"Failed to queue trigger"}}var rt="x-ora-signature",st="x-ora-timestamp",ot="x-ora-nonce",at="x-ora-tenant",bs=300,nt=new TextEncoder;function qt(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function Gt(t){try{let e=new URL(t);return`${e.origin}${e.pathname.replace(/\/$/,"")}`}catch{return t.replace(/\/$/,"")}}function it(t){return["v1",t.timestamp,t.nonce,t.tenant,Gt(t.destination),t.body].join(`
8
+ `)}async function ct(t,e){let r=await crypto.subtle.importKey("raw",nt.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return qt(await crypto.subtle.sign("HMAC",r,nt.encode(e)))}function Wt(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t.charCodeAt(n)^e.charCodeAt(n);return r===0}async function Os(t){let e=String(t.timestamp??Math.floor(Date.now()/1e3)),r=await ct(t.secret,it({timestamp:e,nonce:t.nonce,tenant:t.tenant,destination:t.destination,body:t.body}));return{"content-type":"application/json",[at]:t.tenant,[st]:e,[ot]:t.nonce,[rt]:`v1=${r}`}}async function lt(t){var l,u,m,f,p;if(!((l=t.secret)!=null&&l.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(u=t.headers.get(at))==null?void 0:u.trim(),r=(m=t.headers.get(st))==null?void 0:m.trim(),n=(f=t.headers.get(ot))==null?void 0:f.trim(),s=(p=t.headers.get(rt))==null?void 0:p.trim();if(!e||!r||!n||!s)return{ok:!1,error:"missing signature headers"};if(!s.startsWith("v1="))return{ok:!1,error:"unsupported signature version"};let a=Number(r);if(!Number.isFinite(a))return{ok:!1,error:"invalid timestamp"};let o=Math.floor((t.now??Date.now())/1e3),i=t.toleranceSeconds??300;if(Math.abs(o-a)>i)return{ok:!1,error:"stale timestamp"};let c=await ct(t.secret.trim(),it({timestamp:r,nonce:n,tenant:e,destination:t.url,body:t.body}));return Wt(s.slice(3),c)?{ok:!0,tenant:e,nonce:n,timestamp:a}:{ok:!1,error:"signature mismatch"}}var A=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}});async function ut(t,e,r){var l;if(new URL(t.url).pathname!=="/api/triggers/dispatch")return;if(t.method!=="POST")return A({error:"Method not allowed"},405);let s=await t.text(),a=await lt({secret:e.HX_API_KEY,body:s,url:t.url,headers:t.headers});if(!a.ok)return console.warn(`[triggers] rejected dispatch: ${a.error}`),A({error:"Invalid signature"},401);let o;try{o=JSON.parse(s)}catch{return A({error:"Invalid payload"},400)}if(!(o!=null&&o.runId)||!(o!=null&&o.flowId)||!(o!=null&&o.runAsUserId)||!(o!=null&&o.tenant)||!(o!=null&&o.activationId)||!(o!=null&&o.triggerId)||!(o!=null&&o.triggerKind)||!(o!=null&&o.invocationMode))return A({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(o.tenant!==a.tenant)return A({error:"Tenant mismatch"},403);let i;try{i=await b(o.flowId,e)}catch{return A({error:"Flow not found"},404)}if(!((l=i==null?void 0:i.metadata)!=null&&l.tenant)||i.metadata.tenant!==o.tenant)return console.warn(`[triggers] flow ${o.flowId} does not belong to tenant ${o.tenant}`),A({error:"Tenant mismatch"},403);let c=await tt(e,{...o,sessionId:o.sessionId||o.runAsUserId,nonce:a.nonce});return c.status==="error"?A({error:c.error},502):c.status==="deduped"?A({deduped:!0,runId:c.runId},200):A({accepted:!0,runId:c.runId,taskId:c.taskId},202)}var te=/^[A-Za-z0-9_-]{1,64}$/;async function ne(t,e,r,n,s,a=!1){let o=(f,p)=>({response:new Response(f,{status:p})});if(!/^[A-Za-z0-9_-]+$/.test(n))return o("Invalid flowId",400);if((!a||s)&&(!s||!te.test(s)))return o("Invalid sessionId",400);let i;try{i=await b(n,e)}catch{return o("Flow not found",404)}let c=i==null?void 0:i.metadata;if(!c||!["active","activo"].includes(c.status))return o("Flow not found",404);if(!e.TENANT||c.tenant!==e.TENANT)return o("Forbidden",403);let l=await v(t,e,r),u=l&&typeof l=="object"?l:void 0;if(u&&u.tenant!==e.TENANT)return o("Forbidden",403);if(c.visibility==="public")return{user:u};if(!u){if(!a)return o("Unauthorized",401);let f=new URL(t.url),p=new URL("/login",f.origin);return p.searchParams.set("nextURL",`${f.pathname}${f.search}`),{response:Response.redirect(p.toString(),302)}}if((c.org||"default")!==(u.org||"default"))return o("Forbidden",403);let m=W(t.headers.get("cookie")).access_token||new URL(t.url).searchParams.get("access_token");if(!m)return o("Unauthorized",401);try{let f=await fetch(`${e.HX_CORE_URL}/flows/${encodeURIComponent(n)}`,{headers:{Authorization:m},cache:"no-store"});if(!f.ok||(await f.json()).id!==n)return o("Forbidden",403)}catch{return o("Forbidden",403)}return{user:u}}var Xt=/^[A-Za-z0-9_-]+$/,zt=new Set(["state","messages","memory"]);async function Vt(t,e){let r=new URL(t.url);if(!r.pathname.startsWith("/api/internal/sessions/"))return;let n=r.pathname.split("/");if(n[6]!=="runs"||n[8]!=="stop"||n.length!==9)return;if(t.method!=="POST")return new Response("Method not allowed",{status:405});if(!e.HX_API_KEY||t.headers.get("Authorization")!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=decodeURIComponent(n[4]||""),a=decodeURIComponent(n[5]||""),o=decodeURIComponent(n[7]||"");if(!s||!a||!o)return new Response("Not found",{status:404});try{let i=await X(e.AGENT,`${s}::${a}`);return Response.json(await i.requestRunStop(o))}catch(i){return console.error("[agents] failed to request run stop",i),Response.json({error:"Failed to stop run"},{status:502})}}async function Jt(t,e){let r=new URL(t.url);if(!r.pathname.startsWith("/api/internal/sessions/"))return;if(t.method!=="GET")return new Response("Method not allowed",{status:405});let n=t.headers.get("Authorization")||"";if(!e.HX_API_KEY||n!==e.HX_API_KEY)return new Response("Unauthorized",{status:401});let s=r.pathname.split("/"),a=decodeURIComponent(s[4]||""),o=decodeURIComponent(s[5]||""),i=s[6];if(!a||!o||!i||!zt.has(i))return new Response("Not found",{status:404});try{let l=await(await X(e.AGENT,`${a}::${o}`)).inspectPersistedSession(i);return Response.json(l)}catch(c){return console.error("[agents] failed to inspect persisted session",c),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function Gs(t,e,r){var i,c;let n=new URL(t.url),s=await ut(t,e,r);if(s instanceof Response)return s;let a=await Vt(t,e);if(a instanceof Response)return a;let o=await Jt(t,e);if(o instanceof Response)return o;if(n.pathname.startsWith("/a/")){let l=n.pathname.split("/"),u=l[2],m=l[3];try{if(!u)return Response.redirect(new URL("/",n.origin).toString(),302);let f=await ne(t,e,r,u,m,!0);if(f.response)return f.response;if(!m){let p=crypto.randomUUID(),g=new URL(`/a/${u}/${p}`,n.origin);return Response.redirect(g.toString(),302)}}catch(f){return console.error("Error accessing flow KV:",f),new Response("Flow error",{status:500})}}if(n.pathname.startsWith("/api/agent/flow/")){let l=n.pathname.split("/"),u=l[4],m=l[5];return dt(t,e,r,u,m)}if(n.pathname.startsWith("/api/ora/connect")){let l=n.pathname.split("/"),u=l[4],m=l[5];if(!u||!m)return new Response("Missing flowId or sessionId",{status:400});let f=t.headers.get("Authorization")||n.searchParams.get("authorization");if(!f)return new Response("Missing Authorization header",{status:401});try{let p=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${u}`,y=await(await fetch(p,{method:"GET",headers:{Authorization:f}})).json();if(((i=y.payload)==null?void 0:i.flowId)!==u)return console.error("FlowId mismatch:",(c=y.payload)==null?void 0:c.flowId,"!==",u),new Response("Validation error",{status:403});let w=`${u}::${m}`,R=await v(t,e,r);if(!R){let $=new URL(t.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 S=new Headers(t.headers);S.delete("X-User-Payload"),R&&S.set("X-User-Payload",JSON.stringify(R));let U=new Request(t,{headers:S});return(await X(e.AGENT,w)).fetch(U)}catch(p){return console.error("Error in /api/ora/connect:",p),new Response("Internal error",{status:500})}}}async function dt(t,e,r,n,s){let a=`${n}::${s}`;try{let o=await ne(t,e,r,n,s);if(o.response)return o.response;let i=o.user,c=new Headers(t.headers);c.delete("X-User-Payload"),i&&c.set("X-User-Payload",JSON.stringify(i));let l=new Request(t,{headers:c});return(await X(e.AGENT,a)).fetch(l)}catch(o){return console.error("Error accessing agent:",o),new Response("Agent error",{status:500})}}var Ws=async(t,e,r,n)=>{if(!(n!=null&&n.flowId)||!Xt.test(n.flowId)||!(n!=null&&n.sessionId)||!te.test(n.sessionId))return new Response("Not found",{status:404});let s=new URL(`/api/agent/flow/${n.flowId}/${n.sessionId}`,t.url),a=new Headers;for(let[c,l]of t.headers.entries())c.toLowerCase().startsWith("x-")||a.append(c,l);let o={method:t.method,headers:a};t.body&&t.method!=="GET"&&t.method!=="HEAD"&&(o.body=t.body,o.duplex="half");let i=new Request(s.toString(),o);return dt(i,e,r,n.flowId,n.sessionId)};async function Vs(t,e,r){let n=new URL(t.url),s=t.method;if(!n.pathname.startsWith("/api/instances"))return;let a=await v(t,e,r);if(!a)return new Response("Unauthorized",{status:401});let o=e.HX_CORE_URL,i=e.HX_API_KEY;if(!o||!i)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let l=n.pathname.slice("/api/instances".length);l.startsWith("/")&&(l=l.slice(1)),l.endsWith("/")&&(l=l.slice(0,-1));let u="/ora/instances";l&&(u+=`/${l}`);let m=o.endsWith("/")?o.slice(0,-1):o,f=new URL(`${m}${u}`);n.searchParams.forEach((y,w)=>{f.searchParams.set(w,y)}),s==="GET"&&!l&&f.searchParams.set("filter_user_id",a.email);let p=new Headers;p.set("Authorization",i),p.set("Content-Type","application/json"),p.set("X-User-Payload",JSON.stringify(a));let g={method:s,headers:p};if(["POST","PATCH","PUT"].includes(s))try{g.body=await t.text()}catch(y){console.error("Error reading request body:",y)}try{let y=await fetch(f.toString(),g),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 Bs(t,e,r){let n=new URL(t.url);if(t.method==="POST"&&n.pathname==="/auth/login")try{let s=await t.formData(),a=s.get("username"),o=s.get("password"),i=s.get("nextURL")||"/";if(!a||!o)return new Response("Missing username or password",{status:400});let c=new URLSearchParams;c.append("username",a),c.append("password",o),c.append("grant_type","password"),c.append("client_id",e.KC_CLIENT_ID),c.append("client_secret",e.KC_CLIENT_SECRET);let l=await fetch(`${e.KC_BASE_URL}/protocol/openid-connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Cookie:"hxsecure=1"},body:c});if(!l.ok)return new Response("Unauthorized",{status:401});let u=await l.json(),m=new Response(null,{status:302,headers:{Location:i}}),p=n.protocol==="https:"?"; Secure":"",g=(y,w,R)=>{m.headers.append("Set-Cookie",`${y}=${w}; Path=/; HttpOnly${p}; SameSite=Lax; Max-Age=${R}`)};return u.access_token&&g("access_token",u.access_token,u.expires_in),u.refresh_token&&g("refresh_token",u.refresh_token,u.refresh_expires_in||3600*24*30),u.id_token&&g("id_token",u.id_token,u.expires_in),m}catch(s){return console.error("Auth error:",s),new Response("Internal Server Error",{status:500})}if(n.pathname==="/auth/logout"){let s=new Response(null,{status:302,headers:{Location:"/login"}}),a=o=>{s.headers.append("Set-Cookie",`${o}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return a("access_token"),a("refresh_token"),a("id_token"),s}if(n.pathname.startsWith("/s/")){let s=await v(t,e,r);if(!s){let a=new URL("/login",n.origin);return a.searchParams.set("nextURL",`${n.pathname}${n.search}`),Response.redirect(a.toString(),302)}return{user:s}}}import{WorkerEntrypoint as Yt}from"cloudflare:workers";import{getAgentByName as Bt}from"agents";var Zt=/^[A-Za-z0-9_-]+$/,Qt=/^art-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,pt=class extends Yt{async ask(e,r){var n,s,a,o;try{if(!e||typeof e!="string"||!Zt.test(e))throw console.error("[ArtifactWorkerGateway] invalid flowId:",e),new Error("Artifact worker request failed");if(!r||typeof r.message!="string")throw console.error("[ArtifactWorkerGateway] invalid input: message is required"),new Error("Artifact worker request failed");let i;if(r.sessionId!==void 0){if(typeof r.sessionId!="string"||!Qt.test(r.sessionId))throw console.error("[ArtifactWorkerGateway] invalid sessionId:",r.sessionId),new Error("Artifact worker request failed");i=r.sessionId}else i=`art-${crypto.randomUUID()}`;let c=(s=(n=this.ctx)==null?void 0:n.props)==null?void 0:s.slug,l=(o=(a=this.ctx)==null?void 0:a.props)==null?void 0:o.artifactUuid;if(!c||!l)throw console.error("[ArtifactWorkerGateway] missing slug or artifactUuid in gateway context props"),new Error("Artifact worker request failed");let u=this.env.ARTIFACT;if(!u)throw console.error("[ArtifactWorkerGateway] ARTIFACT binding not configured"),new Error("Artifact worker request failed");let m=u.idFromName(c),p=await u.get(m).allowsWorker({flowId:e,mode:"server",artifactUuid:l});if(!(p!=null&&p.ok))throw console.error(`[ArtifactWorkerGateway] grant check failed for flow ${e} on artifact ${c}`),new Error("Artifact worker request failed");let g=await Bt(this.env.AGENT,`${e}::${i}`),y={message:r.message};r.inputs&&typeof r.inputs=="object"&&(y.inputs=r.inputs);let w=new Request("http://localhost/message",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(y)}),R=await g.fetch(w);if(!R.ok)throw console.error(`[ArtifactWorkerGateway] agent returned status ${R.status}`),new Error("Artifact worker request failed");let S=await R.json();return{text:typeof(S==null?void 0:S.answer)=="string"?S.answer:"",sessionId:i}}catch(i){throw(i==null?void 0:i.message)==="Artifact worker request failed"?i:(console.error("[ArtifactWorkerGateway] unexpected error in ask:",i),new Error("Artifact worker request failed"))}}};export{gt as ANONYMOUS_RUN_USER_PREFIX,et as AgentDO,pt as ArtifactWorkerGateway,Wn as CRAWL_DEFAULTS,Xn as CRAWL_LIMITS,mn as DEFAULT_MEMORY_LENGTH,gn as DEFAULT_MEMORY_MODEL,ln as FLOW_INPUT_NAME_RE,hr as FlowExecutionStoppedError,Bn as GENERATION_PARAM_KEYS,Qn as GENERATION_PRESETS,dn as MAX_USER_IDENTITY_LENGTH,pn as MEMORY_LENGTH_MD_LINES,fn as MEMORY_LENGTH_TOKENS,wr as MODEL_REGISTRY_SNAPSHOT,F as NodeType,wn as OUT_VAR_NAME_RE,Zn as PRESET_PARAM_KEYS,ur as REASONING_EFFORT_LEVELS,qn as TENANT_ONLY_NODES,yr as TOOL_REGISTRY_SNAPSHOT,ot as TRIGGER_NONCE_HEADER,rt as TRIGGER_SIGNATURE_HEADER,bs as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,at as TRIGGER_TENANT_HEADER,st as TRIGGER_TIMESTAMP_HEADER,vn as VariableResolutionError,nr as applyPresetToOverrides,Ws as artifactAgentProxy,zn as buildCrawlRequestBody,$e as buildReasoningProviderOptions,Tn as buildScope,Os as buildSignedTriggerHeaders,Ee as buildTriggerMessageText,rn as buildUrl,Ht as canonicalUserEmail,ke as capMemoryContent,N as claimRun,H as clearAllMessages,K as completeRun,en as convertTempMessure,Vn as crawlRequestKey,B as createRun,er as deriveParamSupport,tt as dispatchTrigger,an as embedText,je as ensureAgentTables,mt as ensureMessagesTable,hn as estimateTokens,Nn as extractOutVarValues,Fn as extractTemplateReferences,ve as extractUserKeypoints,kn as findScopedSourceNode,dt as forwardToAgentFlow,O as getAllMessages,In as getAncestorNodeIds,Rn as getDefaultOutVars,En as getEffectiveOutVars,Se as getFlowInputDefs,Rr as getModelEntry,An as getRefTail,xn as getUpstreamOutVars,Gs as handleAgentsRoutes,Bs as handleAuthRoutes,Ts as handleCommonRoutes,Vs as handleIntancesRoutes,Jt as handlePersistedSessionInspection,Vt as handleSessionRunControl,ut as handleTriggerRoutes,on as hashText,M as initializeEngineState,Un as isBinaryOutVar,_n as isJsonContentType,Gn as isNodeTypeAllowedForTenant,Ae as isStartMemoryEnabled,Kn as jsonSchemaToZod,Re as logc,Oe as looksLikeTranscript,be as memoryGenerationMaxTokens,L as memoryMdLineLimit,Te as memoryTokenLimit,Ce as mergeKeypointMemory,I as messageTypes,Gt as normalizeDestination,sr as normalizeEffectiveParams,un as normalizeFlowInputs,mr as normalizeModelEntry,dr as normalizeReasoning,ar as openAiReasoningParamSupport,or as openAiStandardParamSupport,W as parseCookies,yn as parseMemoryLength,bn as parsePayloadText,$n as parseTemplateExpression,xe as parseUserAuth,Ie as parseUserMessage,rr as pickNodeOverrides,On as readFetchPayload,pr as reasoningEffortLevels,fr as reasoningExposable,qe as recordRun,gr as registerProvider,jn as resolveAnswerMappings,Fe as resolveModelById,Dn as resolveOutVarRef,Pn as resolveOutVarValue,tr as resolvePreset,De as resolveReasoningEffort,Mn as resolveReference,Ke as resolveRunUserId,Hn as resolveTemplate,Ln as rewriteTemplateNodeRefs,D as runAgentTurn,Yn as runCrawl,nn as safeParseJSON,J as sanitizeMemoryDocument,P as sanitizeUserIdentity,Je as sendEvent,k as serverSend,He as setMessage,Jn as shapeCrawlOutput,ct as signTriggerMaterial,Le as startEngine,_e as startMemoryLength,Ue as startMemoryModel,lr as stripUnsupportedFromNodeData,tn as tempTool,Wt as timingSafeEqualHex,Me as toStreamTextSettings,it as triggerSignatureMaterial,sn as twitter,ws as validateFlowStart,Sn as validateOutVars,cn as vectorize,jt as verifyToken,lt as verifyTriggerRequest,v as verifyUser,Cn as walkPath,cr as workersAiParamSupport,ir as xaiParamSupport};
@@ -1,4 +1,5 @@
1
1
  import type { UserInterface } from '../../common/types/user-types';
2
+ export declare const SESSION_ID_RE: RegExp;
2
3
  /** Shared admission for the chat page and its HTTP/WebSocket transport. */
3
4
  export declare function authorizeFlowChat(request: Request, env: Env, ctx: ExecutionContext, flowId: string, sessionId?: string, page?: boolean): Promise<{
4
5
  response?: Response;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hugex/ai",
3
- "version": "3.2.0-canary.2",
3
+ "version": "3.2.0-canary.3",
4
4
  "description": "Ora AI Agent Framework",
5
5
  "author": "a@hugex.co",
6
6
  "license": "SEE LICENSE IN LICENSE",