@zibby/agent-workflow 2.0.3 → 2.0.5

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.
@@ -1,50 +1,50 @@
1
- var qt=Object.defineProperty;var ve=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var ue=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var qe=(n,e)=>{for(var t in e)qt(n,t,{get:e[t],enumerable:!0})};var Ke,Vt,fe,_,F=ue(()=>{Ke=()=>{},Vt={debug:Ke,info:Ke,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},fe={impl:Vt},_={debug:(...n)=>fe.impl.debug?.(...n),info:(...n)=>fe.impl.info?.(...n),warn:(...n)=>fe.impl.warn?.(...n),error:(...n)=>fe.impl.error?.(...n)}});var at=ue(()=>{});var ct={};qe(ct,{clearSkills:()=>sn,getAllSkills:()=>on,getSkill:()=>oe,getSkillSource:()=>nn,hasSkill:()=>tn,listSkillIds:()=>rn,registerSkill:()=>en});function en(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:o=!1}=e,r=n.id;if(G.has(r)&&!o){let s=ne.get(r);if(!(s===t)){let a=s||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${r}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}G.set(r,Object.freeze({...n})),t===void 0?ne.delete(r):ne.set(r,t)}function oe(n){return G.get(n)||null}function tn(n){return G.has(n)}function nn(n){return ne.get(n)||null}function on(){return new Map(G)}function rn(){return Array.from(G.keys())}function sn(){G.clear(),ne.clear()}var Oe,Pe,G,ne,ge=ue(()=>{Oe=Symbol.for("@zibby/agent-workflow.skills"),Pe=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Oe]||(globalThis[Oe]=new Map);globalThis[Pe]||(globalThis[Pe]=new Map);G=globalThis[Oe],ne=globalThis[Pe]});var re={};qe(re,{getAgentStrategy:()=>dt,invokeAgent:()=>ln,listStrategies:()=>cn,registerStrategy:()=>an,resolveInvocationExtras:()=>ut,resolveInvocationModel:()=>lt});function an(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=H.findIndex(t=>t.getName()===n.getName());e>=0?H[e]=n:H.push(n)}function cn(){return H.map(n=>n.getName())}function lt({config:n={},options:e={},strategyName:t,envModel:o,nodeConfigModel:r}={}){let s=n.models||{},i=typeof r=="string"&&r.trim()?r.trim():null,a=e.nodeName&&s[e.nodeName]||null,u=s.default||null,d=n.agent?.[t]?.model||null,y=(typeof o=="string"?o.trim():"")||null;return i||a||u||d||e.model||y||null}function ut({options:n={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],extraMcpServers:n.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:n.plugins||t.plugins||[]}}function dt(n={}){let{state:e={},preferredAgent:t=null}=n,o=t||e.agentType||process.env.AGENT_TYPE;if(!o){let s=H.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}_.debug(`[workflow] agent selection: requested=${o}`);let r=H.find(s=>s.getName()===o);if(!r){let s=H.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${s}`)}if(!r.canHandle(n))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return _.debug(`[workflow] using agent: ${r.getName()}`),r}async function ln(n,e={},t={}){let o=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},r={...e,state:o},s=dt(r),i=o.config||t.config||{},a=o._currentNodeConfig||{},u=typeof a.agent=="string"?a.agent.trim():"",d=!u||u===s.name?a.model:null,y=lt({config:i,options:t,strategyName:s.name,envModel:process.env.MODEL,nodeConfigModel:d}),l={...t,model:y,...ut({options:t,stateView:o,context:e}),config:i},c=n,g=l.skills||[];if(g.length>0&&!t.skipPromptFragments){let A=t.connectedIntegrations;if(!A){let p=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof p=="string"&&p.trim()!==""){A={};for(let E of p.split(",").map($=>$.trim()).filter(Boolean))A[E]=!0}}let T=p=>{let E=p&&p.requiresIntegration;return!E||!A?!0:(Array.isArray(E)?E:[E]).some(v=>A[v]===!0)},f=s.name==="assistant",h=p=>p?.inProcessOnly!==!0||f,I=g.map(p=>{let E=oe(p);if(!T(E)||!h(E))return null;let $=E?.promptFragment;return typeof $=="function"?$():$}).filter(Boolean);I.length>0&&(c+=`
1
+ var en=Object.defineProperty;var xe=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var he=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var nt=(n,e)=>{for(var t in e)en(n,t,{get:e[t],enumerable:!0})};var ot,nn,Pe,ye,I,z=he(()=>{ot=()=>{},nn={debug:ot,info:ot,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},Pe=Symbol.for("@zibby/agent-workflow.logger");globalThis[Pe]||(globalThis[Pe]={impl:nn});ye=globalThis[Pe],I={debug:(...n)=>ye.impl.debug?.(...n),info:(...n)=>ye.impl.info?.(...n),warn:(...n)=>ye.impl.warn?.(...n),error:(...n)=>ye.impl.error?.(...n)}});var ht=he(()=>{});var gt={};nt(gt,{clearSkills:()=>dn,getAllSkills:()=>ln,getSkill:()=>ie,getSkillSource:()=>cn,hasSkill:()=>an,listSkillIds:()=>un,registerSkill:()=>sn});function sn(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:o=!1}=e,r=n.id;if(Y.has(r)&&!o){let i=se.get(r);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${r}" is already registered by ${a}; ${l} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}Y.set(r,Object.freeze({...n})),t===void 0?se.delete(r):se.set(r,t)}function ie(n){return Y.get(n)||null}function an(n){return Y.has(n)}function cn(n){return se.get(n)||null}function ln(){return new Map(Y)}function un(){return Array.from(Y.keys())}function dn(){Y.clear(),se.clear()}var Ce,Be,Y,se,we=he(()=>{Ce=Symbol.for("@zibby/agent-workflow.skills"),Be=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Ce]||(globalThis[Ce]=new Map);globalThis[Be]||(globalThis[Be]=new Map);Y=globalThis[Ce],se=globalThis[Be]});var ae={};nt(ae,{getAgentStrategy:()=>St,invokeAgent:()=>hn,listStrategies:()=>fn,registerStrategy:()=>pn,resolveInvocationExtras:()=>yt,resolveInvocationModel:()=>mt});function pn(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=Z.findIndex(t=>t.getName()===n.getName());e>=0?Z[e]=n:Z.push(n)}function fn(){return Z.map(n=>n.getName())}function mt({config:n={},options:e={},strategyName:t,envModel:o,nodeConfigModel:r}={}){let i=n.models||{},s=typeof r=="string"&&r.trim()?r.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,d=n.agent?.[t]?.model||null,S=(typeof o=="string"?o.trim():"")||null;return s||a||l||d||e.model||S||null}function yt({options:n={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],extraMcpServers:n.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:n.plugins||t.plugins||[]}}function St(n={}){let{state:e={},preferredAgent:t=null}=n,o=t||e.agentType||process.env.AGENT_TYPE;if(!o){let i=Z.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}I.debug(`[workflow] agent selection: requested=${o}`);let r=Z.find(i=>i.getName()===o);if(!r){let i=Z.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${i}`)}if(!r.canHandle(n))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${r.getName()}`),r}async function hn(n,e={},t={}){let o=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},r={...e,state:o},i=St(r),s=o.config||t.config||{},a=o._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",d=!l||l===i.name?a.model:null,S=mt({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:d}),u={...t,model:S,...yt({options:t,stateView:o,context:e}),config:s},c=n,g=u.skills||[];if(g.length>0&&!t.skipPromptFragments){let A=t.connectedIntegrations;if(!A){let f=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof f=="string"&&f.trim()!==""){A={};for(let w of f.split(",").map(m=>m.trim()).filter(Boolean))A[w]=!0}}let $=f=>{let w=f&&f.requiresIntegration;return!w||!A?!0:(Array.isArray(w)?w:[w]).some(y=>A[y]===!0)},h=i.name==="assistant",b=f=>f?.inProcessOnly!==!0||h,v=g.map(f=>{let w=ie(f);if(!$(w)||!b(w))return null;let m=w?.promptFragment;return typeof m=="function"?m():m}).filter(Boolean);v.length>0&&(c+=`
2
2
 
3
- ${I.join(`
3
+ ${v.join(`
4
4
 
5
- `)}`)}let m=o._currentNodeConfig?.stores;if(Array.isArray(m)&&m.length>0&&typeof m[0]=="object"){let A=m.length<=8,T=m.map(f=>{let h=f?.id??f?.storeId??"",I=(f?.name??"").toString().trim()||h,p=f?.type?` \xB7 ${f.type}`:"",E=(f?.description||"").toString().replace(/\s+/g," ").trim(),$=`- ${I} \xB7 ${E||"(no description)"}${p} (id: ${h})`;if(A&&f?.schema&&typeof f.schema=="object"){let v=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);v.length&&($+=`
6
- fields: ${v.join(", ")}`)}return $});c+=`
5
+ `)}`)}let p=o._currentNodeConfig?.stores;if(Array.isArray(p)&&p.length>0&&typeof p[0]=="object"){let A=p.length<=8,$=p.map(h=>{let b=h?.id??h?.storeId??"",v=(h?.name??"").toString().trim()||b,f=h?.type?` \xB7 ${h.type}`:"",w=(h?.description||"").toString().replace(/\s+/g," ").trim(),m=`- ${v} \xB7 ${w||"(no description)"}${f} (id: ${b})`;if(A&&h?.schema&&typeof h.schema=="object"){let y=h.schema.properties&&typeof h.schema.properties=="object"?Object.keys(h.schema.properties):Object.keys(h.schema);y.length&&(m+=`
6
+ fields: ${y.join(", ")}`)}return m});c+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
9
- ${T.join(`
10
- `)}`}let b=o._currentNodeConfig?.extraPromptInstructions?.trim();return b&&(c+=`
9
+ ${$.join(`
10
+ `)}`}let T=o._currentNodeConfig?.extraPromptInstructions?.trim();return T&&(c+=`
11
11
 
12
12
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
13
13
  PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
14
14
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
15
15
 
16
- ${b}
17
- `),_.debug(`[workflow] prompt length: ${c.length} chars`),s.invoke(c,l)}var Ne,H,se=ue(()=>{at();F();ge();Ne=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ne]||(globalThis[Ne]=[]);H=globalThis[Ne]});var Kt=new Set(["__proto__","constructor","prototype"]);function Te(n){if(Kt.has(n))throw new Error(`Invalid state key: "${n}"`)}var de=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){Te(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)Te(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){Te(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import J from"handlebars";var pe=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let o=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(r=>r[0]);for(let r of o)try{return this.validate(JSON.parse(r))}catch(s){if(!(s instanceof SyntaxError))throw s}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,r]of Object.entries(this.schema)){if(r.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&r.type){let s=typeof e[o];s!==r.type&&t.push(`Field '${o}' expected ${r.type}, got ${s}`)}if(r.validate&&o in e){let s=r.validate(e[o]);s&&t.push(`Field '${o}': ${s}`)}}if(t.length>0)throw new Error(`Output validation failed:
16
+ ${T}
17
+ `),I.debug(`[workflow] prompt length: ${c.length} chars`),i.invoke(c,u)}var Ue,Z,ce=he(()=>{ht();z();we();Ue=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ue]||(globalThis[Ue]=[]);Z=globalThis[Ue]});var tn=new Set(["__proto__","constructor","prototype"]);function ke(n){if(tn.has(n))throw new Error(`Invalid state key: "${n}"`)}var ge=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){ke(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)ke(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){ke(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import q from"handlebars";var me=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let o=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(r=>r[0]);for(let r of o)try{return this.validate(JSON.parse(r))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,r]of Object.entries(this.schema)){if(r.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&r.type){let i=typeof e[o];i!==r.type&&t.push(`Field '${o}' expected ${r.type}, got ${i}`)}if(r.validate&&o in e){let i=r.validate(e[o]);i&&t.push(`Field '${o}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
18
18
  ${t.join(`
19
- `)}`);return e}};F();import{writeFileSync as Ce,readFileSync as pt,existsSync as ft,mkdirSync as un}from"node:fs";import{join as Re,dirname as dn}from"node:path";import O from"chalk";var Xt="__WORKFLOW_GRAPH_LOG__",te=O.gray("\u2502"),Qt=O.gray("\u250C"),Ve=O.gray("\u2514"),Ae=O.green("\u25C6"),Xe=O.hex("#c084fc")("\u25C6"),Qe=O.hex("#2dd4bf")("\u25C6"),ke=O.red("\u25C6"),et=`${te} `,tt=2;function nt(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function ot(n,e){return(t,o,r)=>{if(typeof t!="string")return n(t,o,r);let s=process.stdout.columns||120,i="";for(let a=0;a<t.length;a++){let u=t[a];e.lineStart&&(i+=et,e.col=tt,e.lineStart=!1),u===`
20
- `?(i+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,i+=u):e.inEsc?(i+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,i+=u,e.col>=s&&(i+=`
21
- ${et}`,e.col=tt))}return n(i,o,r)}}var xe=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=ot(this._origStdoutWrite,e),process.stderr.write=ot(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
19
+ `)}`);return e}};z();import{writeFileSync as De,readFileSync as wt,existsSync as _t,mkdirSync as gn}from"node:fs";import{join as je,dirname as mn}from"node:path";import P from"chalk";var on="__WORKFLOW_GRAPH_LOG__",re=P.gray("\u2502"),rn=P.gray("\u250C"),rt=P.gray("\u2514"),Ne=P.green("\u25C6"),st=P.hex("#c084fc")("\u25C6"),it=P.hex("#2dd4bf")("\u25C6"),Me=P.red("\u25C6"),at=`${re} `,ct=2;function lt(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function ut(n,e){return(t,o,r)=>{if(typeof t!="string")return n(t,o,r);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(s+=at,e.col=ct,e.lineStart=!1),l===`
20
+ `?(s+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,s+=l):e.inEsc?(s+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,s+=l,e.col>=i&&(s+=`
21
+ ${at}`,e.col=ct))}return n(s,o,r)}}var Re=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=ut(this._origStdoutWrite,e),process.stderr.write=ut(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
22
22
  `),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
23
23
  `),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
24
- `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Xt}${JSON.stringify(e)}
24
+ `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${on}${JSON.stringify(e)}
25
25
  `;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
26
26
  `),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
27
27
  `)):process.stdout.write.bind(process.stdout)(`${e} ${t}
28
- `)}step(e){this._origStdoutWrite?this._writeDot(Ae,e):process.stdout.write.bind(process.stdout)(`${te} ${Ae} ${e}
29
- `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Xe,e):process.stdout.write.bind(process.stdout)(`${te} ${Xe} ${e}
30
- `)}stepMemory(e){let t=O.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(Qe,t):process.stdout.write.bind(process.stdout)(`${te} ${Qe} ${t}
31
- `)}stepFail(e){this._origStdoutWrite?this._writeDot(ke,O.red(e)):process.stdout.write.bind(process.stdout)(`${te} ${ke} ${O.red(e)}
32
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Qt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:r}=t;if(r)for(let i of r)this._rawWrite(`${Ae} ${i}`);let s=o?O.dim(` ${nt(o)}`):"";this._rawWrite(`${Ve} ${O.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:r}=o,s=r?O.dim(` ${nt(r)}`):"";this._rawWrite(`${ke} ${O.red(t)}`),this._rawWrite(`${Ve} ${O.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(O.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},P=new xe;var he=".zibby/output",rt="sessions",K=".session-info.json",st=".zibby-stop";var oo=Object.freeze(["codebase-memory","code-scan","artifact"]),it=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];J.helpers.inc||J.registerHelper("inc",n=>Number(n)+1);J.helpers.json||J.registerHelper("json",n=>JSON.stringify(n,null,2));J.helpers.eq||J.registerHelper("eq",(n,e)=>n===e);var U=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new pe(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return _.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let o=()=>t&&typeof t.getAll=="function"?t.getAll():e,r=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){_.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(_.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){return _.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&_.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let s;typeof this.prompt=="function"?s=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=J.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(o())):s=this.prompt;let i=r("_skillHints");i&&(s=`${i}
28
+ `)}step(e){this._origStdoutWrite?this._writeDot(Ne,e):process.stdout.write.bind(process.stdout)(`${re} ${Ne} ${e}
29
+ `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(st,e):process.stdout.write.bind(process.stdout)(`${re} ${st} ${e}
30
+ `)}stepMemory(e){let t=P.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(it,t):process.stdout.write.bind(process.stdout)(`${re} ${it} ${t}
31
+ `)}stepFail(e){this._origStdoutWrite?this._writeDot(Me,P.red(e)):process.stdout.write.bind(process.stdout)(`${re} ${Me} ${P.red(e)}
32
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${rn} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:r}=t;if(r)for(let s of r)this._rawWrite(`${Ne} ${s}`);let i=o?P.dim(` ${lt(o)}`):"";this._rawWrite(`${rt} ${P.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:r}=o,i=r?P.dim(` ${lt(r)}`):"";this._rawWrite(`${Me} ${P.red(t)}`),this._rawWrite(`${rt} ${P.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(P.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},M=new Re;var Se=".zibby/output",dt="sessions",ee=".session-info.json",pt=".zibby-stop";var ho=Object.freeze(["codebase-memory","code-scan","artifact"]),ft=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];q.helpers.inc||q.registerHelper("inc",n=>Number(n)+1);q.helpers.json||q.registerHelper("json",n=>JSON.stringify(n,null,2));q.helpers.eq||q.registerHelper("eq",(n,e)=>n===e);var W=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new me(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return I.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let o=()=>t&&typeof t.getAll=="function"?t.getAll():e,r=u=>t&&typeof t.get=="function"?t.get(u):e?.[u];if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let u=null;for(let c=0;c<=this.retries;c++){try{let g=await this.customExecute(e);if(typeof g=="object"&&g!==null&&g.success===!1)u={success:!1,error:g.error||"Node execution failed",raw:g.raw||null};else return this.isZodSchema?(I.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(g),raw:null}):{success:!0,output:g,raw:null}}catch(g){I.error(`[workflow] node '${this.name}' failed: ${g.message}`),g.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(g.issues||g.errors,null,2)}`),u={success:!1,error:g.message,raw:null}}c<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return u}let i;typeof this.prompt=="function"?i=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=q.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(o())):i=this.prompt;let s=r("_skillHints");s&&(i=`${s}
33
33
 
34
- ${s}`);let a=o(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Re(d,K);if(ft(l)){let g=JSON.parse(pt(l,"utf-8"));g.currentNode=this.name,Ce(l,JSON.stringify(g,null,2),"utf-8")}let c=Re(d,"..",K);if(ft(c))try{let g=JSON.parse(pt(c,"utf-8"));g.currentNode=this.name,Ce(c,JSON.stringify(g,null,2),"utf-8")}catch{}}}catch(l){_.debug(`[workflow] could not update session info: ${l.message}`)}let y=null;for(let l=0;l<=this.retries;l++)try{_.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=o().config||{},g=c.agents||{},m=this.config.agent??g[this.name]??null,b={state:o()};m&&(b.preferredAgent=m);let A={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},T=e?._coreInvokeAgent;T||(T=(await Promise.resolve().then(()=>(se(),re))).invokeAgent);let f=await T(s,b,A),h,I;if(typeof f=="string"?(h=f,I=null):f.structured?(h=f.raw||JSON.stringify(f.structured,null,2),I=f.structured):(h=f.raw||JSON.stringify(f,null,2),I=f.extracted||null),d)try{let p=Re(d,this.name,"raw_stream_output.txt");un(dn(p),{recursive:!0}),Ce(p,typeof h=="string"?h:JSON.stringify(h),"utf-8")}catch(p){_.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&I){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(I,null,2)}`);let p=I;if(typeof this.onComplete=="function")try{p=await this.onComplete(o(),I)}catch(E){_.warn(`[workflow] onComplete hook failed: ${E.message}`)}return{success:!0,output:p,raw:h}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:h}),raw:h}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(h);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),P.step("Output parsed"),{success:!0,output:p,raw:h}}return{success:!0,output:h,raw:h}}catch(c){y=c,l<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:y.message,raw:null}}};F();F();import{mkdirSync as hn,existsSync as Y,statSync as Et,readdirSync as $t,rmSync as gn}from"node:fs";import{spawn as _t}from"node:child_process";import{join as W}from"node:path";import{pathToFileURL as mn}from"node:url";import{AsyncLocalStorage as yn}from"node:async_hooks";import{AsyncLocalStorage as pn}from"node:async_hooks";var ie=new pn;function V(){let n=ie.getStore();return n||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function ht(n,e){let t=ie.getStore()||V(),o=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return ie.run(o,e)}function gt(n,e,t){let o=ie.getStore()||V(),r=Object.freeze({...o,agent:n??o.agent??null,signal:e??o.signal??null});return ie.run(r,t)}var Me=new Map,Be=new Map,mt=new Map;function yt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Me.set(n,e),Be.set(n,"ready"),mt.set(n,{...t,cachedAt:Date.now()})}function wt(n,e){Be.set(n,"failed"),mt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Me.delete(n)}function St(n){return Be.get(n)==="ready"?Me.get(n):null}var me=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function wn(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}};function ye(n,e,t,o="timeout"){let r=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${o})`);return r.code="SUBGRAPH_TIMEOUT",r.subgraphJobId=e,r.subgraphStatus=o,r}function Sn(n,e=process.env,t=process.uptime()){let o=Number.isFinite(n)?Number(n):null,r=Number(e&&e.MAX_WORKFLOW_DURATION_MS),s=Number.isFinite(t)&&t>0?t*1e3:0,i=Number.isFinite(r)&&r>0?r-s:null;if(o===null&&i===null)return null;let a=o===null?i:i===null?o:Math.min(o,i);return Math.max(1,a)}function _n(n,e){let t=new AbortController,o=!1,r=null,s=()=>{t.abort(n?.reason)};return n&&(n.aborted?s():n.addEventListener("abort",s,{once:!0})),e!=null&&!t.signal.aborted&&(r=setTimeout(()=>{o=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof r.unref=="function"&&r.unref()),{signal:t.signal,timedOut:()=>o,dispose(){r&&(clearTimeout(r),r=null),n&&n.removeEventListener("abort",s)}}}var bt=new yn,It=Promise.resolve();async function bn(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([i,a])=>typeof i=="string"&&i&&typeof a=="string"):[];if(t.length===0)return e();let o=bt.getStore()===!0,r=null;if(!o){let i=It;It=new Promise(a=>{r=a}),await i}let s=new Map;try{for(let[i,a]of t)s.set(i,Object.prototype.hasOwnProperty.call(process.env,i)?process.env[i]:void 0),process.env[i]=a;return _.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await bt.run(!0,e)}finally{for(let[i,a]of s)a===void 0?delete process.env[i]:process.env[i]=a;r&&r()}}function In(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,o=process.env.PROJECT_ID,r=process.env.PROJECT_API_TOKEN;if(!t||!o||!r)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:r}}async function En({apiBase:n,authToken:e,body:t}){let o;try{o=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(s){throw new N("network",`begin fetch failed: ${s.message}`)}let r=null;try{r=await o.json()}catch{}if(!o.ok){if(o.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(o.status===429){let s=r?.quotaInfo||{},i=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw i.code="SUBGRAPH_QUOTA_EXCEEDED",i.status=429,i.quotaInfo=s,i}if(o.status===400&&r?.validationErrors){let s=new Error(`Sub-graph rejected input: ${r?.error||r?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=r.validationErrors,s.missing=r.missing,s}throw new N("begin-status",`begin returned ${o.status}`)}return r?.data||r}async function z({apiBase:n,authToken:e,payload:t}){try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});o.ok||_.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){_.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function $n(n,e){let t=W(e,".ready"),o=W(e,"graph.mjs");if(Y(t)&&Y(o))return;hn(e,{recursive:!0});let r=W(e,".lock"),s=!1;try{let{openSync:i,closeSync:a}=await import("node:fs"),u=i(r,"wx");a(u),s=!0}catch(i){if(i.code!=="EEXIST")throw i}if(!s){let i=Date.now()+3e4;for(;Date.now()<i;){if(Y(t)&&Y(o))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let y=_t("curl",["-fsSL",n],{stdio:["ignore","pipe","inherit"]}),l=_t("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});y.stdout.pipe(l.stdin);let c,g,m=()=>{if(c!==void 0&&g!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(g!==0)return d(new Error(`tar exited ${g}`));u()}};y.on("close",b=>{c=b,m()}),l.on("close",b=>{g=b,m()}),y.on("error",d),l.on("error",d)});let{writeFileSync:i,unlinkSync:a}=await import("node:fs");i(t,"");try{a(r)}catch{}}catch(i){try{let{unlinkSync:a}=await import("node:fs");a(r)}catch{}throw new N("bundle-extract-failed",i.message)}}async function vn(n){let e=W(n,"graph.mjs");if(!Y(e))throw new N("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(mn(e).href)}catch(r){throw new N("import-failed",`${r?.code||r?.name||"unknown"}: ${r.message}`)}let o=t.default||Object.values(t).find(r=>typeof r=="function"&&r.prototype?.buildGraph);if(!o)throw new N("entry-class-missing","no buildGraph() class export found");return o}async function vt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=V(),o;try{o=In()}catch($){throw $}_.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let r=await En({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:s,runtimeTag:i,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:y,bundleReady:l,nodeConfigs:c}=r,g=wn();if(i&&i!==g)throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,discard:!0}}),new N("runtime-mismatch",`${g} vs ${i}`);if(!l||!a)throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,discard:!0}}),new N("no-bundle","workflow bundle not built yet");let m=St(n);if(!m){let $=W(me,`${y}@${d||"0"}`);try{await $n(a,$);try{An()}catch{}}catch(v){throw v.fallback&&await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:"failed",error:{message:v.message,code:v.reason}}}),v}try{m=await vn($),yt(n,m,{workflowUuid:y,version:d,runtimeTag:i,cacheDir:$})}catch(v){throw wt(n,v),await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:"failed",error:{message:v.message,code:v.reason||"IMPORT_FAILED"}}}),v.fallback?v:new N("import-failed",v.message)}}let b=Date.now(),A=r.env&&typeof r.env=="object"&&!Array.isArray(r.env)?r.env:null,T=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...T?{nodeConfigs:c}:{}},h=Sn(e.timeoutMs),I=_n(e.signal,h),p,E;try{p=await bn(A,async()=>{let v=await(typeof m=="function"&&m.prototype?.buildGraph?new m:m).buildGraph();return ht({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>v.run(e.parentAgent,f,{signal:I.signal}))}),E=p&&typeof p=="object"&&"state"in p?p.state:p}catch($){let v=I.timedOut();throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:v?"timeout":"failed",error:v?{message:`aborted at the declared ${Math.round(h/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:$.message,code:$.code||"CHILD_THREW",stack:$.stack},durationMs:Date.now()-b}}),v?ye(n,s,h):$}finally{I.dispose()}if(p&&typeof p=="object"&&p.stoppedExternally){let $=I.timedOut();if(await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:$?"timeout":"canceled",finalState:E,durationMs:Date.now()-b}}),$)throw ye(n,s,h);let v=new Error(`Sub-graph '${n}' canceled by parent abort`);throw v.code="SUBGRAPH_CANCELED",v.subgraphJobId=s,v}return await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:"completed",finalState:E,durationMs:Date.now()-b}}),{finalState:E,executionId:s}}function Tn(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),r;try{r=Et(o)}catch{continue}if(r.isDirectory()){let s;try{s=$t(o)}catch{continue}for(let i of s)t.push(W(o,i))}else e+=r.size}return e}function An({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(me))return{evicted:0,freedBytes:0};let e=$t(me),t=[],o=0;for(let a of e){let u=W(me,a),d;try{d=Et(u)}catch{continue}let y=d.isDirectory()?Tn(u):d.size;o+=y,t.push({name:a,full:u,size:y,mtimeMs:d.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let r=Math.floor(n*.7),s=0,i=0;for(let a of t){if(o-s<=r)break;if(!Y(W(a.full,".lock")))try{gn(a.full,{recursive:!0,force:!0}),s+=a.size,i+=1}catch(u){_.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return i>0&&_.info(`[sub-graph cache] evicted ${i} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:i,freedBytes:s,totalBytes:o-s}}catch(e){return _.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var kn=2e3,xn=600*1e3,On=new Set(["completed","failed","canceled","timeout"]);function Pn(){let n=process.env.PROGRESS_API_URL;if(!n)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return n.replace(/\/executions\/?$/,"")}function Nn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function Cn(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function Rn(){return process.env.EXECUTION_ID||null}function Tt(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,o)=>t==null?t:t[o],n):n}async function At(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=V();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=o)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let r=Number.isFinite(e.timeoutMs)?e.timeoutMs:xn;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{_.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:h}=await vt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:r}),I=Tt(h,e.output);return _.info(`[sub-graph] '${n}' completed in-process`),I}catch(h){if(h instanceof N||h?.fallback)_.info(`[sub-graph] in-process fallback for '${n}': ${h.reason||"unknown"} \u2014 using HTTP`);else throw h}let s=Pn(),i=Nn(),a=Cn(),u=Rn(),d=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(n)}/trigger`,y={input:e.input||{},...u?{parentExecutionId:u}:{},...e.conversationId?{conversationId:e.conversationId}:{}};_.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${u||"<none>"}`);let l=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(y)});if(!l.ok){let h=null,I="";try{h=await l.json(),I=h?.error||h?.message||JSON.stringify(h)}catch{I=await l.text().catch(()=>"")}if(l.status===429){let E=h?.quotaInfo||{},$=new Error(`Sub-graph '${n}' blocked by execution quota (${E.used??"?"}/${E.limit??"?"} on plan ${E.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw $.code="SUBGRAPH_QUOTA_EXCEEDED",$.status=429,$.subgraph=n,$.quotaInfo=E,$}if(l.status===400){let E=new Error(`Sub-graph '${n}' rejected input: ${I}`);throw E.code="SUBGRAPH_INVALID_INPUT",E.status=400,E.subgraph=n,E.validationErrors=h?.validationErrors||null,E.missing=h?.missing||null,E}let p=new Error(`Sub-graph '${n}' trigger rejected (${l.status}): ${I}`);throw p.code="SUBGRAPH_TRIGGER_FAILED",p.status=l.status,p.subgraph=n,p}let c=await l.json(),g=c?.data?.jobId||c?.jobId;if(!g)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(e.async)return _.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${g} (not waiting)`),{jobId:g,status:"accepted",workflow:n};let m=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:kn,b=`${s}/executions/${encodeURIComponent(g)}`,A=Date.now()+r,T="accepted",f=0;for(;Date.now()<A;){await new Promise(E=>setTimeout(E,m)),f+=1;let h=await fetch(b,{headers:{Authorization:`Bearer ${a}`}});if(!h.ok){if(h.status>=500){_.warn(`[sub-graph] status poll for ${g} returned ${h.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${g}: ${h.status}`)}let I=await h.json(),p=I?.data||I?.execution||I;if(T=p?.status||T,On.has(T)){if(T!=="completed"){let v=new Error(`Sub-graph '${n}' (${g}) ended in status '${T}'`);throw v.subgraphJobId=g,v.subgraphStatus=T,v}let E=p?.finalState||p?.state||{},$=Tt(E,e.output);return _.info(`[sub-graph] '${n}' (${g}) completed after ${f} polls`),$}}throw ye(n,g,r,T)}import{existsSync as kt,readFileSync as Mn}from"node:fs";import{join as je,dirname as xt}from"node:path";var we=class{static async loadContext(e,t,o={}){let r={},s=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=xt(je(t,e));for(let u of s){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let y=u.replace(/\.[^.]+$/,"").toLowerCase();r[y]=d}}}let i=o.discovery||{};for(let[a,u]of Object.entries(i))try{let d=je(t,u);kt(d)&&(r[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return r}static async findAndMergeContextFiles(e,t,o){let r=[],s=t;for(;s.startsWith(o);){let i=je(s,e);if(kt(i))try{r.unshift(await this.loadFile(i))}catch(u){console.warn(`[workflow] could not load ${e} from ${i}: ${u.message}`)}let a=xt(s);if(a===s)break;s=a}return r.length===0?null:r.every(i=>typeof i=="string")?r.join(`
34
+ ${i}`);let a=o(),l=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let u=je(d,ee);if(_t(u)){let g=JSON.parse(wt(u,"utf-8"));g.currentNode=this.name,De(u,JSON.stringify(g,null,2),"utf-8")}let c=je(d,"..",ee);if(_t(c))try{let g=JSON.parse(wt(c,"utf-8"));g.currentNode=this.name,De(c,JSON.stringify(g,null,2),"utf-8")}catch{}}}catch(u){I.debug(`[workflow] could not update session info: ${u.message}`)}let S=null;for(let u=0;u<=this.retries;u++)try{I.debug(`[workflow] node '${this.name}' attempt ${u}`);let c=o().config||{},g=c.agents||{},p=this.config.agent??g[this.name]??null,T={state:o()};p&&(T.preferredAgent=p);let A={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},$=e?._coreInvokeAgent;$||($=(await Promise.resolve().then(()=>(ce(),ae))).invokeAgent);let h=await $(i,T,A),b,v;if(typeof h=="string"?(b=h,v=null):h.structured?(b=h.raw||JSON.stringify(h.structured,null,2),v=h.structured):(b=h.raw||JSON.stringify(h,null,2),v=h.extracted||null),d)try{let f=je(d,this.name,"raw_stream_output.txt");gn(mn(f),{recursive:!0}),De(f,typeof b=="string"?b:JSON.stringify(b),"utf-8")}catch(f){I.debug(`[workflow] could not save raw output: ${f.message}`)}if(this.isZodSchema&&v){I.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(v,null,2)}`);let f=v;if(typeof this.onComplete=="function")try{f=await this.onComplete(o(),v)}catch(w){I.warn(`[workflow] onComplete hook failed: ${w.message}`)}return{success:!0,output:f,raw:b}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:b}),raw:b}}catch(f){throw new Error(`onComplete failed: ${f.message}`,{cause:f})}if(this.parser){let f=this.parser.parse(b);return I.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(f,null,2)}`),M.step("Output parsed"),{success:!0,output:f,raw:b}}return{success:!0,output:b,raw:b}}catch(c){S=c,u<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${u+1}/${this.retries})\u2026`)}return{success:!1,error:S.message,raw:null}}};z();z();import{mkdirSync as bn,existsSync as V,statSync as kt,readdirSync as Pt,rmSync as En}from"node:fs";import{spawn as At}from"node:child_process";import{join as H}from"node:path";import{pathToFileURL as In}from"node:url";import{AsyncLocalStorage as Tn}from"node:async_hooks";import{AsyncLocalStorage as yn}from"node:async_hooks";var le=new yn;function te(){let n=le.getStore();return n||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function bt(n,e){let t=le.getStore()||te(),o=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return le.run(o,e)}function Et(n,e,t){let o=le.getStore()||te(),r=Object.freeze({...o,agent:n??o.agent??null,signal:e??o.signal??null});return le.run(r,t)}var Le=new Map,Ge=new Map,It=new Map;function Tt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Le.set(n,e),Ge.set(n,"ready"),It.set(n,{...t,cachedAt:Date.now()})}function $t(n,e){Ge.set(n,"failed"),It.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Le.delete(n)}function vt(n){return Ge.get(n)==="ready"?Le.get(n):null}function ue(n,e,t=process.env){let o=Number(t[n]);return Number.isFinite(o)&&o>0?Math.min(12e4,Math.max(1e3,Math.floor(o))):e}function Fe(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function de(n,e){return Fe(ue(n,e),n)}function D(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}var _e=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function $n(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}};function be(n,e,t,o="timeout",r=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${o})`+(r?`; the status API was unreachable on the last attempt (${r})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=o,r&&(i.subgraphTransportError=r),i}function vn(n,e=process.env,t=process.uptime()){let o=Number.isFinite(n)?Number(n):null,r=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,s=Number.isFinite(r)&&r>0?r-i:null;if(o===null&&s===null)return null;let a=o===null?s:s===null?o:Math.min(o,s);return Math.max(1,a)}function An(n,e){let t=new AbortController,o=!1,r=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(r=setTimeout(()=>{o=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof r.unref=="function"&&r.unref()),{signal:t.signal,timedOut:()=>o,dispose(){r&&(clearTimeout(r),r=null),n&&n.removeEventListener("abort",i)}}}var Ot=new Tn,xt=Promise.resolve();async function On(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(t.length===0)return e();let o=Ot.getStore()===!0,r=null;if(!o){let s=xt;xt=new Promise(a=>{r=a}),await s}let i=new Map;try{for(let[s,a]of t)i.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=a;return I.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await Ot.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;r&&r()}}function xn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,o=process.env.PROJECT_ID,r=process.env.PROJECT_API_TOKEN;if(!t||!o||!r)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:r}}async function kn({apiBase:n,authToken:e,body:t}){let o=de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),r;try{r=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:o.signal})}catch(s){throw new N(D(s)?"begin-timeout":"network",D(s)?`begin TIMED OUT ${o.label}`:`begin fetch failed: ${s.message}`)}let i=null;try{i=await r.json()}catch(s){if(D(s))throw new N("begin-timeout",`begin body read TIMED OUT ${o.label}`)}if(!r.ok){if(r.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(r.status===429){let s=i?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=s,a}if(r.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new N("begin-status",`begin returned ${r.status}`)}return i?.data||i}async function K({apiBase:n,authToken:e,payload:t}){let o=de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let r=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:o.signal});r.ok||I.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){I.warn(`[in-process subgraph] finalize ${D(r)?`TIMED OUT ${o.label}`:`failed: ${r.message}`}`)}}async function Pn(n,e){let t=H(e,".ready"),o=H(e,"graph.mjs");if(V(t)&&V(o))return;bn(e,{recursive:!0});let r=H(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),l=s(r,"wx");a(l),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(V(t)&&V(o))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,d)=>{let S=Math.ceil(1e4/1e3),u=Math.ceil(ue("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=At("curl",["-fsSL","--connect-timeout",String(S),"--max-time",String(u),n],{stdio:["ignore","pipe","inherit"]}),g=At("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(g.stdin);let p,T,A=()=>{if(p!==void 0&&T!==void 0){if(p!==0)return d(new Error(`curl exited ${p}`));if(T!==0)return d(new Error(`tar exited ${T}`));l()}};c.on("close",$=>{p=$,A()}),g.on("close",$=>{T=$,A()}),c.on("error",d),g.on("error",d)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(r)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(r)}catch{}throw new N("bundle-extract-failed",s.message)}}async function Nn(n){let e=H(n,"graph.mjs");if(!V(e))throw new N("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(In(e).href)}catch(r){throw new N("import-failed",`${r?.code||r?.name||"unknown"}: ${r.message}`)}let o=t.default||Object.values(t).find(r=>typeof r=="function"&&r.prototype?.buildGraph);if(!o)throw new N("entry-class-missing","no buildGraph() class export found");return o}async function Nt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=te(),o;try{o=xn()}catch(m){throw m}I.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let r=await kn({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:d,workflowUuid:S,bundleReady:u,nodeConfigs:c}=r,g=$n();if(s&&s!==g)throw await K({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new N("runtime-mismatch",`${g} vs ${s}`);if(!u||!a)throw await K({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new N("no-bundle","workflow bundle not built yet");let p=vt(n);if(!p){let m=H(_e,`${S}@${d||"0"}`);try{await Pn(a,m);try{Rn()}catch{}}catch(y){throw y.fallback&&await K({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:y.message,code:y.reason}}}),y}try{p=await Nn(m),Tt(n,p,{workflowUuid:S,version:d,runtimeTag:s,cacheDir:m})}catch(y){throw $t(n,y),await K({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:y.message,code:y.reason||"IMPORT_FAILED"}}}),y.fallback?y:new N("import-failed",y.message)}}let T=Date.now(),A=r.env&&typeof r.env=="object"&&!Array.isArray(r.env)?r.env:null,$=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...$?{nodeConfigs:c}:{}},b=vn(e.timeoutMs),v=An(e.signal,b),f,w;try{f=await On(A,async()=>{let y=await(typeof p=="function"&&p.prototype?.buildGraph?new p:p).buildGraph();return bt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>y.run(e.parentAgent,h,{signal:v.signal}))}),w=f&&typeof f=="object"&&"state"in f?f.state:f}catch(m){let y=v.timedOut();throw await K({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:y?"timeout":"failed",error:y?{message:`aborted at the declared ${Math.round(b/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:m.message,code:m.code||"CHILD_THREW",stack:m.stack},durationMs:Date.now()-T}}),y?be(n,i,b):m}finally{v.dispose()}if(f&&typeof f=="object"&&f.stoppedExternally){let m=v.timedOut();if(await K({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:m?"timeout":"canceled",finalState:w,durationMs:Date.now()-T}}),m)throw be(n,i,b);let y=new Error(`Sub-graph '${n}' canceled by parent abort`);throw y.code="SUBGRAPH_CANCELED",y.subgraphJobId=i,y}return await K({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"completed",finalState:w,durationMs:Date.now()-T}}),{finalState:w,executionId:i}}function Mn(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),r;try{r=kt(o)}catch{continue}if(r.isDirectory()){let i;try{i=Pt(o)}catch{continue}for(let s of i)t.push(H(o,s))}else e+=r.size}return e}function Rn({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!V(_e))return{evicted:0,freedBytes:0};let e=Pt(_e),t=[],o=0;for(let a of e){let l=H(_e,a),d;try{d=kt(l)}catch{continue}let S=d.isDirectory()?Mn(l):d.size;o+=S,t.push({name:a,full:l,size:S,mtimeMs:d.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let r=Math.floor(n*.7),i=0,s=0;for(let a of t){if(o-i<=r)break;if(!V(H(a.full,".lock")))try{En(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(l){I.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return s>0&&I.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:o-i}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Bn=2e3,Un=600*1e3,Dn=new Set(["completed","failed","canceled","timeout"]);var jn=()=>de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function Ln(n){let e=ue("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return Fe(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function Gn(){let n=process.env.PROGRESS_API_URL;if(!n)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return n.replace(/\/executions\/?$/,"")}function Fn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function Wn(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function Hn(){return process.env.EXECUTION_ID||null}function Mt(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,o)=>t==null?t:t[o],n):n}async function Rt(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=te();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=o)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let r=Number.isFinite(e.timeoutMs)?e.timeoutMs:Un;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:f}=await Nt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:r}),w=Mt(f,e.output);return I.info(`[sub-graph] '${n}' completed in-process`),w}catch(f){if(f instanceof N||f?.fallback)I.info(`[sub-graph] in-process fallback for '${n}': ${f.reason||"unknown"} \u2014 using HTTP`);else throw f}let i=Gn(),s=Fn(),a=Wn(),l=Hn(),d=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(n)}/trigger`,S={input:e.input||{},...l?{parentExecutionId:l}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let u=jn(),c;try{c=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(S),signal:u.signal})}catch(f){if(!D(f))throw f;let w=new Error(`Sub-graph '${n}' trigger TIMED OUT ${u.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw w.code="SUBGRAPH_TRIGGER_TIMEOUT",w.subgraph=n,w.timedOut=!0,w.cause=f,w}if(!c.ok){let f=null,w="";try{f=await c.json(),w=f?.error||f?.message||JSON.stringify(f)}catch{w=await c.text().catch(()=>"")}if(c.status===429){let y=f?.quotaInfo||{},O=new Error(`Sub-graph '${n}' blocked by execution quota (${y.used??"?"}/${y.limit??"?"} on plan ${y.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw O.code="SUBGRAPH_QUOTA_EXCEEDED",O.status=429,O.subgraph=n,O.quotaInfo=y,O}if(c.status===400){let y=new Error(`Sub-graph '${n}' rejected input: ${w}`);throw y.code="SUBGRAPH_INVALID_INPUT",y.status=400,y.subgraph=n,y.validationErrors=f?.validationErrors||null,y.missing=f?.missing||null,y}let m=new Error(`Sub-graph '${n}' trigger rejected (${c.status}): ${w}`);throw m.code="SUBGRAPH_TRIGGER_FAILED",m.status=c.status,m.subgraph=n,m}let g;try{g=await c.json()}catch(f){if(!D(f))throw f;let w=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${u.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw w.code="SUBGRAPH_TRIGGER_TIMEOUT",w.subgraph=n,w.timedOut=!0,w.cause=f,w}let p=g?.data?.jobId||g?.jobId;if(!p)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(g).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:n};let T=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Bn,A=`${i}/executions/${encodeURIComponent(p)}`,$=Date.now()+r,h="accepted",b=0,v=null;for(;Date.now()<$;){await new Promise(O=>setTimeout(O,T)),b+=1;let f=Ln($),w;try{w=await fetch(A,{headers:{Authorization:`Bearer ${a}`},signal:f.signal})}catch(O){v=D(O)?`poll TIMED OUT ${f.label}`:O?.message||String(O),I.warn(`[sub-graph] status poll for ${p} could not reach the API (${v}), will retry`);continue}if(!w.ok){if(w.status>=500){I.warn(`[sub-graph] status poll for ${p} returned ${w.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${w.status}`)}let m;try{m=await w.json()}catch(O){v=D(O)?`poll body read TIMED OUT ${f.label}`:O?.message||String(O),I.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${v}), will retry`);continue}let y=m?.data||m?.execution||m;if(h=y?.status||h,Dn.has(h)){if(h!=="completed"){let J=new Error(`Sub-graph '${n}' (${p}) ended in status '${h}'`);throw J.subgraphJobId=p,J.subgraphStatus=h,J}let O=y?.finalState||y?.state||{},F=Mt(O,e.output);return I.info(`[sub-graph] '${n}' (${p}) completed after ${b} polls`),F}}throw be(n,p,r,h,v)}import{existsSync as Ct,readFileSync as Jn}from"node:fs";import{join as We,dirname as Bt}from"node:path";var Ie=class{static async loadContext(e,t,o={}){let r={},i=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Bt(We(t,e));for(let l of i){let d=await this.findAndMergeContextFiles(l,a,t);if(d){let S=l.replace(/\.[^.]+$/,"").toLowerCase();r[S]=d}}}let s=o.discovery||{};for(let[a,l]of Object.entries(s))try{let d=We(t,l);Ct(d)&&(r[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${l}': ${d.message}`)}return r}static async findAndMergeContextFiles(e,t,o){let r=[],i=t;for(;i.startsWith(o);){let s=We(i,e);if(Ct(s))try{r.unshift(await this.loadFile(s))}catch(l){console.warn(`[workflow] could not load ${e} from ${s}: ${l.message}`)}let a=Bt(i);if(a===i)break;i=a}return r.length===0?null:r.every(s=>typeof s=="string")?r.join(`
35
35
 
36
36
  ---
37
37
 
38
- `):r.every(i=>typeof i=="object")?Object.assign({},...r):r[r.length-1]}static async loadFile(e){let t=Mn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),r=await import(o(e).href);return r.default||r}return t}};import{mkdirSync as Nt,existsSync as De,writeFileSync as Ot,unlinkSync as Bn}from"node:fs";import{join as Z,resolve as Ct}from"node:path";import{config as jn}from"dotenv";import{zodToJsonSchema as Pt}from"zod-to-json-schema";import{z as Se}from"zod";import Dn from"handlebars";function Ln({traceFrom:n,sessionId:e,sessionPath:t,idSource:o,mkdirFresh:r}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let i=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${n} pid=${process.pid} ppid=${i} sessionId=${e} source=${o} mkdir=${r?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let y=(new Error("session trace").stack||"").split(`
38
+ `):r.every(s=>typeof s=="object")?Object.assign({},...r):r[r.length-1]}static async loadFile(e){let t=Jn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),r=await import(o(e).href);return r.default||r}return t}};import{mkdirSync as jt,existsSync as He,writeFileSync as Ut,unlinkSync as zn}from"node:fs";import{join as X,resolve as Lt}from"node:path";import{config as Yn}from"dotenv";import{zodToJsonSchema as Dt}from"zod-to-json-schema";import{z as Te}from"zod";import Zn from"handlebars";function qn({traceFrom:n,sessionId:e,sessionPath:t,idSource:o,mkdirFresh:r}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${n} pid=${process.pid} ppid=${s} sessionId=${e} source=${o} mkdir=${r?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let S=(new Error("session trace").stack||"").split(`
39
39
  `).slice(2,14).join(`
40
40
  `);console.log(`[zibby:session] stack (${n}):
41
- ${y}`)}}function Un(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Wn(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Ct(String(e).trim())}catch{return String(e).trim()}}function Fn(){Un()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Gn({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Hn(n={}){let e=it.map(s=>process.env[s]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,r=n.paths?.sessionPrefix;return r?`${r}_${o}`:o}function Jn({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let r=t.sessionPath,s=t.sessionTimestamp,i="initialState.sessionPath";if(!r&&process.env.ZIBBY_SESSION_PATH)try{let d=Ct(String(process.env.ZIBBY_SESSION_PATH));d&&(r=d,i="ZIBBY_SESSION_PATH")}catch{}let a;if(r)a=String(r).split(/[/\\]/).filter(Boolean).pop(),s==null&&(s=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,i="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,i="config.sessionId"):(a=Hn(e),i="generated")}s=s??Date.now();let y=e.paths?.output||he;r=Z(n,y,rt,a)}let u=!De(r);return u&&Nt(r,{recursive:!0}),(u||i!=="initialState.sessionPath")&&Ln({traceFrom:o,sessionId:a,sessionPath:r,idSource:i,mkdirFresh:u}),Gn({sessionPath:r,sessionId:a}),{sessionPath:r,sessionId:a,sessionTimestamp:s}}var _e=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,o={}){if(!(t instanceof U)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let i=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:i.workflow,retries:i.retries,onComplete:i.onComplete,execute:async d=>{let y=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof i.input=="function"?l=i.input(y):i.input&&typeof i.input=="object"?l=i.input:l={},At(i.workflow,{input:l,async:i.async===!0,conversationId:typeof i.conversationId=="function"?i.conversationId(y):i.conversationId,output:i.output,timeoutMs:i.timeoutMs,pollIntervalMs:i.pollIntervalMs,signal:y?._signal,parentAgent:d?.agent})}},u=new U(a);return u.name=e,this.nodes.set(e,u),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let r=!(t instanceof U)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,s=t instanceof U?t:new U(r?{...t,_isRouter:!0}:t);return s.name=e,this.nodes.set(e,s),o.prompt?this.nodePrompts.set(e,o.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addEdge(e,t){let o=this.edges.get(e);return o===void 0?this.edges.set(e,t):typeof o=="string"?o!==t&&this.edges.set(e,[o,t]):Array.isArray(o)?o.includes(t)||o.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:o}={}){let r=this.edges.get(e);return r!==void 0&&!r.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(r)?r.join(", "):r}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:o}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,o=s=>{t.set(s,1);for(let i of this._simpleTargets(s)){if(!i||i==="END")continue;let a=t.get(i)||0;a===1?e.add(`${s}->${i}`):a===0&&o(i)}t.set(s,2)};this.entryPoint&&o(this.entryPoint);let r=new Map;for(let[s]of this.edges)for(let i of this._simpleTargets(s))!i||i==="END"||e.has(`${s}->${i}`)||r.set(i,(r.get(i)||0)+1);return{backEdges:e,joinDegree:r}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,r,s){let i=o;for(let a=e.length-1;a>=0;a--){let u=e[a],d=i;i=()=>u(t,d,r,s)}return i()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let g=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:g,data:{nodeType:g,label:l}});let m={};c._isCustomCode&&typeof c.execute=="function"&&(m.customCode=c.execute.toString());let b=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;b&&(m.description=b);let A=this.nodePrompts.get(l);if(A)m.prompt=A;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(m.prompt=p,m.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(m.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(m.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(m.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof Se?.toJSONSchema=="function")try{p=Se.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Pt(c.outputSchema,{target:"openApi3"})}catch{}m.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else m.outputSchema={schema:c.outputSchema};let T=(this.resolvedToolsMap||{})[l];T?.toolIds&&(m.tools=T.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(m.skills=[...f]);let h=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;h&&h.length>0&&(m.plugins=h.map(p=>p&&typeof p=="object"?{...p}:p));let I=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;I&&I.length>0&&(m.stores=I.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(m).length>0&&(t[l]=m)}let o=[];for(let[l,c]of this.edges)if(typeof c=="string")o.push({source:l,target:c});else if(Array.isArray(c))for(let g of c)o.push({source:l,target:g});else if(c.conditional){let g=this.conditionalCodeMap.get(l)||c.routes.toString(),m=this._inferConditionalTargets(c.routes,c.labels),b=c.labels||{},A=this.nodes.get(l),T=A?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!A,f=l;if(!T){let h=`${l}__branch`;e.push({id:h,type:"decision",data:{nodeType:"decision",label:h}}),o.push({source:l,target:h}),f=h}for(let h of m){let I={source:f,target:h,data:{conditionalCode:g}};b[h]&&(I.label=b[h]),o.push(I)}}let r=l=>{if(!l)return null;if(typeof Se?.toJSONSchema=="function")try{return Se.toJSONSchema(l)}catch{}try{return Pt(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let s=0;for(let l of o)if(l.target==="END"){s+=1;let c=`END__${s}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){s+=1;let c=`END__${s}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:l,target:c})}let i=this._topoOrderNodes(e,o),a=this._runtimeSchema(),u=r(a||this.stateSchema),d=r(this.inputSchema),y=r(this.contextSchema);return{nodes:i,edges:o,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:y}}_topoOrderNodes(e,t){let o=new Map(e.map((l,c)=>[l.id,c])),r=new Map(e.map(l=>[l.id,l])),s=new Map(e.map(l=>[l.id,0])),i=new Map(e.map(l=>[l.id,[]]));for(let l of t)i.has(l.source)&&s.has(l.target)&&(i.get(l.source).push(l.target),s.set(l.target,s.get(l.target)+1));let a=new Set,u=new Set(o.keys()),d=[...u].filter(l=>s.get(l)===0),y=[];for(;y.length<e.length;){let l;if(d.length>0){if(d.sort((c,g)=>o.get(c)-o.get(g)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,g)=>o.get(c)-o.get(g))[0];a.add(l),u.delete(l),y.push(r.get(l));for(let c of i.get(l)||[])s.set(c,s.get(c)-1),s.get(c)<=0&&!a.has(c)&&d.push(c)}return y}_inferConditionalTargets(e,t){let o=e.toString(),r=new Set,s=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,i;for(;(i=s.exec(o))!==null;){let d=i[2]!==void 0?i[2]:i[3];d!==void 0&&d!==""&&r.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let u=new Set;for(let d of r)a.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,y;for(;(y=d.exec(o))!==null;)u.add(y[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let r=e.$ref.replace("#/definitions/","");o=e.definitions[r]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],r=e.properties||{},s=e.required||[];for(let[i,a]of Object.entries(r)){let u=t?`${t}.${i}`:i;o.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(i),optional:!s.includes(i)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${u}[]`))}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[r,s]of Object.entries(t))if(!(r==="success"||r==="raw"||r==="nextNode")){if(typeof s=="string"&&s.length<=80)o.push(`${r}: ${s}`);else if(Array.isArray(s)){let i=s.length,a=s.filter(d=>d?.passed===!0).length,u=s.some(d=>d?.passed!==void 0);o.push(u?`${r}: ${a}/${i} passed${i-a?`, ${i-a} failed`:""}`:`${r}: ${i} items`)}if(o.length>=4)break}return o}async run(e,t={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(S){let w=new Error(`agent.normalizeInput() rejected the trigger input: ${S?.message||S}`);throw w.cause=S,w.code=S?.code||"NORMALIZE_INPUT_FAILED",w}let r=new AbortController;o.signal&&(o.signal.aborted?r.abort():o.signal.addEventListener("abort",()=>r.abort(),{once:!0}));let s=o.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,i=t.cwd||process.cwd();jn({path:Z(i,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let S=Z(i,".zibby.config.js");De(S)&&(a=(await import(S)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let S=a?.agent;S?.provider?u=S.provider:S?.gemini?u="gemini":S?.claude?u="claude":S?.cursor?u="cursor":S?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},y=this._runtimeSchema();if(y){let S=y.safeParse(t);if(!S.success){let w=S.error.issues.map(M=>`${M.path.join(".")}: ${M.message}`);throw console.error("\u274C Initial state validation failed:"),w.forEach(M=>console.error(` - ${M}`)),new Error(`State validation failed: ${w.join(", ")}`)}P.step("State validated against schema")}let l=Wn(),c=t.sessionPath||l;c||Fn();let{sessionPath:g,sessionTimestamp:m,sessionId:b}=Jn({cwd:i,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});P.step(`Session ${b}`);let A=await we.loadContext(t.specPath||"",i,d);Object.keys(A).length>0&&P.step(`Context loaded: ${Object.keys(A).join(", ")}`);let T=t.outputPath;!T&&t.specPath&&(e?.calculateOutputPath?T=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new de({...t,config:a,agentType:u,outputPath:T,sessionPath:g,sessionTimestamp:m,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:r.signal}),h=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:I}=await Promise.resolve().then(()=>(ge(),ct)),p=a.skills&&typeof a.skills=="object"?a.skills:{},E=Object.values(p).filter(S=>S&&typeof S=="object"&&typeof S.id=="string"),$=S=>{for(let w of E)if(w.id===S)return w;return I(S)},v=new Set;for(let[,S]of this.nodes)for(let w of S.config?.skills||[])v.add(w);for(let S of v){let w=$(S);if(typeof w?.middleware=="function")try{let M=await w.middleware();typeof M=="function"&&h.set(S,M)}catch{}}let{backEdges:Dt,joinDegree:Lt}=this._analyzeFlow(),Ie=new Map,X=[],Ee=(S,w,M)=>{if(!S||S==="END")return;let D=Lt.get(S)||0;if(M&&D>1&&!Dt.has(`${w}->${S}`)){let Q=(Ie.get(S)||0)+1;if(Q<D){Ie.set(S,Q);return}Ie.set(S,0)}X.includes(S)||X.push(S)};this.entryPoint&&X.push(this.entryPoint);let ae=[],Fe=a?.recursionLimit??100,Ut=0;try{for(;X.length>0;){let w=X.pop();if(!w||w==="END")continue;if(++Ut>Fe)throw new Error(`Workflow exceeded recursion limit (${Fe}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let M=Z(g,st);if(De(M)){try{Bn(M)}catch{}r.abort()}if(r.signal.aborted)return console.warn(`
42
- \u{1F6D1} External stop requested \u2014 ending workflow.`),P.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ae,stoppedExternally:!0};let D=this.nodes.get(w);if(!D)throw new Error(`Node '${w}' not found in graph`);let Q=JSON.stringify({sessionPath:g,sessionTimestamp:m,currentNode:w,createdAt:new Date().toISOString(),config:f.get("config")}),Wt=Z(g,K);Ot(Wt,Q,"utf-8");let Ge=f.get("config")?.paths?.output||he,Ft=Z(i,Ge,K);Nt(Z(i,Ge),{recursive:!0});try{Ot(Ft,Q,"utf-8")}catch{}let He=t.onPipelineProgress;if(typeof He=="function")try{He({cwd:i,sessionPath:g,sessionId:b,outputBase:f.get("config")?.paths?.output||he,currentNode:w})}catch{}let Gt=(this.resolvedToolsMap||{})[w]||null;f.set("_currentNodeTools",Gt);let Ht=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Ht[w]||{}),P.nodeStart(w);let Je=Date.now(),ce=this.nodePrompts.get(w);if(!this._invokeAgent){let x=await Promise.resolve().then(()=>(se(),re));this._invokeAgent=x.invokeAgent}let Jt=this._invokeAgent,$e={},zt=D.config?.skills||[];for(let x of zt){let C=$(x);if(typeof C?.invokeAgentOptions=="function")try{let k=C.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:w});k&&typeof k=="object"&&($e={...$e,...k})}catch(k){console.warn(`[graph] skill '${x}' invokeAgentOptions threw: ${k.message}`)}}let ze=async(x,C,k={})=>{let B=Jt(x,C,{...$e,...k,signal:r.signal});return B.catch(()=>{}),r.signal.aborted?B:Promise.race([B,new Promise((q,L)=>{let R=()=>{setTimeout(()=>{let ee=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${s}ms`);ee.name="AbortError",L(ee)},s)};r.signal.addEventListener("abort",R,{once:!0})})])},Yt=async(x={},C={})=>{let k=C.prompt||"";if(ce){let B=this._compiledPrompts.get(w);B||(B=Dn.compile(ce,{noEscape:!0}),this._compiledPrompts.set(w,B));try{k=B(x)}catch(q){throw console.error(`\u274C Template rendering failed for node '${w}':`,q.message),new Error(`Template rendering failed: ${q.message}`,{cause:q})}}else if(!k)throw new Error(`No prompt template configured for node '${w}' and no prompt provided in options`);return ze(k,{state:f.getAll(),images:C.images||[]},{model:C.model||f.get("model"),workspace:f.get("workspace"),schema:C.schema,...C,signal:r.signal,nodeName:w})},Ye=f.getAll(),Zt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let x of Zt)Object.prototype.hasOwnProperty.call(Ye,x)&&console.warn(`[workflow] node "${w}": state key "${x}" is shadowed by the engine context prop; read it via context.state.get('${x}')`);let Ze={...Ye,state:f,invokeAgent:Yt,_coreInvokeAgent:ze,agent:e,nodeId:w,promptTemplate:ce,getPromptTemplate:()=>ce};try{let x=(D.config?.skills||[]).map(R=>h.get(R)).filter(Boolean),C=[...this.middleware,...x],k;k=await gt(e,r.signal,async()=>C.length>0?this._composeMiddleware(C,w,async()=>D.execute(Ze,f),f.getAll(),f):D.execute(Ze,f));let B=Date.now()-Je;if(ae.push({node:w,success:k.success,duration:B,timestamp:new Date().toISOString()}),!k.success){if(r.signal.aborted)return P.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ae,stoppedExternally:!0};f.append("errors",{node:w,error:k.error});let R=D.config?.retries||0,ee=`${w}_retries`,le=f.getAll()[ee]||0;if(le<R){P.stepInfo(`Retrying (attempt ${le+1}/${R})`),f.update({[ee]:le+1,[`${w}_raw`]:k.raw});continue}throw P.nodeFailed(w,k.error,{duration:B}),new Error(`Node '${w}' failed after ${le} attempts: ${k.error}`)}f.update({[w]:k.output});let q=this._summarizeNodeOutput(w,k.output);P.nodeComplete(w,{duration:B,details:q});let L=this.edges.get(w);if(L)if(L.conditional){let R=L.routes(f.getAll());P.route(w,R),Ee(R,w,!1)}else if(Array.isArray(L))for(let R=L.length-1;R>=0;R--)Ee(L[R],w,!0);else Ee(L,w,!0)}catch(x){throw P.isInsideNode&&P.nodeFailed(w,x.message,{duration:Date.now()-Je}),f.set("failed",!0),f.set("failedAt",w),x}}P.graphComplete();let S={success:!0,state:f.getAll(),executionLog:ae};return e&&typeof e.onComplete=="function"&&await e.onComplete(S),S}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(S){console.warn(`[workflow] agent.cleanup() failed: ${S.message}`)}}}};var Le=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Le]||(globalThis[Le]=new Map);var Ue=globalThis[Le];function zn(n,e){Ue.set(n,e)}function Rt(n){return Ue.get(n)}function We(n){return Ue.has(n)}zn("ai_agent",{name:"ai_agent",factory:!0,create:(n,e={})=>({name:n,_isCustomCode:!0,execute:async t=>{let o=t?._coreInvokeAgent;o||(o=(await Promise.resolve().then(()=>(se(),re))).invokeAgent);let r=e.extraPromptInstructions||"Execute the task based on the current state.",s=Yn(r,t),i=await o(s,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:i,nodeId:n},raw:typeof i=="string"?i:i.raw}}})});function Yn(n,e){let t=/@([\w.]+)/g,o=new Set,r;for(;(r=t.exec(n))!==null;)o.add(r[1]);if(o.size===0)return n;let s=[],i=new Set;for(let a of o){let u=a.split(".")[0];if(i.has(u))continue;let d=a.split(".").reduce((c,g)=>c?.[g],e);if(d===void 0)continue;let y=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),l=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());s.push(`## ${l}
43
- ${y}`),a.includes(".")||i.add(u)}return s.length===0?n:`${n}
41
+ ${S}`)}}function Kn(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Vn(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Lt(String(e).trim())}catch{return String(e).trim()}}function Xn(){Kn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Qn({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function eo(n={}){let e=ft.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,r=n.paths?.sessionPrefix;return r?`${r}_${o}`:o}function to({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let r=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!r&&process.env.ZIBBY_SESSION_PATH)try{let d=Lt(String(process.env.ZIBBY_SESSION_PATH));d&&(r=d,s="ZIBBY_SESSION_PATH")}catch{}let a;if(r)a=String(r).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,s="ZIBBY_SESSION_ID";else{let u=e.sessionId!=null?String(e.sessionId).trim():"";u&&u!=="last"?(a=u,s="config.sessionId"):(a=eo(e),s="generated")}i=i??Date.now();let S=e.paths?.output||Se;r=X(n,S,dt,a)}let l=!He(r);return l&&jt(r,{recursive:!0}),(l||s!=="initialState.sessionPath")&&qn({traceFrom:o,sessionId:a,sessionPath:r,idSource:s,mkdirFresh:l}),Qn({sessionPath:r,sessionId:a}),{sessionPath:r,sessionId:a,sessionTimestamp:i}}var $e=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,o={}){if(!(t instanceof W)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async d=>{let S=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,u;return typeof s.input=="function"?u=s.input(S):s.input&&typeof s.input=="object"?u=s.input:u={},Rt(s.workflow,{input:u,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(S):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:S?._signal,parentAgent:d?.agent})}},l=new W(a);return l.name=e,this.nodes.set(e,l),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let r=!(t instanceof W)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof W?t:new W(r?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),o.prompt?this.nodePrompts.set(e,o.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addEdge(e,t){let o=this.edges.get(e);return o===void 0?this.edges.set(e,t):typeof o=="string"?o!==t&&this.edges.set(e,[o,t]):Array.isArray(o)?o.includes(t)||o.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:o}={}){let r=this.edges.get(e);return r!==void 0&&!r.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(r)?r.join(", "):r}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:o}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,o=i=>{t.set(i,1);for(let s of this._simpleTargets(i)){if(!s||s==="END")continue;let a=t.get(s)||0;a===1?e.add(`${i}->${s}`):a===0&&o(s)}t.set(i,2)};this.entryPoint&&o(this.entryPoint);let r=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||r.set(s,(r.get(s)||0)+1);return{backEdges:e,joinDegree:r}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,r,i){let s=o;for(let a=e.length-1;a>=0;a--){let l=e[a],d=s;s=()=>l(t,d,r,i)}return s()}serialize(){let e=[],t={};for(let[u,c]of this.nodes){let g=this.nodeTypeMap.get(u)||(c?.config?._isRouter===!0?"decision":u);e.push({id:u,type:g,data:{nodeType:g,label:u}});let p={};c._isCustomCode&&typeof c.execute=="function"&&(p.customCode=c.execute.toString());let T=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;T&&(p.description=T);let A=this.nodePrompts.get(u);if(A)p.prompt=A;else if(typeof c.prompt=="function")try{let m=c.prompt({});typeof m=="string"&&m.trim()&&(p.prompt=m,p.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(p.executeCode=c.customExecute.toString());let $=c?.config?.dispatchesWorkflow;if(typeof $=="string"&&$.trim())p.dispatchesWorkflow=$.trim();else if(Array.isArray($)){let m=[...new Set($.filter(y=>typeof y=="string").map(y=>y.trim()).filter(Boolean))];m.length&&(p.dispatchesWorkflow=m)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(p.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let m=null;if(typeof Te?.toJSONSchema=="function")try{m=Te.toJSONSchema(c.outputSchema)}catch{}if(!m)try{m=Dt(c.outputSchema,{target:"openApi3"})}catch{}p.outputSchema=m?{jsonSchema:m,variables:this._flattenJsonSchemaToVariables(m)}:{schema:c.outputSchema}}else p.outputSchema={schema:c.outputSchema};let h=(this.resolvedToolsMap||{})[u];h?.toolIds&&(p.tools=h.toolIds);let b=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;b&&b.length>0&&(p.skills=[...b]);let v=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;v&&v.length>0&&(p.plugins=v.map(m=>m&&typeof m=="object"?{...m}:m));let f=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;f&&f.length>0&&(p.stores=f.map(m=>m&&typeof m=="object"?{...m}:m));let w=Array.isArray(c?.config?.uses)?c.config.uses:typeof c?.config?.uses=="string"?[c.config.uses]:Array.isArray(c?.uses)?c.uses:typeof c?.uses=="string"?[c.uses]:null;if(w&&w.length>0){let m=new Set,y=[];for(let O of w){let F=typeof O=="string"?O.trim():"";!F||m.has(F)||(m.add(F),y.push(F))}y.length>0&&(p.uses=y)}Object.keys(p).length>0&&(t[u]=p)}let o=[];for(let[u,c]of this.edges)if(typeof c=="string")o.push({source:u,target:c});else if(Array.isArray(c))for(let g of c)o.push({source:u,target:g});else if(c.conditional){let g=this.conditionalCodeMap.get(u)||c.routes.toString(),p=this._inferConditionalTargets(c.routes,c.labels),T=c.labels||{},A=this.nodes.get(u),$=A?.config?._isRouter===!0||this.nodeTypeMap.get(u)==="decision"||!A,h=u;if(!$){let b=`${u}__branch`;e.push({id:b,type:"decision",data:{nodeType:"decision",label:b}}),o.push({source:u,target:b}),h=b}for(let b of p){let v={source:h,target:b,data:{conditionalCode:g}};T[b]&&(v.label=T[b]),o.push(v)}}let r=u=>{if(!u)return null;if(typeof Te?.toJSONSchema=="function")try{return Te.toJSONSchema(u)}catch{}try{return Dt(u,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let i=0;for(let u of o)if(u.target==="END"){i+=1;let c=`END__${i}`;u.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let u of this.nodes.keys())if(!this.edges.has(u)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:u,target:c})}let s=this._topoOrderNodes(e,o),a=this._runtimeSchema(),l=r(a||this.stateSchema),d=r(this.inputSchema),S=r(this.contextSchema);return{nodes:s,edges:o,nodeConfigs:t,stateSchema:l,inputSchema:d,contextSchema:S}}_topoOrderNodes(e,t){let o=new Map(e.map((u,c)=>[u.id,c])),r=new Map(e.map(u=>[u.id,u])),i=new Map(e.map(u=>[u.id,0])),s=new Map(e.map(u=>[u.id,[]]));for(let u of t)s.has(u.source)&&i.has(u.target)&&(s.get(u.source).push(u.target),i.set(u.target,i.get(u.target)+1));let a=new Set,l=new Set(o.keys()),d=[...l].filter(u=>i.get(u)===0),S=[];for(;S.length<e.length;){let u;if(d.length>0){if(d.sort((c,g)=>o.get(c)-o.get(g)),u=d.shift(),a.has(u))continue}else u=[...l].sort((c,g)=>o.get(c)-o.get(g))[0];a.add(u),l.delete(u),S.push(r.get(u));for(let c of s.get(u)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return S}_inferConditionalTargets(e,t){let o=e.toString(),r=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(o))!==null;){let d=s[2]!==void 0?s[2]:s[3];d!==void 0&&d!==""&&r.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let l=new Set;for(let d of r)a.has(d)&&l.add(d);if(l.size===0){let d=/return\s+['"]([^'"]+)['"]/g,S;for(;(S=d.exec(o))!==null;)l.add(S[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let r=e.$ref.replace("#/definitions/","");o=e.definitions[r]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],r=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(r)){let l=t?`${t}.${s}`:s;o.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${l}[]`))}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[r,i]of Object.entries(t))if(!(r==="success"||r==="raw"||r==="nextNode")){if(typeof i=="string"&&i.length<=80)o.push(`${r}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(d=>d?.passed===!0).length,l=i.some(d=>d?.passed!==void 0);o.push(l?`${r}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${r}: ${s} items`)}if(o.length>=4)break}return o}async run(e,t={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(E){let _=new Error(`agent.normalizeInput() rejected the trigger input: ${E?.message||E}`);throw _.cause=E,_.code=E?.code||"NORMALIZE_INPUT_FAILED",_}let r=new AbortController;o.signal&&(o.signal.aborted?r.abort():o.signal.addEventListener("abort",()=>r.abort(),{once:!0}));let i=o.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();Yn({path:X(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let E=X(s,".zibby.config.js");He(E)&&(a=(await import(E)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let E=a?.agent;E?.provider?l=E.provider:E?.gemini?l="gemini":E?.claude?l="claude":E?.cursor?l="cursor":E?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},S=this._runtimeSchema();if(S){let E=S.safeParse(t);if(!E.success){let _=E.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),_.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${_.join(", ")}`)}M.step("State validated against schema")}let u=Vn(),c=t.sessionPath||u;c||Xn();let{sessionPath:g,sessionTimestamp:p,sessionId:T}=to({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});M.step(`Session ${T}`);let A=await Ie.loadContext(t.specPath||"",s,d);Object.keys(A).length>0&&M.step(`Context loaded: ${Object.keys(A).join(", ")}`);let $=t.outputPath;!$&&t.specPath&&(e?.calculateOutputPath?$=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new ge({...t,config:a,agentType:l,outputPath:$,sessionPath:g,sessionTimestamp:p,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:r.signal}),b=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:v}=await Promise.resolve().then(()=>(we(),gt)),f=a.skills&&typeof a.skills=="object"?a.skills:{},w=Object.values(f).filter(E=>E&&typeof E=="object"&&typeof E.id=="string"),m=E=>{for(let _ of w)if(_.id===E)return _;return v(E)},y=new Set;for(let[,E]of this.nodes)for(let _ of E.config?.skills||[])y.add(_);for(let E of y){let _=m(E);if(typeof _?.middleware=="function")try{let C=await _.middleware();typeof C=="function"&&b.set(E,C)}catch{}}let{backEdges:O,joinDegree:F}=this._analyzeFlow(),J=new Map,ne=[],Ae=(E,_,C)=>{if(!E||E==="END")return;let L=F.get(E)||0;if(C&&L>1&&!O.has(`${_}->${E}`)){let oe=(J.get(E)||0)+1;if(oe<L){J.set(E,oe);return}J.set(E,0)}ne.includes(E)||ne.push(E)};this.entryPoint&&ne.push(this.entryPoint);let pe=[],Ze=a?.recursionLimit??100,Jt=0;try{for(;ne.length>0;){let _=ne.pop();if(!_||_==="END")continue;if(++Jt>Ze)throw new Error(`Workflow exceeded recursion limit (${Ze}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let C=X(g,pt);if(He(C)){try{zn(C)}catch{}r.abort()}if(r.signal.aborted)return console.warn(`
42
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),M.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:pe,stoppedExternally:!0};let L=this.nodes.get(_);if(!L)throw new Error(`Node '${_}' not found in graph`);let oe=JSON.stringify({sessionPath:g,sessionTimestamp:p,currentNode:_,createdAt:new Date().toISOString(),config:h.get("config")}),zt=X(g,ee);Ut(zt,oe,"utf-8");let qe=h.get("config")?.paths?.output||Se,Yt=X(s,qe,ee);jt(X(s,qe),{recursive:!0});try{Ut(Yt,oe,"utf-8")}catch{}let Ke=t.onPipelineProgress;if(typeof Ke=="function")try{Ke({cwd:s,sessionPath:g,sessionId:T,outputBase:h.get("config")?.paths?.output||Se,currentNode:_})}catch{}let Zt=(this.resolvedToolsMap||{})[_]||null;h.set("_currentNodeTools",Zt);let qt=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",qt[_]||{}),M.nodeStart(_);let Ve=Date.now(),fe=this.nodePrompts.get(_);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(ce(),ae));this._invokeAgent=k.invokeAgent}let Kt=this._invokeAgent,Oe={},Vt=L.config?.skills||[];for(let k of Vt){let R=m(k);if(typeof R?.invokeAgentOptions=="function")try{let x=R.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:_});x&&typeof x=="object"&&(Oe={...Oe,...x})}catch(x){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${x.message}`)}}let Xe=async(k,R,x={})=>{let B=Kt(k,R,{...Oe,...x,signal:r.signal});return B.catch(()=>{}),r.signal.aborted?B:Promise.race([B,new Promise((Q,G)=>{let U=()=>{setTimeout(()=>{let tt=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);tt.name="AbortError",G(tt)},i)};r.signal.addEventListener("abort",U,{once:!0})})])},Xt=async(k={},R={})=>{let x=R.prompt||"";if(fe){let B=this._compiledPrompts.get(_);B||(B=Zn.compile(fe,{noEscape:!0}),this._compiledPrompts.set(_,B));try{x=B(k)}catch(Q){throw console.error(`\u274C Template rendering failed for node '${_}':`,Q.message),new Error(`Template rendering failed: ${Q.message}`,{cause:Q})}}else if(!x)throw new Error(`No prompt template configured for node '${_}' and no prompt provided in options`);return Xe(x,{state:h.getAll(),images:R.images||[]},{model:R.model||h.get("model"),workspace:h.get("workspace"),schema:R.schema,...R,signal:r.signal,nodeName:_})},Qe=h.getAll(),Qt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of Qt)Object.prototype.hasOwnProperty.call(Qe,k)&&console.warn(`[workflow] node "${_}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let et={...Qe,state:h,invokeAgent:Xt,_coreInvokeAgent:Xe,agent:e,nodeId:_,promptTemplate:fe,getPromptTemplate:()=>fe};try{let k=(L.config?.skills||[]).map(U=>b.get(U)).filter(Boolean),R=[...this.middleware,...k],x;x=await Et(e,r.signal,async()=>R.length>0?this._composeMiddleware(R,_,async()=>L.execute(et,h),h.getAll(),h):L.execute(et,h));let B=Date.now()-Ve;if(pe.push({node:_,success:x.success,duration:B,timestamp:new Date().toISOString()}),!x.success){if(r.signal.aborted)return M.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:pe,stoppedExternally:!0};h.append("errors",{node:_,error:x.error});let U=(L.config?.retries||0)+1;throw M.nodeFailed(_,x.error,{duration:B}),new Error(`Node '${_}' failed after ${U} attempt(s): ${x.error}`)}h.update({[_]:x.output});let Q=this._summarizeNodeOutput(_,x.output);M.nodeComplete(_,{duration:B,details:Q});let G=this.edges.get(_);if(G)if(G.conditional){let U=G.routes(h.getAll());M.route(_,U),Ae(U,_,!1)}else if(Array.isArray(G))for(let U=G.length-1;U>=0;U--)Ae(G[U],_,!0);else Ae(G,_,!0)}catch(k){throw M.isInsideNode&&M.nodeFailed(_,k.message,{duration:Date.now()-Ve}),h.set("failed",!0),h.set("failedAt",_),k}}M.graphComplete();let E={success:!0,state:h.getAll(),executionLog:pe};return e&&typeof e.onComplete=="function"&&await e.onComplete(E),E}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(E){console.warn(`[workflow] agent.cleanup() failed: ${E.message}`)}}}};var Je=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Je]||(globalThis[Je]=new Map);var ze=globalThis[Je];function no(n,e){ze.set(n,e)}function Gt(n){return ze.get(n)}function Ye(n){return ze.has(n)}no("ai_agent",{name:"ai_agent",factory:!0,create:(n,e={})=>({name:n,_isCustomCode:!0,execute:async t=>{let o=t?._coreInvokeAgent;o||(o=(await Promise.resolve().then(()=>(ce(),ae))).invokeAgent);let r=e.extraPromptInstructions||"Execute the task based on the current state.",i=oo(r,t),s=await o(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:s,nodeId:n},raw:typeof s=="string"?s:s.raw}}})});function oo(n,e){let t=/@([\w.]+)/g,o=new Set,r;for(;(r=t.exec(n))!==null;)o.add(r[1]);if(o.size===0)return n;let i=[],s=new Set;for(let a of o){let l=a.split(".")[0];if(s.has(l))continue;let d=a.split(".").reduce((c,g)=>c?.[g],e);if(d===void 0)continue;let S=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),u=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${u}
43
+ ${S}`),a.includes(".")||s.add(l)}return i.length===0?n:`${n}
44
44
 
45
45
  ---
46
46
  # Referenced Context
47
47
 
48
- ${s.join(`
48
+ ${i.join(`
49
49
 
50
- `)}`}ge();F();var Zn={};function Bt(n,e){if(Array.isArray(e))return Mt(e);let t=Zn[n];return!t||t.length===0?null:Mt(t)}function Mt(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},o=[];for(let r of n){let s=oe(r);if(!s){_.warn(`[workflow] unknown skill "${r}" \u2014 skipping`);continue}o.push(r);for(let i of s.tools||[])e.push({name:i.name,description:i.description,input_schema:i.input_schema||{type:"object",properties:{}}});if(!t[s.serverName])if(typeof s.resolve=="function"){let i=s.resolve();i&&(t[s.serverName]={...i,toolPrefix:r})}else{let i={};for(let a of s.envKeys||[]){let u=process.env[a];u&&(i[a]=u)}t[s.serverName]={command:s.command,args:[...s.args||[]],env:i,toolPrefix:r}}}return o.length===0?null:{toolIds:o,claudeTools:e,mcpServers:t}}F();function rr(n,e={}){let{nodes:t,edges:o,nodeConfigs:r={}}=n;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(o))throw new j("Graph edges must be an array");let s=new _e(e);e.stateSchema&&s.setStateSchema(e.stateSchema);let i=new Set,a=new Map,u={};for(let c of t){let g=be(c);a.set(c.id,{...c,resolvedType:g}),g==="decision"&&i.add(c.id)}for(let[c,g]of a){if(i.has(c))continue;let m=g.resolvedType,b=r[c]||{},A=Bt(m,b.tools);A&&(u[c]=A);let T={};b.prompt&&(T.prompt=b.prompt);let f=We(m);if(_.debug(`[workflow] compiler: node "${c}" type="${m}" registered=${f}`),b.customCode&&!f)s.addNode(c,jt(c,b.customCode,b),T),s.setNodeType(c,m);else if(f){let h=Rt(m);h.factory?s.addNode(c,h.create(c,{...b,resolvedTools:A}),T):s.addNode(c,h,T),s.setNodeType(c,m)}else if(b.executeCode)s.addNode(c,jt(c,b.executeCode,b),T),s.setNodeType(c,m);else throw new j(`Unknown node type "${m}" for node "${c}". Did you forget to register it?`)}s.resolvedToolsMap=u;let d=new Set;for(let c of o)i.has(c.target)||d.add(c.target);let y=t.find(c=>!i.has(c.id)&&!d.has(c.id));if(!y)throw new j("Could not determine entry point: no node without incoming edges found");s.setEntryPoint(y.id);let l=qn(o,"source");for(let c of o)if(!i.has(c.source))if(i.has(c.target)){let g=c.target,m=l.get(g)||[];if(m.length===0)throw new j(`Decision node "${g}" has no outgoing edges`);let b=Kn(g,m,i);s.addConditionalEdges(c.source,b)}else s.addEdge(c.source,c.target);return s}function sr(n){let e=[];if(!n||typeof n!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(n.nodes)||n.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(n.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=n.nodeConfigs||{};for(let a of n.nodes){let u=be(a);if(u==="decision"||We(u))continue;let d=t[a.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${u}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let o=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)o.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),o.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let r=new Set(n.nodes.filter(a=>be(a)==="decision").map(a=>a.id)),s=new Set;for(let a of n.edges)r.has(a.target)||s.add(a.target);let i=n.nodes.filter(a=>!r.has(a.id)&&!s.has(a.id));i.length===0?e.push("No entry point found (every node has incoming edges)"):i.length>1&&e.push(`Multiple entry points found: ${i.map(a=>a.id).join(", ")}`);for(let a of r){let u=n.edges.filter(y=>y.source===a);u.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),u.some(y=>y.data?.conditionalCode||y.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function ir(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>be(e)!=="decision").map(e=>e.id)}function be(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function qn(n,e){let t=new Map;for(let o of n){let r=o[e];t.has(r)||t.set(r,[]),t.get(r).push(o)}return t}function Kn(n,e,t){let o=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!o)throw new j(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let r=o.data?.conditionalCode||o.conditionalCode,s=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),i;try{let u=new Function(`return (${r})`)();i=d=>{let y=u(d);return s.has(y)||_.warn(`[workflow] conditional route from "${n}" returned "${y}" which is not in valid targets: ${[...s].join(", ")}`),y}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return i}function jt(n,e,t={}){let o;try{o=new Function("invokeAgent","require","console",`return (${e})`)}catch(i){throw new j(`Failed to compile customCode for node "${n}": ${i.message}`)}let r=o(async(...i)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(se(),re));return a(...i)},typeof ve<"u"?ve:void 0,console),s=null;return t.outputSchema&&(s=t.outputSchema.jsonSchema||t.outputSchema),{name:n,_isCustomCode:!0,outputSchema:s,execute:async i=>{try{let a=await r(i);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var j=class extends Error{constructor(e){super(e),this.name="CompilationError"}};export{j as CompilationError,rr as compileGraph,ir as extractSteps,sr as validateGraphConfig};
50
+ `)}`}we();z();var ro={};function Wt(n,e){if(Array.isArray(e))return Ft(e);let t=ro[n];return!t||t.length===0?null:Ft(t)}function Ft(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},o=[];for(let r of n){let i=ie(r);if(!i){I.warn(`[workflow] unknown skill "${r}" \u2014 skipping`);continue}o.push(r);for(let s of i.tools||[])e.push({name:s.name,description:s.description,input_schema:s.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let s=i.resolve();s&&(t[i.serverName]={...s,toolPrefix:r})}else{let s={};for(let a of i.envKeys||[]){let l=process.env[a];l&&(s[a]=l)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:s,toolPrefix:r}}}return o.length===0?null:{toolIds:o,claudeTools:e,mcpServers:t}}z();function yr(n,e={}){let{nodes:t,edges:o,nodeConfigs:r={}}=n;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(o))throw new j("Graph edges must be an array");let i=new $e(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let s=new Set,a=new Map,l={};for(let c of t){let g=ve(c);a.set(c.id,{...c,resolvedType:g}),g==="decision"&&s.add(c.id)}for(let[c,g]of a){if(s.has(c))continue;let p=g.resolvedType,T=r[c]||{},A=Wt(p,T.tools);A&&(l[c]=A);let $={};T.prompt&&($.prompt=T.prompt);let h=Ye(p);if(I.debug(`[workflow] compiler: node "${c}" type="${p}" registered=${h}`),T.customCode&&!h)i.addNode(c,Ht(c,T.customCode,T),$),i.setNodeType(c,p);else if(h){let b=Gt(p);b.factory?i.addNode(c,b.create(c,{...T,resolvedTools:A}),$):i.addNode(c,b,$),i.setNodeType(c,p)}else if(T.executeCode)i.addNode(c,Ht(c,T.executeCode,T),$),i.setNodeType(c,p);else throw new j(`Unknown node type "${p}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=l;let d=new Set;for(let c of o)s.has(c.target)||d.add(c.target);let S=t.find(c=>!s.has(c.id)&&!d.has(c.id));if(!S)throw new j("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(S.id);let u=so(o,"source");for(let c of o)if(!s.has(c.source))if(s.has(c.target)){let g=c.target,p=u.get(g)||[];if(p.length===0)throw new j(`Decision node "${g}" has no outgoing edges`);let T=io(g,p,s);i.addConditionalEdges(c.source,T)}else i.addEdge(c.source,c.target);return i}function Sr(n){let e=[];if(!n||typeof n!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(n.nodes)||n.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(n.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=n.nodeConfigs||{};for(let a of n.nodes){let l=ve(a);if(l==="decision"||Ye(l))continue;let d=t[a.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${l}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let o=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)o.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),o.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let r=new Set(n.nodes.filter(a=>ve(a)==="decision").map(a=>a.id)),i=new Set;for(let a of n.edges)r.has(a.target)||i.add(a.target);let s=n.nodes.filter(a=>!r.has(a.id)&&!i.has(a.id));s.length===0?e.push("No entry point found (every node has incoming edges)"):s.length>1&&e.push(`Multiple entry points found: ${s.map(a=>a.id).join(", ")}`);for(let a of r){let l=n.edges.filter(S=>S.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(S=>S.data?.conditionalCode||S.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function wr(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>ve(e)!=="decision").map(e=>e.id)}function ve(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function so(n,e){let t=new Map;for(let o of n){let r=o[e];t.has(r)||t.set(r,[]),t.get(r).push(o)}return t}function io(n,e,t){let o=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!o)throw new j(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let r=o.data?.conditionalCode||o.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),s;try{let l=new Function(`return (${r})`)();s=d=>{let S=l(d);return i.has(S)||I.warn(`[workflow] conditional route from "${n}" returned "${S}" which is not in valid targets: ${[...i].join(", ")}`),S}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return s}function Ht(n,e,t={}){let o;try{o=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new j(`Failed to compile customCode for node "${n}": ${s.message}`)}let r=o(async(...s)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(ce(),ae));return a(...s)},typeof xe<"u"?xe:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:n,_isCustomCode:!0,outputSchema:i,execute:async s=>{try{let a=await r(s);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var j=class extends Error{constructor(e){super(e),this.name="CompilationError"}};export{j as CompilationError,yr as compileGraph,wr as extractSteps,Sr as validateGraphConfig};