@hugex/ai 3.1.4 → 3.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -28,5 +28,7 @@ export * from './server/runners/startNodeRunner';
28
28
  export * from './server/runners/classifierNodeRunner';
29
29
  export * from './server/runners/llmNodeRunner';
30
30
  export * from './server/sql/agentSQL';
31
+ export * from './server/core/ArtifactWorkerGateway';
32
+ export type * from './server/types/artifact';
31
33
  export * from './common';
32
34
  export * from './common/utils/logc';
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import{a as A,b as Mn,c as Ce,d as Pe,e as ir,f as $e,g as cr,h as Fe,i as ur}from"./chunk-DEW7U7V7.js";import"./chunk-V35SRZAO.js";import{c as Nn}from"./chunk-ZYIULB2P.js";import"./chunk-6AZ7RATD.js";import"./chunk-XXB57DMN.js";import"./chunk-3K4IMMLP.js";import{a as dr,b as mr}from"./chunk-RFWFJGER.js";import{A as Hn,B as Kn,C as jn,D as Xn,E as qn,F as Vn,G as Gn,H as Jn,I as zn,J as Wn,K as Yn,L as Bn,M as Me,N as Qn,O as Zn,P as er,Q as tr,R as nr,S as rr,T as sr,U as or,V as ar,W as Ne,X as De,Y as lr,a as T,b as Ee,c as rn,d as N,e as Ie,f as sn,g as on,h as an,i as cn,j as ln,k as xe,l as j,m as un,n as Te,o as ke,p as Ae,q as Ue,r as _e,s as Oe,t as W,u as be,v as ve,w as Dn,x as $n,y as Fn,z as Ln}from"./chunk-6JUKM6LT.js";import{A as Cn,B as Pn,a as K,b as tn,c as Re,d as nn,e as Se,f as dn,g as mn,h as pn,i as gn,j as fn,k as yn,l as hn,m as wn,n as Rn,o as Sn,p as En,q as In,r as xn,s as Tn,t as kn,u as An,v as Un,w as _n,x as On,y as bn,z as vn}from"./chunk-QEZQZG6Z.js";import{a as Jt}from"./chunk-RYHQGPX5.js";import{a as zt}from"./chunk-R6EKV3WR.js";import{a as Bt}from"./chunk-6HY7QUMP.js";import{a as Wt,b as Yt}from"./chunk-V6JSMX5A.js";import{a as en}from"./chunk-Q7QHJJGR.js";import{a as O,b as P,c as Qt,d as Zt}from"./chunk-YLDLDEUP.js";import{a as we}from"./chunk-U56YWPSI.js";import"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";import{Agent as Ct}from"agents";import{nanoid as Pt}from"nanoid";async function ut(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 b(t){return t.sql`SELECT id, role, type, content, ts FROM messages ORDER BY ts ASC`}async function X(t){t.sql`DELETE FROM messages`}async function He(t){await ut(t)}function Y(t){return{"Content-Type":"application/json",Authorization:t.HX_API_KEY}}function q(t){return!!(t!=null&&t.HX_ORA_URL)&&!!(t!=null&&t.HX_API_KEY)}var dt="anonymous:";function Ke(t,e){return(t==null?void 0:t.trim())||`${dt}${e}`}async function B(t,e){if(!q(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 D(t,e){if(!q(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 V(t,e,r,n=3){if(!q(t))return!0;for(let s=1;s<=n;s++){try{let o=await fetch(`${t.HX_ORA_URL}/internal/runs/${encodeURIComponent(e)}/complete`,{method:"POST",headers:Y(t),body:JSON.stringify(r)});if(o.ok||o.status===409)return!0;if(o.status===404)return console.error(`[oraTriggers] completeRun ${e} rejected with 404`),!1;console.warn(`[oraTriggers] completeRun ${e} attempt ${s} failed with ${o.status}`)}catch(o){console.warn(`[oraTriggers] completeRun ${e} attempt ${s} threw`,o)}s<n&&await new Promise(o=>setTimeout(o,250*s))}return console.error(`[oraTriggers] completeRun ${e} exhausted ${n} attempts; hx-ora will time the run out`),!1}async function je(t,e){if(!q(t))return Promise.resolve();try{return await B(t,e)}catch(r){return console.error("[oraTriggers] recordRun failed",r),null}}var Q=Object.freeze({}),mt="__SYSTEM_";function Z(t){return t.startsWith(mt)}function pt(t){let e={};for(let[r,n]of Object.entries(t))Z(r)||(e[r]=n);return Object.freeze(e)}function G(t){return(typeof t=="string"?t.trim():"")||"default"}async function Xe(t,e,r){if(!e)return Q;let n=G(r);if(t.HX_ORA_URL&&t.HX_API_KEY)try{let o=new URL(`${t.HX_ORA_URL.replace(/\/$/,"")}/internal/secrets`);o.searchParams.set("org",n);let a=await fetch(o,{headers:{Authorization:t.HX_API_KEY}});if(a.ok){let i=await a.json();if(i.secrets)return pt(i.secrets)}else console.warn(`[secrets] API failed with status ${a.status}, falling back to KV`)}catch(o){console.error("[secrets] API request failed, falling back to KV",o)}let s=t.ORA_SECRETS;if(!s)return Q;try{let o={};return await gt(s,`${e}:${n}:`,o),n==="default"&&await ft(s,e,o),Object.freeze(o)}catch(o){return console.error("[secrets] failed to load tenant secrets from KV",{tenant:e,org:n,err:o}),Q}}async function gt(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(a=>{let i=a.name.slice(e.length);return i.length>0&&!i.includes(":")&&!Z(i)}),o=await Promise.all(s.map(async a=>{let i=await t.get(a.name);return i!==null?[a.name.slice(e.length),i]:null}));for(let a of o){if(!a)continue;let[i,c]=a;i&&(r[i]=c)}}async function ft(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 o=s.keys.filter(i=>{let c=i.name.slice(n.length);return c.length>0&&!c.includes(":")&&!Z(c)}),a=await Promise.all(o.map(async i=>{let c=i.name.slice(n.length);if(c in r)return null;let d=await t.get(i.name);return d!==null?[c,d]:null}));for(let i of a){if(!i)continue;let[c,d]=i;c&&(r[c]=d)}}function J(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(o=>o.type==="startNode");return n==null?void 0:n.data}import{nanoid as _t}from"nanoid";import{streamText as yt}from"ai";var ht={short:`Up to ${j("short")} markdown lines (one fact or bullet per line). Keep constraints, working agreements, and the outline of anything already settled.`,medium:`Up to ${j("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 ${j("long")} markdown lines. Same as medium, with one-line context on a decision or plan block when later turns will need it.`},wt=12,Rt=400,qe=700;function St(t,e=wt){let r=t.filter(s=>s.role==="user"||s.role==="assistant").slice(-e),n=[];for(let s of r){let o=typeof s.content=="string"?s.content:JSON.stringify(s.content??""),a=s.role==="assistant"?qe:Rt,i=o.trim().replace(/\s+/g," ").slice(0,a);i&&n.push(`${s.role==="user"?"U":"A"}: ${i}`)}return n.join(`
2
- `)}function Et(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 It(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 xt(t){var s,o;let e=((s=t.flowData)==null?void 0:s.state)??t.flowData,r=(e==null?void 0:e.nodes)??[],n=[];for(let a of r){if(a.type!=="answerNode")continue;let i=(o=t.results)==null?void 0:o[a.id];i!=null&&n.push(typeof i=="string"?i:JSON.stringify(i))}return n.join(`
3
- `)}function Tt(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.`,ht[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,qe)}`:"",t.answers.trim()?`Answer outputs:
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:
4
4
  ${t.answers.trim()}`:""].filter(Boolean).join(`
5
- `);return{system:e,user:r}}function kt(t){return ve(t.previous,be(t.userText),t.maxTokens)}async function At(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 Ut(t){if(t.fullStream&&typeof t.fullStream[Symbol.asyncIterator]=="function")return At({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 Ve(t){var d;let e=J(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),o=W(t.previousContent||""),a=It(t.messages),i=xt(t.engineState),c=m=>{let h=kt({previous:o,userText:t.userText,maxTokens:n});return{status:"written",content:h,truncated:!1,modelId:s,fallback:!0,error:h?void 0:m}};try{let m=await $e(s,t.sessionEnv,{maxOutputTokens:n});if(!m)throw new Error(`Memory model '${s}' not found in registry`);let h=_e(r,(d=m.reasoning)==null?void 0:d.kind),{system:R,user:u}=Tt({previous:o,userText:t.userText,assistantText:a,answers:i,length:r,maxTokens:n,recentTurns:St(t.messages)}),p=Ne(m.reasoning),g=De(m.provider,{effort:p,exposeReasoning:!1,maxTokens:h}),f=yt({model:m.modelHandle,system:R,messages:[{role:"user",content:u}],...Me({...m.effectiveParams??{},maxOutputTokens:h}),...g?{providerOptions:g}:{}}),y=await Ut(f),E=Et(await f.usage),x=W(y.text);if(Oe(x)&&(x=""),!x)return{...c(y.error||"Memory model returned empty text"),usage:E};let I=Te(x,n);return{status:"written",content:I.content,truncated:I.truncated,usage:E,modelId:s}}catch(m){let h=m instanceof Error?m.message:"Memory update failed";return console.error("Memory update failed:",m),c(h)}}async function Ge(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 o=await P(r,t),a={...e,flowData:{...o,tenant:e.flowData.tenant,flowId:r,chatId:e.flowData.chatId}},i=o==null?void 0:o.stateVersion,c=typeof i=="number"&&i!==((s=e.flowData)==null?void 0:s.stateVersion);return{engineState:a,refreshed:c}}catch(o){return console.error(`[flowRefresh] fetch failed for flow ${r}:`,o),{engineState:e,refreshed:!1}}}function Je(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 ze=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 $(t,e){var o,a;let r=t.id||t.name||"",[n,s]=String(r).split("::");if(!n||!s)return null;try{let c=(o=(await O(n,e)).metadata)==null?void 0:o.tenant,d=await P(n,e),m=(a=t.state)==null?void 0:a.user,h={flowData:{...d,tenant:c,flowId:n,chatId:s},executedNodes:[],context:m?{user:m}:{}};return t.setState({...t.state,engineState:h}),h}catch(i){return console.error("Failed to initialize engine state:",i),null}}async function Ot(t,e,r){var n;if(e&&t.HX_CORE_URL&&t.HX_API_KEY)try{let s=await O(e,t),o=(n=s==null?void 0:s.metadata)==null?void 0:n.org;if(typeof o=="string"&&o.trim())return G(o)}catch(s){console.warn(`[secrets] could not read org for flow ${e}`,s)}return G(r)}async function F(t){var H,ne,re,se,oe,ae,ie,ce,le,ue,de,me;let{agent:e,env:r,ctx:n,payload:s,connection:o}=t,a=Date.now(),i=[],c=t.runId?Ce():void 0,d=async()=>await b(e),m=async l=>{await Le(e,l)},h=async l=>{if(e.state.modelsCache&&e.state.modelsCache[l])return e.state.modelsCache[l];try{let{fetchOraModel:w}=await import("./oraApi-YIJGMXX7.js"),k=await w(l,r);return e.setState({...e.state,modelsCache:{...e.state.modelsCache||{},[l]:k}}),k}catch(w){throw console.error(`Error fetching model ${l}:`,w),w}},R={id:_t(),role:"user",type:"text",content:s.text,images:s.images,ts:Date.now()};await m(R);let u={onChangeState:l=>{e.setState({...e.state,engineState:l})},onServerEvent:async l=>{var w;await((w=t.onServerEvent)==null?void 0:w.call(t,l)),i.push(l)},onTelemetry:async l=>{var _,pe,ge,fe,ye,he;let w=t.user??e.state.user,k=typeof(w==null?void 0:w.org)=="string"&&w.org.trim()?w.org.trim():"default";await ze({...l,userId:t.resolveUserId(),tenant:((pe=(_=e.state.engineState)==null?void 0:_.flowData)==null?void 0:pe.tenant)||"",org:k,flowId:((fe=(ge=e.state.engineState)==null?void 0:ge.flowData)==null?void 0:fe.flowId)||"",sessionId:((he=(ye=e.state.engineState)==null?void 0:ye.flowData)==null?void 0:he.chatId)||""},r)},onError:l=>{var w;(w=t.onError)==null||w.call(t,l),e.setState({...e.state,error:l})},shouldStop:t.shouldStop},p=e.state.engineState?{...e.state.engineState}:null;if(p){let{engineState:l,refreshed:w}=await Ge(r,p);p=l,w&&e.setState({...e.state,engineState:p,modelsCache:{}})}else if(p=await $(e,r),!p){let l="Failed to initialize agent";return u.onError(l),{status:"failed",error:l}}let g=t.user??e.state.user??void 0,f=(H=p.flowData)==null?void 0:H.tenant,y=await Ot(r,(ne=p.flowData)==null?void 0:ne.flowId,g==null?void 0:g.org),E=f?await Xe(r,f,y):{};(re=t.onSecretsLoaded)==null||re.call(t,E),g&&!((se=p.context)!=null&&se.user)&&(p.context={...p.context||{},user:g});let x={env:r,ctx:n,conn:o,getMessages:d,setMessages:m,getOraModel:h,secrets:E,userAuth:t.userAuth,user:g,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=p.flowData)!=null&&ae.flowId?[p.flowData.flowId]:[],workerCalls:{count:0}},I=await Fe(x,p,u)(s),S=e.state.engineState??p;if(I.status==="completed")try{let l=await Ve({sessionEnv:x,engineState:S,previousContent:typeof((ie=e.state.memory)==null?void 0:ie.content)=="string"?e.state.memory.content:"",userText:s.text||"",messages:await d()});if(l.status==="skipped")await u.onServerEvent({type:"agent:memory",content:{skipped:!0,reason:l.reason},timestamp:Date.now()});else if(!l.content.trim())await u.onServerEvent({type:"agent:memory",content:{updated:!1,empty:!0,error:l.error,fallback:l.fallback},timestamp:Date.now()});else{let w={promptTokens:((ce=S.tokenUsage)==null?void 0:ce.promptTokens)??0,completionTokens:((le=S.tokenUsage)==null?void 0:le.completionTokens)??0,totalTokens:((ue=S.tokenUsage)==null?void 0:ue.totalTokens)??0};l.usage&&(w.promptTokens+=l.usage.promptTokens,w.completionTokens+=l.usage.completionTokens,w.totalTokens+=l.usage.totalTokens),S={...S,tokenUsage:w},e.setState({...e.state,engineState:S,memory:{content:l.content,updatedTs:Date.now(),...l.error?{lastError:l.error}:{},...l.fallback?{fallback:!0}:{}}}),await u.onTelemetry({type:"memory_update",payload:{model:l.modelId,truncated:l.truncated,usage:l.usage,fallback:l.fallback,error:l.error}}),await u.onServerEvent({type:"agent:memory",content:{updated:!0,truncated:l.truncated,fallback:l.fallback,error:l.error},timestamp:Date.now()})}}catch(l){let w=l instanceof Error?l.message:"Memory update failed";console.error("Memory update failed:",l),await u.onServerEvent({type:"agent:memory",content:{error:w},timestamp:Date.now()})}if(I.status==="completed"&&t.runId&&(c!=null&&c.hasOutputs())){let{flowId:l,chatId:w}=S.flowData??{};if(!l||!w)I={status:"failed",error:"Structured output persistence requires flowId and sessionId"};else try{await Pe(r,{flowId:l,sessionId:w,runId:t.runId,createdAt:new Date(a).toISOString(),data:c.snapshotData(),answerNodeIds:c.answerNodeIds()});let k={...S.results||{}};for(let _ of c.answerNodeIds())k[_]={...k[_]||{},persisted:!0,runId:t.runId};S={...S,results:k},e.setState({...e.state,engineState:S})}catch(k){let _=k instanceof Error?k.message:"Structured output persistence failed";u.onError(_),await u.onServerEvent({type:"error:answer-output",content:{runId:t.runId,error:_},timestamp:Date.now()}),I={status:"failed",error:_}}}let{tenant:v,flowId:M,chatId:L}=S.flowData??{},te=(de=S.flowData)==null?void 0:de.org;return v&&M&&L&&n.waitUntil(Je(r,{id:`${M}::${L}`,tenant:v,org:te,flowId:M,sessionId:L,userId:t.resolveUserId(),title:(me=s.text)==null?void 0:me.slice(0,120),turnTs:a,events:i})),e.setState({...e.state,lastUpdated:new Date}),{status:I.status,error:I.error,engineState:S}}import{nanoid as bt}from"nanoid";function vt(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"?N(r.email):null;return n?{...r,email:n}:null}catch{return null}}async function We(t,e,r,n){var s;try{let o=await e.json(),a=o.message;if(!a||typeof a!="string")return new Response(JSON.stringify({error:"Invalid message"}),{status:400,headers:{"content-type":"application/json"}});let i=typeof o.userId=="string"?N(o.userId):null,c=vt(e),d=c==null?void 0:c.email;c?t.setState({...t.state,user:c,injectedUserId:d}):i&&!((s=t.state.user)!=null&&s.email)&&t.setState({...t.state,injectedUserId:i});let m=()=>d??i??t.state.injectedUserId??void 0;t.skillRefCache||(t.skillRefCache=new Map);let h=o.inputs&&typeof o.inputs=="object"?o.inputs:void 0;if(!t.state.engineState&&!await $(t,r))return new Response(JSON.stringify({error:"Failed to initialize agent"}),{status:500,headers:{"content-type":"application/json"}});let R=`run-${bt(12)}`;await t.registerManualRun(R,a,m()),await D(r,R).catch(f=>{console.warn(`[AgentHTTP] could not mark manual run ${R} as running`,f)});let u;try{u=await F({agent:t,env:r,ctx:n,payload:{text:a,inputs:h},skillRefCache:t.skillRefCache,user:c??void 0,resolveUserId:m,runId:R,shouldStop:()=>t.isRunStopRequested(R)}),n.waitUntil(t.completeManualRun(R,u.status==="completed"?"succeeded":u.status==="stopped"?"skipped":"failed",u.error))}finally{await t.clearRunStopRequest(R)}if(u.status==="failed")return new Response(JSON.stringify({error:u.error||"Agent execution failed"}),{status:500,headers:{"content-type":"application/json"}});if(u.status==="stopped")return new Response(JSON.stringify({error:u.error||"Stopped by user"}),{status:409,headers:{"content-type":"application/json"}});let g=(await b(t)).reverse().find(f=>f.role==="assistant");return new Response(JSON.stringify({answer:(g==null?void 0:g.content)||""}),{headers:{"content-type":"application/json"}})}catch(o){return new Response(JSON.stringify({error:o.message}),{status:500,headers:{"content-type":"application/json"}})}}async function Ye(t){try{return await X(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 Be="trigger:nonce:",Mt=900*1e3,ee="run:stop:",Qe=class extends Ct{initialState={user:void 0,injectedUserId:null,sessionId:null,lastUpdated:null,modelsCache:{},memory:void 0};resolveSessionUserId(){var e;return((e=this.state.user)==null?void 0:e.email)??this.state.injectedUserId??void 0}secrets=Object.freeze({});userAuth={};composioSessions={};skillRefCache=new Map;publicOrigin;async inspectPersistedSession(e){return e==="state"?{state:this.state}:e==="memory"?{memory:this.state.memory??null}:{messages:await b(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){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 b(this);return new Response(JSON.stringify(n),{headers:{"content-type":"application/json"}})}return e.method==="POST"&&r.pathname.endsWith("/message")?We(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 R,u,p,g,f;let[n,s]=e.server.split("::"),a=(R=(await O(n,this.env)).metadata)==null?void 0:R.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 y=r.request.headers.get("X-User-Payload");if(y)try{i=JSON.parse(y)}catch(E){console.warn("Failed to parse X-User-Payload",E)}}let c=await P(n,this.env);this.setState({...this.state,user:i||null,sessionId:s,engineState:{flowData:{...c,tenant:a,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 d=await b(this);A(e,T.SERVER_HISTORY,JSON.stringify({messages:d}));let h=(((u=c==null?void 0:c.state)==null?void 0:u.nodes)??(c==null?void 0:c.nodes)??[]).find(y=>y.type==="startNode");if(h){let y={allow_images:((p=h.data)==null?void 0:p.allow_images)??!1,allow_documents:((g=h.data)==null?void 0:g.allow_documents)??!1,greeting:(f=h.data)==null?void 0:f.greeting};A(e,T.SERVER_CONFIG,JSON.stringify(y))}}async onMessage(e,r){if(typeof r!="string")return;let n=r.indexOf(":");if(n===-1)return;let s=r.substring(0,n),o=r.substring(n+1);if(!s||!o)return;let i={[T.USER_MESSAGE]:c=>this.onUserMessage(e,c),[T.USER_CLEAR_HISTORY]:()=>this.onClearHistory(e),[T.USER_AUTH]:c=>this.onUserAuth(e,c),[T.USER_IDENTITY]:c=>this.onUserIdentity(e,c)}[s];i&&await i(o)}async onUserMessage(e,r){let n=Ee(r),s=`run-${Pt(12)}`;await this.registerManualRun(s,n.text),await D(this.env,s).catch(o=>{console.warn(`[AgentDO] could not mark manual run ${s} as running`,o)});try{let o=await F({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:this.state.user,resolveUserId:()=>this.resolveSessionUserId(),runId:s,shouldStop:()=>this.isRunStopRequested(s),onServerEvent:a=>{A(e,T.SERVER_EVENT,JSON.stringify(a))},onError:a=>{A(e,T.SERVER_ERROR,a)},onSecretsLoaded:a=>{this.secrets=a}});this.ctx.waitUntil(this.completeManualRun(s,o.status==="completed"?"succeeded":o.status==="stopped"?"skipped":"failed",o.error))}finally{await this.clearRunStopRequest(s)}}registerManualRun(e,r,n){var c;let{tenant:s,flowId:o,chatId:a}=((c=this.state.engineState)==null?void 0:c.flowData)??{};if(!s||!o||!a)return Promise.resolve();let i=Ke(n||this.resolveSessionUserId(),a);return je(this.env,{id:e,tenant:s,flowId:o,userId:i,sessionId:a,label:r==null?void 0:r.slice(0,120)})}completeManualRun(e,r,n){return V(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=`${Be}${e}`;if(await this.ctx.storage.get(r))return!1;let n=Date.now();await this.ctx.storage.put(r,n);let o=[...(await this.ctx.storage.list({prefix:Be})).entries()].filter(([,a])=>n-a>Mt).map(([a])=>a);return o.length>0&&await this.ctx.storage.delete(o),!0}async processTrigger(e){if(!(await D(this.env,e.runId)).claimed){console.warn(`[AgentDO] activation ${e.activationId} skipped \u2014 run ${e.runId} already claimed`);return}try{this.state.engineState||await $(this,this.env);let n=Re(J(this.state.engineState)),s=Se(n,e.inputs||{},e.label),o=await F({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:a=>{this.secrets=a}});await V(this.env,e.runId,{status:o.status==="completed"?"succeeded":o.status==="stopped"?"skipped":"failed",error:o.error})}catch(n){let s=n instanceof Error?n.message:"Trigger execution failed";throw await V(this.env,e.runId,{status:"failed",error:s}),n}finally{await this.clearRunStopRequest(e.runId)}}async onUserIdentity(e,r){let n=N(r);if(!n){A(e,T.SERVER_ERROR,"Invalid identity payload");return}this.setState({...this.state,injectedUserId:n}),A(e,T.SERVER_EVENT,JSON.stringify({type:"info:identity",content:{set:!0}}))}async onUserAuth(e,r){let n=Ie(r);if(!n){A(e,T.SERVER_ERROR,"Invalid auth payload");return}let s=n.value.trim();s===""?delete this.userAuth[n.name]:this.userAuth[n.name]=n.value,A(e,T.SERVER_EVENT,JSON.stringify({type:"info:auth",content:{name:n.name,set:s!==""}}))}async onClearHistory(e){await X(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&&A(e,T.SERVER_HISTORY,JSON.stringify({messages:[]}))}async onStart(){`${JSON.stringify(this.state)}`,await He(this);let e=await b(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 ds(t){let e=t.state;if(!e)return null;let r=["startNode","answerNode"];for(let n of r)if(!e.nodes.some(o=>o.type===n))return!1;return e.nodes.find(n=>n.type==="startNode")}import{importSPKI as Nt,jwtVerify as Dt}from"jose";function Ze(t){let e={};if(!t)return e;let r=t.split(";");for(let n of r){let s=n.indexOf("=");if(s>-1){let o=n.slice(0,s).trim(),a=n.slice(s+1).trim();o&&(e[o]=decodeURIComponent(a))}}return e}function $t(t){return(typeof t.email=="string"?t.email.trim():"")||null}async function C(t,e,r){let n=Ze(t.headers.get("cookie")),s=new URL(t.url),o=n.access_token||s.searchParams.get("access_token"),a=await Ft(e,o);if(a.ok){let i=a.payload,c=$t(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 Ft(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 _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-----
6
6
  ${t.KC_RS256_PK}
7
- -----END PUBLIC KEY-----`,n=await Nt(r,"RS256");try{let{payload:s,protectedHeader:o}=await Dt(e,n);return{ok:!0,payload:s,protectedHeader:o}}catch(s){return console.error("JWT verification failed:",s),{ok:!1,payload:null,protectedHeader:null}}}async function hs(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 z}from"agents";import{getAgentByName as Lt}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 o={...e,sessionId:r,runId:s,inputs:n},i=await(await Lt(t.AGENT,`${e.flowId}::${r}`)).enqueueTrigger(o);return i.duplicate?{status:"deduped",runId:s}:i.queued?{status:"queued",runId:s,activation:o,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",Is=300,tt=new TextEncoder;function Ht(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function Kt(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,Kt(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 Ht(await crypto.subtle.sign("HMAC",r,tt.encode(e)))}function jt(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 xs(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 d,m,h,R,u;if(!((d=t.secret)!=null&&d.trim()))return{ok:!1,error:"HX_API_KEY is not configured"};let e=(m=t.headers.get(ot))==null?void 0:m.trim(),r=(h=t.headers.get(rt))==null?void 0:h.trim(),n=(R=t.headers.get(st))==null?void 0:R.trim(),s=(u=t.headers.get(nt))==null?void 0:u.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 o=Number(r);if(!Number.isFinite(o))return{ok:!1,error:"invalid timestamp"};let a=Math.floor((t.now??Date.now())/1e3),i=t.toleranceSeconds??300;if(Math.abs(a-o)>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 jt(s.slice(3),c)?{ok:!0,tenant:e,nonce:n,timestamp:o}:{ok:!1,error:"signature mismatch"}}var U=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}});async function lt(t,e,r){var d;if(new URL(t.url).pathname!=="/api/triggers/dispatch")return;if(t.method!=="POST")return U({error:"Method not allowed"},405);let s=await t.text(),o=await ct({secret:e.HX_API_KEY,body:s,url:t.url,headers:t.headers});if(!o.ok)return console.warn(`[triggers] rejected dispatch: ${o.error}`),U({error:"Invalid signature"},401);let a;try{a=JSON.parse(s)}catch{return U({error:"Invalid payload"},400)}if(!(a!=null&&a.runId)||!(a!=null&&a.flowId)||!(a!=null&&a.runAsUserId)||!(a!=null&&a.tenant)||!(a!=null&&a.activationId)||!(a!=null&&a.triggerId)||!(a!=null&&a.triggerKind)||!(a!=null&&a.invocationMode))return U({error:"activationId, triggerId, triggerKind, invocationMode, runId, flowId, runAsUserId and tenant are required"},400);if(a.tenant!==o.tenant)return U({error:"Tenant mismatch"},403);let i;try{i=await O(a.flowId,e)}catch{return U({error:"Flow not found"},404)}if(!((d=i==null?void 0:i.metadata)!=null&&d.tenant)||i.metadata.tenant!==a.tenant)return console.warn(`[triggers] flow ${a.flowId} does not belong to tenant ${a.tenant}`),U({error:"Tenant mismatch"},403);let c=await et(e,{...a,sessionId:a.sessionId||a.runAsUserId,nonce:o.nonce});return c.status==="error"?U({error:c.error},502):c.status==="deduped"?U({deduped:!0,runId:c.runId},200):U({accepted:!0,runId:c.runId,taskId:c.taskId},202)}var Xt=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,qt=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]||""),o=decodeURIComponent(n[5]||""),a=decodeURIComponent(n[7]||"");if(!s||!o||!a)return new Response("Not found",{status:404});try{let i=await z(e.AGENT,`${s}::${o}`);return Response.json(await i.requestRunStop(a))}catch(i){return console.error("[agents] failed to request run stop",i),Response.json({error:"Failed to stop run"},{status:502})}}async function Gt(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("/"),o=decodeURIComponent(s[4]||""),a=decodeURIComponent(s[5]||""),i=s[6];if(!o||!a||!i||!qt.has(i))return new Response("Not found",{status:404});try{let d=await(await z(e.AGENT,`${o}::${a}`)).inspectPersistedSession(i);return Response.json(d)}catch(c){return console.error("[agents] failed to inspect persisted session",c),Response.json({error:"Failed to inspect persisted session"},{status:502})}}async function Ps(t,e,r){var i,c,d,m,h,R;let n=new URL(t.url),s=await lt(t,e,r);if(s instanceof Response)return s;let o=await Vt(t,e);if(o instanceof Response)return o;let a=await Gt(t,e);if(a instanceof Response)return a;if(n.pathname.startsWith("/a/")){let u=n.pathname.split("/"),p=u[2],g=u[3];try{if(!p)return Response.redirect(new URL("/",n.origin).toString(),302);let f;try{f=await O(p,e)}catch{return new Response("Flow not found",{status:404})}if(!f.metadata||((i=f.metadata)==null?void 0:i.status)!=="active"&&((c=f.metadata)==null?void 0:c.status)!=="activo")return new Response("NO chat",{status:404});if(((d=f.metadata)==null?void 0:d.visibility)!=="public"){let y=await C(t,e,r);if(!y){let I=new URL("/login",n.origin);return I.searchParams.set("nextURL",`${n.pathname}${n.search}`),Response.redirect(I.toString(),302)}let E=((m=f.metadata)==null?void 0:m.org)||"default",x=typeof y=="object"&&(y==null?void 0:y.org)||"default";if(E!==x)return new Response("Forbidden",{status:403})}if(!g){let y=crypto.randomUUID(),E=new URL(`/a/${p}/${y}`,n.origin);return Response.redirect(E.toString(),302)}if(!Xt.test(g))return new Response("Id del chat no v\xE1lido",{status:400})}catch(f){return console.error("Error accessing flow KV:",f),new Response("Flow error",{status:500})}}if(n.pathname.startsWith("/api/agent/flow")){let u=n.pathname.split("/"),p=u[4],g=u[5],f=`${p}::${g}`;try{let y=await C(t,e,r);if(!y){let v=new URL(t.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${v}) \u2014 Composio connections from tool editor will not apply`)}let E=new Headers(t.headers);E.delete("X-User-Payload"),y&&E.set("X-User-Payload",JSON.stringify(y));let x=new Request(t,{headers:E});return(await z(e.AGENT,f)).fetch(x)}catch(y){return console.error("Error accessing agent:",y),new Response("Agent error",{status:500})}}if(n.pathname.startsWith("/api/ora/connect")){let u=n.pathname.split("/"),p=u[4],g=u[5];if(!p||!g)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 y=`${e.HX_CORE_URL}/p/v1/validation/key/agent/${p}`,x=await(await fetch(y,{method:"GET",headers:{Authorization:f}})).json();if(((h=x.payload)==null?void 0:h.flowId)!==p)return console.error("FlowId mismatch:",(R=x.payload)==null?void 0:R.flowId,"!==",p),new Response("Validation error",{status:403});let I=`${p}::${g}`,S=await C(t,e,r);if(!S){let H=new URL(t.url).searchParams.has("access_token");console.warn(`[agents] Unauthenticated agent socket upgrade (access_token query=${H}) \u2014 Composio connections from tool editor will not apply`)}let v=new Headers(t.headers);v.delete("X-User-Payload"),S&&v.set("X-User-Payload",JSON.stringify(S));let M=new Request(t,{headers:v});return(await z(e.AGENT,I)).fetch(M)}catch(y){return console.error("Error in /api/ora/connect:",y),new Response("Internal error",{status:500})}}}async function Ds(t,e,r){let n=new URL(t.url),s=t.method;if(!n.pathname.startsWith("/api/instances"))return;let o=await C(t,e,r);if(!o)return new Response("Unauthorized",{status:401});let a=e.HX_CORE_URL,i=e.HX_API_KEY;if(!a||!i)return console.error("Missing configuration: HX_CORE_URL or HX_API_KEY"),new Response("Internal Server Error",{status:500});let d=n.pathname.slice("/api/instances".length);d.startsWith("/")&&(d=d.slice(1)),d.endsWith("/")&&(d=d.slice(0,-1));let m="/ora/instances";d&&(m+=`/${d}`);let h=a.endsWith("/")?a.slice(0,-1):a,R=new URL(`${h}${m}`);n.searchParams.forEach((g,f)=>{R.searchParams.set(f,g)}),s==="GET"&&!d&&R.searchParams.set("filter_user_id",o.email);let u=new Headers;u.set("Authorization",i),u.set("Content-Type","application/json"),u.set("X-User-Payload",JSON.stringify(o));let p={method:s,headers:u};if(["POST","PATCH","PUT"].includes(s))try{p.body=await t.text()}catch(g){console.error("Error reading request body:",g)}try{let g=await fetch(R.toString(),p),f=await g.text();return new Response(f,{status:g.status,headers:{"Content-Type":"application/json"}})}catch(g){return console.error("Error proxying to flow instance backend:",g),new Response("Internal Server Error",{status:500})}}async function Ls(t,e,r){let n=new URL(t.url);if(t.method==="POST"&&n.pathname==="/auth/login")try{let s=await t.formData(),o=s.get("username"),a=s.get("password"),i=s.get("nextURL")||"/";if(!o||!a)return new Response("Missing username or password",{status:400});let c=new URLSearchParams;c.append("username",o),c.append("password",a),c.append("grant_type","password"),c.append("client_id",e.KC_CLIENT_ID),c.append("client_secret",e.KC_CLIENT_SECRET);let d=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(!d.ok)return new Response("Unauthorized",{status:401});let m=await d.json(),h=new Response(null,{status:302,headers:{Location:i}}),u=n.protocol==="https:"?"; Secure":"",p=(g,f,y)=>{h.headers.append("Set-Cookie",`${g}=${f}; Path=/; HttpOnly${u}; SameSite=Lax; Max-Age=${y}`)};return m.access_token&&p("access_token",m.access_token,m.expires_in),m.refresh_token&&p("refresh_token",m.refresh_token,m.refresh_expires_in||3600*24*30),m.id_token&&p("id_token",m.id_token,m.expires_in),h}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"}}),o=a=>{s.headers.append("Set-Cookie",`${a}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`)};return o("access_token"),o("refresh_token"),o("id_token"),s}if(n.pathname.startsWith("/s/")){let s=await C(t,e,r);if(!s){let o=new URL("/login",n.origin);return o.searchParams.set("nextURL",`${n.pathname}${n.search}`),Response.redirect(o.toString(),302)}return{user:s}}}export{dt as ANONYMOUS_RUN_USER_PREFIX,Qe as AgentDO,Fn as CRAWL_DEFAULTS,Ln as CRAWL_LIMITS,an as DEFAULT_MEMORY_LENGTH,cn as DEFAULT_MEMORY_MODEL,tn as FLOW_INPUT_NAME_RE,ur as FlowExecutionStoppedError,qn as GENERATION_PARAM_KEYS,Gn as GENERATION_PRESETS,rn as MAX_USER_IDENTITY_LENGTH,sn as MEMORY_LENGTH_MD_LINES,on as MEMORY_LENGTH_TOKENS,dr as MODEL_REGISTRY_SNAPSHOT,K as NodeType,dn as OUT_VAR_NAME_RE,Vn as PRESET_PARAM_KEYS,rr as REASONING_EFFORT_LEVELS,Dn as TENANT_ONLY_NODES,lr as TOOL_REGISTRY_SNAPSHOT,st as TRIGGER_NONCE_HEADER,nt as TRIGGER_SIGNATURE_HEADER,Is as TRIGGER_SIGNATURE_TOLERANCE_SECONDS,ot as TRIGGER_TENANT_HEADER,rt as TRIGGER_TIMESTAMP_HEADER,Tn as VariableResolutionError,Wn as applyPresetToOverrides,Hn as buildCrawlRequestBody,De as buildReasoningProviderOptions,hn as buildScope,xs as buildSignedTriggerHeaders,Se as buildTriggerMessageText,Yt as buildUrl,$t as canonicalUserEmail,Te as capMemoryContent,D as claimRun,X as clearAllMessages,V as completeRun,Jt as convertTempMessure,Kn as crawlRequestKey,B as createRun,Jn as deriveParamSupport,et as dispatchTrigger,Zt as embedText,He as ensureAgentTables,ut as ensureMessagesTable,un as estimateTokens,Un as extractOutVarValues,vn as extractTemplateReferences,be as extractUserKeypoints,wn as findScopedSourceNode,b as getAllMessages,fn as getAncestorNodeIds,mn as getDefaultOutVars,gn as getEffectiveOutVars,Re as getFlowInputDefs,mr as getModelEntry,Rn as getRefTail,yn as getUpstreamOutVars,Ps as handleAgentsRoutes,Ls as handleAuthRoutes,hs as handleCommonRoutes,Ds as handleIntancesRoutes,Gt as handlePersistedSessionInspection,Vt as handleSessionRunControl,lt as handleTriggerRoutes,Qt as hashText,$ as initializeEngineState,Sn as isBinaryOutVar,En as isJsonContentType,$n as isNodeTypeAllowedForTenant,ke as isStartMemoryEnabled,Nn as jsonSchemaToZod,we as logc,Oe as looksLikeTranscript,_e as memoryGenerationMaxTokens,j as memoryMdLineLimit,xe as memoryTokenLimit,ve as mergeKeypointMemory,T as messageTypes,Kt as normalizeDestination,Bn as normalizeEffectiveParams,nn as normalizeFlowInputs,ir as normalizeModelEntry,sr as normalizeReasoning,Zn as openAiReasoningParamSupport,Qn as openAiStandardParamSupport,Ze as parseCookies,ln as parseMemoryLength,In as parsePayloadText,bn as parseTemplateExpression,Ie as parseUserAuth,Ee as parseUserMessage,Yn as pickNodeOverrides,xn as readFetchPayload,or as reasoningEffortLevels,ar as reasoningExposable,je as recordRun,cr as registerProvider,Mn as resolveAnswerMappings,$e as resolveModelById,On as resolveOutVarRef,An as resolveOutVarValue,zn as resolvePreset,Ne as resolveReasoningEffort,_n as resolveReference,Ke as resolveRunUserId,Pn as resolveTemplate,Cn as rewriteTemplateNodeRefs,F as runAgentTurn,Xn as runCrawl,Wt as safeParseJSON,W as sanitizeMemoryDocument,N as sanitizeUserIdentity,ze as sendEvent,A as serverSend,Le as setMessage,jn as shapeCrawlOutput,it as signTriggerMaterial,Fe as startEngine,Ue as startMemoryLength,Ae as startMemoryModel,nr as stripUnsupportedFromNodeData,zt as tempTool,jt as timingSafeEqualHex,Me as toStreamTextSettings,at as triggerSignatureMaterial,Bt as twitter,ds as validateFlowStart,pn as validateOutVars,en as vectorize,Ft as verifyToken,ct as verifyTriggerRequest,C as verifyUser,kn as walkPath,tr as workersAiParamSupport,er as xaiParamSupport};
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};
@@ -1,3 +1,7 @@
1
+ import type { ArtifactAgentProxy } from '../types/artifact';
1
2
  export declare function handleSessionRunControl(request: Request, env: Env): Promise<Response | undefined>;
2
3
  export declare function handlePersistedSessionInspection(request: Request, env: Env): Promise<Response | undefined>;
3
4
  export declare function handleAgentsRoutes(request: Request, env: Env, ctx: ExecutionContext): Promise<Response | undefined>;
5
+ export declare function forwardToAgentFlow(request: Request, env: Env, ctx: ExecutionContext, flowId: string, sessionId: string): Promise<Response>;
6
+ export declare const artifactAgentProxy: ArtifactAgentProxy;
7
+ export type { ArtifactAgentProxy, ArtifactAgentProxyTarget, ArtifactHostOptions } from '../types/artifact';
@@ -76,7 +76,11 @@ export type PersistedSessionSectionResult = {
76
76
  };
77
77
  export declare class AgentDO extends Agent<Env, State> {
78
78
  initialState: State;
79
- /** JWT email wins; explicit client identity is fallback only. */
79
+ constructor(ctx: DurableObjectState, env: Env);
80
+ /** Only the server may change SDK-synchronized state. Supported since agents 0.8.7. */
81
+ validateStateChange(_nextState: State, source: Connection | 'server'): void;
82
+ private requireStateValidation;
83
+ /** Declared anonymous identity only; authorized user comes from the connection/request. */
80
84
  private resolveSessionUserId;
81
85
  private secrets;
82
86
  private userAuth;
@@ -0,0 +1,5 @@
1
+ import { WorkerEntrypoint } from 'cloudflare:workers';
2
+ import type { ArtifactWorkerGatewayInput, ArtifactWorkerGatewayProps, ArtifactWorkerGatewayResult } from '../types/artifact';
3
+ export declare class ArtifactWorkerGateway extends WorkerEntrypoint<Env, ArtifactWorkerGatewayProps> {
4
+ ask(flowId: string, input: ArtifactWorkerGatewayInput): Promise<ArtifactWorkerGatewayResult>;
5
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Types shared with @hugex/artifact according to v6 contract (.orchestrator/artifacts-workers/v6-CONTRATO.md).
3
+ * Declared locally to avoid coupling during parallel development with w-v6a.
4
+ */
5
+ export interface ArtifactAgentProxyTarget {
6
+ flowId: string;
7
+ sessionId: string;
8
+ }
9
+ export type ArtifactAgentProxy = (request: Request, env: any, ctx: ExecutionContext, target: ArtifactAgentProxyTarget) => Promise<Response>;
10
+ export interface ArtifactHostOptions {
11
+ agentProxy?: ArtifactAgentProxy;
12
+ }
13
+ export interface ArtifactWorkerGatewayProps {
14
+ tenant: string;
15
+ slug: string;
16
+ artifactUuid: string;
17
+ }
18
+ export interface ArtifactWorkerGatewayInput {
19
+ message: string;
20
+ sessionId?: string;
21
+ inputs?: Record<string, unknown>;
22
+ }
23
+ export interface ArtifactWorkerGatewayResult {
24
+ text: string;
25
+ sessionId: string;
26
+ }
@@ -0,0 +1,6 @@
1
+ import type { UserInterface } from '../../common/types/user-types';
2
+ /** Shared admission for the chat page and its HTTP/WebSocket transport. */
3
+ export declare function authorizeFlowChat(request: Request, env: Env, ctx: ExecutionContext, flowId: string, sessionId?: string, page?: boolean): Promise<{
4
+ response?: Response;
5
+ user?: UserInterface;
6
+ }>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hugex/ai",
3
- "version": "3.1.4",
3
+ "version": "3.1.6",
4
4
  "description": "Ora AI Agent Framework",
5
5
  "author": "a@hugex.co",
6
6
  "license": "SEE LICENSE IN LICENSE",