@zibby/agent-workflow 2.0.4 → 2.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,50 +1,50 @@
1
- var qt=Object.defineProperty;var $e=(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 le=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var Ke=(n,e)=>{for(var t in e)qt(n,t,{get:e[t],enumerable:!0})};var Ve,Vt,Te,pe,E,W=le(()=>{Ve=()=>{},Vt={debug:Ve,info:Ve,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},Te=Symbol.for("@zibby/agent-workflow.logger");globalThis[Te]||(globalThis[Te]={impl:Vt});pe=globalThis[Te],E={debug:(...n)=>pe.impl.debug?.(...n),info:(...n)=>pe.impl.info?.(...n),warn:(...n)=>pe.impl.warn?.(...n),error:(...n)=>pe.impl.error?.(...n)}});var ct=le(()=>{});var lt={};Ke(lt,{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,he=le(()=>{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={};Ke(re,{getAgentStrategy:()=>pt,invokeAgent:()=>ln,listStrategies:()=>cn,registerStrategy:()=>an,resolveInvocationExtras:()=>dt,resolveInvocationModel:()=>ut});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 ut({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,m=(typeof o=="string"?o.trim():"")||null;return i||a||u||d||e.model||m||null}function dt({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 pt(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}`)}E.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 E.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=pt(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,m=ut({config:i,options:t,strategyName:s.name,envModel:process.env.MODEL,nodeConfigModel:d}),l={...t,model:m,...dt({options:t,stateView:o,context:e}),config:i},c=n,p=l.skills||[];if(p.length>0&&!t.skipPromptFragments){let A=t.connectedIntegrations;if(!A){let g=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof g=="string"&&g.trim()!==""){A={};for(let y of g.split(",").map(w=>w.trim()).filter(Boolean))A[y]=!0}}let T=g=>{let y=g&&g.requiresIntegration;return!y||!A?!0:(Array.isArray(y)?y:[y]).some($=>A[$]===!0)},f=s.name==="assistant",_=g=>g?.inProcessOnly!==!0||f,b=p.map(g=>{let y=oe(g);if(!T(y)||!_(y))return null;let w=y?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);b.length>0&&(c+=`
1
+ var ln=Object.defineProperty;var Oe=(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(r){throw t=[r],r}};var st=(n,e)=>{for(var t in e)ln(n,t,{get:e[t],enumerable:!0})};var it,dn,Ne,ye,T,J=he(()=>{it=()=>{},dn={debug:it,info:it,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},Ne=Symbol.for("@zibby/agent-workflow.logger");globalThis[Ne]||(globalThis[Ne]={impl:dn});ye=globalThis[Ne],T={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 bt=he(()=>{});var Et={};st(Et,{clearSkills:()=>xn,getAllSkills:()=>vn,getSkill:()=>ie,getSkillSource:()=>An,hasSkill:()=>Tn,listSkillIds:()=>$n,registerSkill:()=>In});function In(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:r=!1}=e,o=n.id;if(Y.has(o)&&!r){let i=se.get(o);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${o}" 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(o,Object.freeze({...n})),t===void 0?se.delete(o):se.set(o,t)}function ie(n){return Y.get(n)||null}function Tn(n){return Y.has(n)}function An(n){return se.get(n)||null}function vn(){return new Map(Y)}function $n(){return Array.from(Y.keys())}function xn(){Y.clear(),se.clear()}var Ue,je,Y,se,we=he(()=>{Ue=Symbol.for("@zibby/agent-workflow.skills"),je=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Ue]||(globalThis[Ue]=new Map);globalThis[je]||(globalThis[je]=new Map);Y=globalThis[Ue],se=globalThis[je]});var ae={};st(ae,{getAgentStrategy:()=>At,invokeAgent:()=>Nn,listStrategies:()=>kn,registerStrategy:()=>On,resolveInvocationExtras:()=>Tt,resolveInvocationModel:()=>It});function On(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 kn(){return Z.map(n=>n.getName())}function It({config:n={},options:e={},strategyName:t,envModel:r,nodeConfigModel:o}={}){let i=n.models||{},s=typeof o=="string"&&o.trim()?o.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,u=n.agent?.[t]?.model||null,S=(typeof r=="string"?r.trim():"")||null;return s||a||l||u||e.model||S||null}function Tt({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 At(n={}){let{state:e={},preferredAgent:t=null}=n,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){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}`)}T.debug(`[workflow] agent selection: requested=${r}`);let o=Z.find(i=>i.getName()===r);if(!o){let i=Z.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!o.canHandle(n))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return T.debug(`[workflow] using agent: ${o.getName()}`),o}async function Nn(n,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},o={...e,state:r},i=At(o),s=r.config||t.config||{},a=r._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",u=!l||l===i.name?a.model:null,S=It({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:u}),d={...t,model:S,...Tt({options:t,stateView:r,context:e}),config:s},c=n,y=d.skills||[];if(y.length>0&&!t.skipPromptFragments){let v=t.connectedIntegrations;if(!v){let m=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof m=="string"&&m.trim()!==""){v={};for(let g of m.split(",").map(h=>h.trim()).filter(Boolean))v[g]=!0}}let $=m=>{let g=m&&m.requiresIntegration;return!g||!v?!0:(Array.isArray(g)?g:[g]).some(w=>v[w]===!0)},f=i.name==="assistant",I=m=>m?.inProcessOnly!==!0||f,A=y.map(m=>{let g=ie(m);if(!$(g)||!I(g))return null;let h=g?.promptFragment;return typeof h=="function"?h():h}).filter(Boolean);A.length>0&&(c+=`
2
2
 
3
- ${b.join(`
3
+ ${A.join(`
4
4
 
5
- `)}`)}let h=o._currentNodeConfig?.stores;if(Array.isArray(h)&&h.length>0&&typeof h[0]=="object"){let A=h.length<=8,T=h.map(f=>{let _=f?.id??f?.storeId??"",b=(f?.name??"").toString().trim()||_,g=f?.type?` \xB7 ${f.type}`:"",y=(f?.description||"").toString().replace(/\s+/g," ").trim(),w=`- ${b} \xB7 ${y||"(no description)"}${g} (id: ${_})`;if(A&&f?.schema&&typeof f.schema=="object"){let $=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);$.length&&(w+=`
6
- fields: ${$.join(", ")}`)}return w});c+=`
5
+ `)}`)}let p=r._currentNodeConfig?.stores;if(Array.isArray(p)&&p.length>0&&typeof p[0]=="object"){let v=p.length<=8,$=p.map(f=>{let I=f?.id??f?.storeId??"",A=(f?.name??"").toString().trim()||I,m=f?.type?` \xB7 ${f.type}`:"",g=(f?.description||"").toString().replace(/\s+/g," ").trim(),h=`- ${A} \xB7 ${g||"(no description)"}${m} (id: ${I})`;if(v&&f?.schema&&typeof f.schema=="object"){let w=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);w.length&&(h+=`
6
+ fields: ${w.join(", ")}`)}return h});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 v=o._currentNodeConfig?.extraPromptInstructions?.trim();return v&&(c+=`
9
+ ${$.join(`
10
+ `)}`}let b=r._currentNodeConfig?.extraPromptInstructions?.trim();return b&&(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
- ${v}
17
- `),E.debug(`[workflow] prompt length: ${c.length} chars`),s.invoke(c,l)}var Ne,H,se=le(()=>{ct();W();he();Ne=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ne]||(globalThis[Ne]=[]);H=globalThis[Ne]});var Kt=new Set(["__proto__","constructor","prototype"]);function ve(n){if(Kt.has(n))throw new Error(`Invalid state key: "${n}"`)}var ue=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){ve(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)ve(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){ve(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 de=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
+ ${b}
17
+ `),T.debug(`[workflow] prompt length: ${c.length} chars`),i.invoke(c,d)}var Le,Z,ce=he(()=>{bt();J();we();Le=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Le]||(globalThis[Le]=[]);Z=globalThis[Le]});var un=new Set(["__proto__","constructor","prototype"]);function ke(n){if(un.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 r of t)ke(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}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 r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(o=>o[0]);for(let o of r)try{return this.validate(JSON.parse(o))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,o]of Object.entries(this.schema)){if(o.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&o.type){let i=typeof e[r];i!==o.type&&t.push(`Field '${r}' expected ${o.type}, got ${i}`)}if(o.validate&&r in e){let i=o.validate(e[r]);i&&t.push(`Field '${r}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
18
18
  ${t.join(`
19
- `)}`);return e}};W();import{writeFileSync as Ce,readFileSync as ft,existsSync as ht,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"),Xe=O.gray("\u2514"),Ae=O.green("\u25C6"),Qe=O.hex("#c084fc")("\u25C6"),et=O.hex("#2dd4bf")("\u25C6"),ke=O.red("\u25C6"),tt=`${te} `,nt=2;function ot(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function rt(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+=tt,e.col=nt,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
- ${tt}`,e.col=nt))}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=rt(this._origStdoutWrite,e),process.stderr.write=rt(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
19
+ `)}`);return e}};J();import{writeFileSync as Fe,readFileSync as vt,existsSync as $t,mkdirSync as Mn}from"node:fs";import{join as Ge,dirname as Rn}from"node:path";import N from"chalk";var pn="__WORKFLOW_GRAPH_LOG__",oe=N.gray("\u2502"),fn=N.gray("\u250C"),at=N.gray("\u2514"),Me=N.green("\u25C6"),ct=N.hex("#c084fc")("\u25C6"),lt=N.hex("#2dd4bf")("\u25C6"),Re=N.red("\u25C6"),ut=`${oe} `,dt=2;function pt(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function ft(n,e){return(t,r,o)=>{if(typeof t!="string")return n(t,r,o);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(s+=ut,e.col=dt,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
+ ${ut}`,e.col=dt))}return n(s,r,o)}}var Pe=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=ft(this._origStdoutWrite,e),process.stderr.write=ft(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=`${pn}${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(Qe,e):process.stdout.write.bind(process.stdout)(`${te} ${Qe} ${e}
30
- `)}stepMemory(e){let t=O.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(et,t):process.stdout.write.bind(process.stdout)(`${te} ${et} ${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(` ${ot(o)}`):"";this._rawWrite(`${Xe} ${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(` ${ot(r)}`):"";this._rawWrite(`${ke} ${O.red(t)}`),this._rawWrite(`${Xe} ${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 fe=".zibby/output",st="sessions",K=".session-info.json",it=".zibby-stop";var oo=Object.freeze(["codebase-memory","code-scan","artifact"]),at=["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 de(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 E.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"){E.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let l=null;for(let c=0;c<=this.retries;c++){try{let p=await this.customExecute(e);if(typeof p=="object"&&p!==null&&p.success===!1)l={success:!1,error:p.error||"Node execution failed",raw:p.raw||null};else return this.isZodSchema?(E.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(p),raw:null}):{success:!0,output:p,raw:null}}catch(p){E.error(`[workflow] node '${this.name}' failed: ${p.message}`),p.name==="ZodError"&&E.error(`Schema errors: ${JSON.stringify(p.issues||p.errors,null,2)}`),l={success:!1,error:p.message,raw:null}}c<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return l}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(Me,e):process.stdout.write.bind(process.stdout)(`${oe} ${Me} ${e}
29
+ `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(ct,e):process.stdout.write.bind(process.stdout)(`${oe} ${ct} ${e}
30
+ `)}stepMemory(e){let t=N.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(lt,t):process.stdout.write.bind(process.stdout)(`${oe} ${lt} ${t}
31
+ `)}stepFail(e){this._origStdoutWrite?this._writeDot(Re,N.red(e)):process.stdout.write.bind(process.stdout)(`${oe} ${Re} ${N.red(e)}
32
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${fn} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:o}=t;if(o)for(let s of o)this._rawWrite(`${Me} ${s}`);let i=r?N.dim(` ${pt(r)}`):"";this._rawWrite(`${at} ${N.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:o}=r,i=o?N.dim(` ${pt(o)}`):"";this._rawWrite(`${Re} ${N.red(t)}`),this._rawWrite(`${at} ${N.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(N.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},R=new Pe;var Se=".zibby/output",ht="sessions",ee=".session-info.json",gt=".zibby-stop";var kr=Object.freeze(["codebase-memory","code-scan","artifact"]),mt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var hn=Object.freeze({authentication_failed:"deterministic",oauth_org_not_allowed:"deterministic",billing_error:"deterministic",invalid_request:"deterministic",max_output_tokens:"deterministic",rate_limit:"transient",server_error:"transient",unknown:"inconclusive"}),gn=Object.freeze([/stream idle timeout/i,/partial response received/i,/no chunks received/i,/stream ended without receiving any events/i,/stream completed without receiving/i,/socket hang up/i,/premature close/i,/\b(?:ECONNRESET|ECONNABORTED|ECONNREFUSED|EPIPE|ETIMEDOUT|EAI_AGAIN|ENETUNREACH|ENETRESET|EHOSTUNREACH)\b/,/\bfetch failed\b/i,/\bnetwork (?:error|timeout)\b/i,/request timed out/i,/\brequest timeout\b/i,/\boverloaded(?:_error)?\b/i,/\brate[_ ]limit(?:_error|ed)?\b/i,/\b(?:HTTP|http_status|status(?:\s*code)?)[:= ]\s*(?:429|5\d\d)\b/i,/\b(?:429|500|502|503|504|529)\s+(?:too many requests|internal server error|bad gateway|service unavailable|gateway time-?out|overloaded)\b/i]),mn=Object.freeze([/\bAbortError\b/,/\bAPIUserAbortError\b/,/\boperation was aborted\b/i,/\bcanceled by parent abort\b/i,/\bstopped by operator\b/i]),wt=/provider error \[([a-z_]+)(?:\s+http\s+(\d{3}))?\]/i;function Be(n){if(n==null)return"";if(typeof n=="string")return n;if(typeof n!="object")return String(n);let e=n;return[e.message,e.name,e.code,e.providerErrorText,e.cause?.message??(typeof e.cause=="string"?e.cause:void 0),e.cause?.code].filter(r=>typeof r=="string"||typeof r=="number").join(" | ")}function yn(n){if(n&&typeof n=="object"){let t=n.providerErrorKind;if(typeof t=="string"&&t.trim())return t.trim()}let e=wt.exec(Be(n));return e?e[1].toLowerCase():null}function Sn(n){if(n&&typeof n=="object"){let r=Number(n.providerErrorStatus);if(Number.isInteger(r)&&r>=100&&r<=599)return r}let e=wt.exec(Be(n)),t=e&&e[2]?Number(e[2]):NaN;return Number.isInteger(t)?t:null}function wn(n){let e=Be(n);if(!e)return"deterministic";for(let o of mn)if(o.test(e))return"deterministic";let t=yn(n);if(t){let o=hn[t];if(o==="transient"||o==="deterministic")return o}let r=Sn(n);if(r===429||r>=500&&r<=599)return"transient";for(let o of gn)if(o.test(e))return"transient";return"deterministic"}var yt=2,_n=5;function bn(n=process.env){let e=n?.AGENT_TRANSIENT_RETRIES;if(e==null||String(e).trim()==="")return yt;let t=Number(e);return!Number.isFinite(t)||t<0?yt:Math.min(_n,Math.floor(t))}var Ce=5e3,_t=3e4;function En(n=process.env){let e=n?.AGENT_TRANSIENT_BACKOFF_MS;if(e==null||String(e).trim()==="")return Ce;let t=Number(e);return!Number.isFinite(t)||t<0?Ce:Math.min(_t,Math.floor(t))}function St(n,e=Math.random,t=Ce){if(!(t>0))return 0;let r=Math.max(1,Math.floor(Number(n)||1)),o=Math.min(_t,t*2**(r-1)),i=1+(e()-.5)*.4;return Math.max(1,Math.round(o*i))}function De(n,{env:e=process.env,rand:t=Math.random}={}){let r=Math.max(0,Math.floor(Number(n)||0)),o=bn(e),i=En(e),s=0,a=0;return{get attemptsMade(){return 1+s+a},get transientUsed(){return a},get transientMax(){return o},next(l){let u=wn(l);return s<r?(s+=1,{retry:!0,paidBy:"declared",delayMs:u==="transient"?St(s,t,i):0,failureClass:u,index:s,of:r}):u==="transient"&&a<o?(a+=1,{retry:!0,paidBy:"transient",delayMs:St(a,t,i),failureClass:u,index:a,of:o}):{retry:!1,delayMs:0,failureClass:u}}}}async function xt(n,e,t,r){if(!e.retry)return!1;if(r())return T.info(`[workflow] node '${n}': run aborted \u2014 not retrying`),!1;let o=t?.message??String(t??"");return e.paidBy==="transient"?T.warn(`[workflow] node '${n}': TRANSIENT provider failure \u2014 ${o}. Retrying in ${Math.round(e.delayMs/1e3)}s (transient retry ${e.index}/${e.of}; the workspace is untouched, so files this node already wrote survive into the retry).`):T.info(`[workflow] node '${n}' failed (${e.failureClass}), retrying (${e.index}/${e.of})\u2026`),e.delayMs>0&&(await new Promise(i=>setTimeout(i,e.delayMs)),r())?(T.info(`[workflow] node '${n}': run aborted during backoff \u2014 not retrying`),!1):!0}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 T.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,o=y=>t&&typeof t.get=="function"?t.get(y):e?.[y],i=()=>o("_signal")?.aborted===!0;if(typeof this.customExecute=="function"){T.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let y=De(this.retries),p=null,b=null;for(;;){try{let f=await this.customExecute(e);if(typeof f=="object"&&f!==null&&f.success===!1)b=null,p={success:!1,error:f.error||`node '${this.name}' returned { success: false } with no \`error\` field. On a custom-code node \`success\` is RESERVED: the engine reads it as "this node failed" and stops the graph. If it was meant as a DOMAIN fact (no diff to commit, a PR deliberately skipped), give that fact its own field name and return the outcome \u2014 or set \`error\` to say what actually failed.`,raw:f.raw||null};else return this.isZodSchema?(T.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(f),raw:null}):{success:!0,output:f,raw:null}}catch(f){T.error(`[workflow] node '${this.name}' failed: ${f.message}`),f.name==="ZodError"&&T.error(`Schema errors: ${JSON.stringify(f.issues||f.errors,null,2)}`),b=f,p={success:!1,error:f.message,raw:null}}let v=b??p?.error,$=y.next(v);if(!await xt(this.name,$,v,i))break}return p&&(p.attempts=y.attemptsMade),p}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=q.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let a=o("_skillHints");a&&(s=`${a}
33
33
 
34
- ${s}`);let a=o(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Re(d,K);if(ht(l)){let p=JSON.parse(ft(l,"utf-8"));p.currentNode=this.name,Ce(l,JSON.stringify(p,null,2),"utf-8")}let c=Re(d,"..",K);if(ht(c))try{let p=JSON.parse(ft(c,"utf-8"));p.currentNode=this.name,Ce(c,JSON.stringify(p,null,2),"utf-8")}catch{}}}catch(l){E.debug(`[workflow] could not update session info: ${l.message}`)}let m=null;for(let l=0;l<=this.retries;l++)try{E.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=o().config||{},p=c.agents||{},h=this.config.agent??p[this.name]??null,v={state:o()};h&&(v.preferredAgent=h);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,v,A),_,b;if(typeof f=="string"?(_=f,b=null):f.structured?(_=f.raw||JSON.stringify(f.structured,null,2),b=f.structured):(_=f.raw||JSON.stringify(f,null,2),b=f.extracted||null),d)try{let g=Re(d,this.name,"raw_stream_output.txt");un(dn(g),{recursive:!0}),Ce(g,typeof _=="string"?_:JSON.stringify(_),"utf-8")}catch(g){E.debug(`[workflow] could not save raw output: ${g.message}`)}if(this.isZodSchema&&b){E.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(b,null,2)}`);let g=b;if(typeof this.onComplete=="function")try{g=await this.onComplete(o(),b)}catch(y){E.warn(`[workflow] onComplete hook failed: ${y.message}`)}return{success:!0,output:g,raw:_}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:_}),raw:_}}catch(g){throw new Error(`onComplete failed: ${g.message}`,{cause:g})}if(this.parser){let g=this.parser.parse(_);return E.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(g,null,2)}`),P.step("Output parsed"),{success:!0,output:g,raw:_}}return{success:!0,output:_,raw:_}}catch(c){m=c,l<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:m.message,raw:null}}};W();W();import{mkdirSync as hn,existsSync as Y,statSync as $t,readdirSync as vt,rmSync as gn}from"node:fs";import{spawn as bt}from"node:child_process";import{join as F}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 gt(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 mt(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,yt=new Map;function wt(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"),yt.set(n,{...t,cachedAt:Date.now()})}function St(n,e){Be.set(n,"failed"),yt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Me.delete(n)}function _t(n){return Be.get(n)==="ready"?Me.get(n):null}var ge=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 me(n,e,t,o="timeout",r=null){let s=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 s.code="SUBGRAPH_TIMEOUT",s.subgraphJobId=e,s.subgraphStatus=o,r&&(s.subgraphTransportError=r),s}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 It=new yn,Et=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=It.getStore()===!0,r=null;if(!o){let i=Et;Et=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 E.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await It.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||E.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){E.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function $n(n,e){let t=F(e,".ready"),o=F(e,"graph.mjs");if(Y(t)&&Y(o))return;hn(e,{recursive:!0});let r=F(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 m=bt("curl",["-fsSL",n],{stdio:["ignore","pipe","inherit"]}),l=bt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});m.stdout.pipe(l.stdin);let c,p,h=()=>{if(c!==void 0&&p!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(p!==0)return d(new Error(`tar exited ${p}`));u()}};m.on("close",v=>{c=v,h()}),l.on("close",v=>{p=v,h()}),m.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=F(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 Tt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=V(),o;try{o=In()}catch(w){throw w}E.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:m,bundleReady:l,nodeConfigs:c}=r,p=wn();if(i&&i!==p)throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,discard:!0}}),new N("runtime-mismatch",`${p} 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 h=_t(n);if(!h){let w=F(ge,`${m}@${d||"0"}`);try{await $n(a,w);try{An()}catch{}}catch($){throw $.fallback&&await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{h=await vn(w),wt(n,h,{workflowUuid:m,version:d,runtimeTag:i,cacheDir:w})}catch($){throw St(n,$),await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new N("import-failed",$.message)}}let v=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}:{}},_=Sn(e.timeoutMs),b=_n(e.signal,_),g,y;try{g=await bn(A,async()=>{let $=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph();return gt({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,f,{signal:b.signal}))}),y=g&&typeof g=="object"&&"state"in g?g.state:g}catch(w){let $=b.timedOut();throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:$?"timeout":"failed",error:$?{message:`aborted at the declared ${Math.round(_/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:w.message,code:w.code||"CHILD_THREW",stack:w.stack},durationMs:Date.now()-v}}),$?me(n,s,_):w}finally{b.dispose()}if(g&&typeof g=="object"&&g.stoppedExternally){let w=b.timedOut();if(await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:w?"timeout":"canceled",finalState:y,durationMs:Date.now()-v}}),w)throw me(n,s,_);let $=new Error(`Sub-graph '${n}' canceled by parent abort`);throw $.code="SUBGRAPH_CANCELED",$.subgraphJobId=s,$}return await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:"completed",finalState:y,durationMs:Date.now()-v}}),{finalState:y,executionId:s}}function Tn(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),r;try{r=$t(o)}catch{continue}if(r.isDirectory()){let s;try{s=vt(o)}catch{continue}for(let i of s)t.push(F(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(ge))return{evicted:0,freedBytes:0};let e=vt(ge),t=[],o=0;for(let a of e){let u=F(ge,a),d;try{d=$t(u)}catch{continue}let m=d.isDirectory()?Tn(u):d.size;o+=m,t.push({name:a,full:u,size:m,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(F(a.full,".lock")))try{gn(a.full,{recursive:!0,force:!0}),s+=a.size,i+=1}catch(u){E.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return i>0&&E.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 E.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 At(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 kt(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{E.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:b}=await Tt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:r}),g=At(b,e.output);return E.info(`[sub-graph] '${n}' completed in-process`),g}catch(b){if(b instanceof N||b?.fallback)E.info(`[sub-graph] in-process fallback for '${n}': ${b.reason||"unknown"} \u2014 using HTTP`);else throw b}let s=Pn(),i=Nn(),a=Cn(),u=Rn(),d=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(n)}/trigger`,m={input:e.input||{},...u?{parentExecutionId:u}:{},...e.conversationId?{conversationId:e.conversationId}:{}};E.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(m)});if(!l.ok){let b=null,g="";try{b=await l.json(),g=b?.error||b?.message||JSON.stringify(b)}catch{g=await l.text().catch(()=>"")}if(l.status===429){let w=b?.quotaInfo||{},$=new Error(`Sub-graph '${n}' blocked by execution quota (${w.used??"?"}/${w.limit??"?"} on plan ${w.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=w,$}if(l.status===400){let w=new Error(`Sub-graph '${n}' rejected input: ${g}`);throw w.code="SUBGRAPH_INVALID_INPUT",w.status=400,w.subgraph=n,w.validationErrors=b?.validationErrors||null,w.missing=b?.missing||null,w}let y=new Error(`Sub-graph '${n}' trigger rejected (${l.status}): ${g}`);throw y.code="SUBGRAPH_TRIGGER_FAILED",y.status=l.status,y.subgraph=n,y}let c=await l.json(),p=c?.data?.jobId||c?.jobId;if(!p)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(e.async)return E.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:n};let h=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:kn,v=`${s}/executions/${encodeURIComponent(p)}`,A=Date.now()+r,T="accepted",f=0,_=null;for(;Date.now()<A;){await new Promise(w=>setTimeout(w,h)),f+=1;let b;try{b=await fetch(v,{headers:{Authorization:`Bearer ${a}`}})}catch(w){_=w?.message||String(w),E.warn(`[sub-graph] status poll for ${p} could not reach the API (${_}), will retry`);continue}if(!b.ok){if(b.status>=500){E.warn(`[sub-graph] status poll for ${p} returned ${b.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${b.status}`)}let g;try{g=await b.json()}catch(w){_=w?.message||String(w),E.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${_}), will retry`);continue}let y=g?.data||g?.execution||g;if(T=y?.status||T,On.has(T)){if(T!=="completed"){let X=new Error(`Sub-graph '${n}' (${p}) ended in status '${T}'`);throw X.subgraphJobId=p,X.subgraphStatus=T,X}let w=y?.finalState||y?.state||{},$=At(w,e.output);return E.info(`[sub-graph] '${n}' (${p}) completed after ${f} polls`),$}}throw me(n,p,r,T,_)}import{existsSync as xt,readFileSync as Mn}from"node:fs";import{join as je,dirname as Ot}from"node:path";var ye=class{static async loadContext(e,t,o={}){let r={},s=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Ot(je(t,e));for(let u of s){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let m=u.replace(/\.[^.]+$/,"").toLowerCase();r[m]=d}}}let i=o.discovery||{};for(let[a,u]of Object.entries(i))try{let d=je(t,u);xt(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(xt(i))try{r.unshift(await this.loadFile(i))}catch(u){console.warn(`[workflow] could not load ${e} from ${i}: ${u.message}`)}let a=Ot(s);if(a===s)break;s=a}return r.length===0?null:r.every(i=>typeof i=="string")?r.join(`
34
+ ${s}`);let l=r(),u=l.cwd||process.cwd(),S=l.sessionPath;try{if(S){let y=Ge(S,ee);if($t(y)){let b=JSON.parse(vt(y,"utf-8"));b.currentNode=this.name,Fe(y,JSON.stringify(b,null,2),"utf-8")}let p=Ge(S,"..",ee);if($t(p))try{let b=JSON.parse(vt(p,"utf-8"));b.currentNode=this.name,Fe(p,JSON.stringify(b,null,2),"utf-8")}catch{}}}catch(y){T.debug(`[workflow] could not update session info: ${y.message}`)}let d=De(this.retries),c=null;for(;;)try{T.debug(`[workflow] node '${this.name}' attempt ${d.attemptsMade-1}`);let y=r().config||{},p=y.agents||{},b=this.config.agent??p[this.name]??null,v={state:r()};b&&(v.preferredAgent=b);let $={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:S,config:y,nodeName:this.name,timeout:this.config?.timeout||3e5},f=e?._coreInvokeAgent;f||(f=(await Promise.resolve().then(()=>(ce(),ae))).invokeAgent);let I=await f(s,v,$),A,m;if(typeof I=="string"?(A=I,m=null):I.structured?(A=I.raw||JSON.stringify(I.structured,null,2),m=I.structured):(A=I.raw||JSON.stringify(I,null,2),m=I.extracted||null),S)try{let g=Ge(S,this.name,"raw_stream_output.txt");Mn(Rn(g),{recursive:!0}),Fe(g,typeof A=="string"?A:JSON.stringify(A),"utf-8")}catch(g){T.debug(`[workflow] could not save raw output: ${g.message}`)}if(this.isZodSchema&&m){T.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let g=m;if(typeof this.onComplete=="function")try{g=await this.onComplete(r(),m)}catch(h){T.warn(`[workflow] onComplete hook failed: ${h.message}`)}return{success:!0,output:g,raw:A}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:A}),raw:A}}catch(g){throw new Error(`onComplete failed: ${g.message}`,{cause:g})}if(this.parser){let g=this.parser.parse(A);return T.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(g,null,2)}`),R.step("Output parsed"),{success:!0,output:g,raw:A}}return{success:!0,output:A,raw:A}}catch(y){c=y;let p=d.next(y);if(!await xt(this.name,p,y,i))break}return{success:!1,error:c.message,raw:null,attempts:d.attemptsMade}}};J();J();import{mkdirSync as Un,existsSync as V,statSync as Ut,readdirSync as jt,rmSync as jn}from"node:fs";import{spawn as Ct}from"node:child_process";import{join as H}from"node:path";import{pathToFileURL as Ln}from"node:url";import{AsyncLocalStorage as Fn}from"node:async_hooks";import{AsyncLocalStorage as Pn}from"node:async_hooks";var le=new Pn;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 Ot(n,e){let t=le.getStore()||te(),r=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(r,e)}function kt(n,e,t){let r=le.getStore()||te(),o=Object.freeze({...r,agent:n??r.agent??null,signal:e??r.signal??null});return le.run(o,t)}var We=new Map,He=new Map,Nt=new Map;function Mt(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");We.set(n,e),He.set(n,"ready"),Nt.set(n,{...t,cachedAt:Date.now()})}function Rt(n,e){He.set(n,"failed"),Nt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),We.delete(n)}function Pt(n){return He.get(n)==="ready"?We.get(n):null}function ue(n,e,t=process.env){let r=Number(t[n]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):e}function ze(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function de(n,e){return ze(ue(n,e),n)}function U(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}var _e=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Gn(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var M=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,r="timeout",o=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${r})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=r,o&&(i.subgraphTransportError=o),i}function Wn(n,e=process.env,t=process.uptime()){let r=Number.isFinite(n)?Number(n):null,o=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,s=Number.isFinite(o)&&o>0?o-i:null;if(r===null&&s===null)return null;let a=r===null?s:s===null?r:Math.min(r,s);return Math.max(1,a)}function Hn(n,e){let t=new AbortController,r=!1,o=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(o=setTimeout(()=>{r=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof o.unref=="function"&&o.unref()),{signal:t.signal,timedOut:()=>r,dispose(){o&&(clearTimeout(o),o=null),n&&n.removeEventListener("abort",i)}}}var Bt=new Fn,Dt=Promise.resolve();async function zn(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 r=Bt.getStore()===!0,o=null;if(!r){let s=Dt;Dt=new Promise(a=>{o=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 T.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await Bt.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;o&&o()}}function Jn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!t||!r||!o)throw new M("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:o}}async function Yn({apiBase:n,authToken:e,body:t}){let r=de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal})}catch(s){throw new M(U(s)?"begin-timeout":"network",U(s)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${s.message}`)}let i=null;try{i=await o.json()}catch(s){if(U(s))throw new M("begin-timeout",`begin body read TIMED OUT ${r.label}`)}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=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(o.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 M("begin-status",`begin returned ${o.status}`)}return i?.data||i}async function K({apiBase:n,authToken:e,payload:t}){let r=de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal});o.ok||T.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){T.warn(`[in-process subgraph] finalize ${U(o)?`TIMED OUT ${r.label}`:`failed: ${o.message}`}`)}}async function Zn(n,e){let t=H(e,".ready"),r=H(e,"graph.mjs");if(V(t)&&V(r))return;Un(e,{recursive:!0});let o=H(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),l=s(o,"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(r))return;await new Promise(a=>setTimeout(a,100))}throw new M("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let S=Math.ceil(1e4/1e3),d=Math.ceil(ue("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=Ct("curl",["-fsSL","--connect-timeout",String(S),"--max-time",String(d),n],{stdio:["ignore","pipe","inherit"]}),y=Ct("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(y.stdin);let p,b,v=()=>{if(p!==void 0&&b!==void 0){if(p!==0)return u(new Error(`curl exited ${p}`));if(b!==0)return u(new Error(`tar exited ${b}`));l()}};c.on("close",$=>{p=$,v()}),y.on("close",$=>{b=$,v()}),c.on("error",u),y.on("error",u)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(o)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(o)}catch{}throw new M("bundle-extract-failed",s.message)}}async function qn(n){let e=H(n,"graph.mjs");if(!V(e))throw new M("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(Ln(e).href)}catch(o){throw new M("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=t.default||Object.values(t).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new M("entry-class-missing","no buildGraph() class export found");return r}async function Lt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=te(),r;try{r=Jn()}catch(h){throw h}T.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let o=await Yn({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:S,bundleReady:d,nodeConfigs:c}=o,y=Gn();if(s&&s!==y)throw await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new M("runtime-mismatch",`${y} vs ${s}`);if(!d||!a)throw await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new M("no-bundle","workflow bundle not built yet");let p=Pt(n);if(!p){let h=H(_e,`${S}@${u||"0"}`);try{await Zn(a,h);try{Vn()}catch{}}catch(w){throw w.fallback&&await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:w.message,code:w.reason}}}),w}try{p=await qn(h),Mt(n,p,{workflowUuid:S,version:u,runtimeTag:s,cacheDir:h})}catch(w){throw Rt(n,w),await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:w.message,code:w.reason||"IMPORT_FAILED"}}}),w.fallback?w:new M("import-failed",w.message)}}let b=Date.now(),v=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,$=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...$?{nodeConfigs:c}:{}},I=Wn(e.timeoutMs),A=Hn(e.signal,I),m,g;try{m=await zn(v,async()=>{let w=await(typeof p=="function"&&p.prototype?.buildGraph?new p:p).buildGraph();return Ot({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>w.run(e.parentAgent,f,{signal:A.signal}))}),g=m&&typeof m=="object"&&"state"in m?m.state:m}catch(h){let w=A.timedOut();throw await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:w?"timeout":"failed",error:w?{message:`aborted at the declared ${Math.round(I/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:h.message,code:h.code||"CHILD_THREW",stack:h.stack},durationMs:Date.now()-b}}),w?be(n,i,I):h}finally{A.dispose()}if(m&&typeof m=="object"&&m.stoppedExternally){let h=A.timedOut();if(await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:h?"timeout":"canceled",finalState:g,durationMs:Date.now()-b}}),h)throw be(n,i,I);let w=new Error(`Sub-graph '${n}' canceled by parent abort`);throw w.code="SUBGRAPH_CANCELED",w.subgraphJobId=i,w}return await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:g,durationMs:Date.now()-b}}),{finalState:g,executionId:i}}function Kn(n){let e=0,t=[n];for(;t.length;){let r=t.pop(),o;try{o=Ut(r)}catch{continue}if(o.isDirectory()){let i;try{i=jt(r)}catch{continue}for(let s of i)t.push(H(r,s))}else e+=o.size}return e}function Vn({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=jt(_e),t=[],r=0;for(let a of e){let l=H(_e,a),u;try{u=Ut(l)}catch{continue}let S=u.isDirectory()?Kn(l):u.size;r+=S,t.push({name:a,full:l,size:S,mtimeMs:u.mtimeMs})}if(r<=n)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let o=Math.floor(n*.7),i=0,s=0;for(let a of t){if(r-i<=o)break;if(!V(H(a.full,".lock")))try{jn(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(l){T.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return s>0&&T.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:r-i}}catch(e){return T.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Qn=2e3,er=600*1e3,tr=new Set(["completed","failed","canceled","timeout"]);var nr=()=>de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function rr(n){let e=ue("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return ze(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function or(){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 sr(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function ir(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function ar(){return process.env.EXECUTION_ID||null}function Ft(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],n):n}async function Gt(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 r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(e.timeoutMs)?e.timeoutMs:er;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{T.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:m}=await Lt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:o}),g=Ft(m,e.output);return T.info(`[sub-graph] '${n}' completed in-process`),g}catch(m){if(m instanceof M||m?.fallback)T.info(`[sub-graph] in-process fallback for '${n}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let i=or(),s=sr(),a=ir(),l=ar(),u=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(n)}/trigger`,S={input:e.input||{},...l?{parentExecutionId:l}:{},...e.conversationId?{conversationId:e.conversationId}:{}};T.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let d=nr(),c;try{c=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(S),signal:d.signal})}catch(m){if(!U(m))throw m;let g=new Error(`Sub-graph '${n}' trigger TIMED OUT ${d.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=m,g}if(!c.ok){let m=null,g="";try{m=await c.json(),g=m?.error||m?.message||JSON.stringify(m)}catch{g=await c.text().catch(()=>"")}if(c.status===429){let w=m?.quotaInfo||{},O=new Error(`Sub-graph '${n}' blocked by execution quota (${w.used??"?"}/${w.limit??"?"} on plan ${w.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=w,O}if(c.status===400){let w=new Error(`Sub-graph '${n}' rejected input: ${g}`);throw w.code="SUBGRAPH_INVALID_INPUT",w.status=400,w.subgraph=n,w.validationErrors=m?.validationErrors||null,w.missing=m?.missing||null,w}let h=new Error(`Sub-graph '${n}' trigger rejected (${c.status}): ${g}`);throw h.code="SUBGRAPH_TRIGGER_FAILED",h.status=c.status,h.subgraph=n,h}let y;try{y=await c.json()}catch(m){if(!U(m))throw m;let g=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${d.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=m,g}let p=y?.data?.jobId||y?.jobId;if(!p)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(y).slice(0,200)}`);if(e.async)return T.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:n};let b=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Qn,v=`${i}/executions/${encodeURIComponent(p)}`,$=Date.now()+o,f="accepted",I=0,A=null;for(;Date.now()<$;){await new Promise(O=>setTimeout(O,b)),I+=1;let m=rr($),g;try{g=await fetch(v,{headers:{Authorization:`Bearer ${a}`},signal:m.signal})}catch(O){A=U(O)?`poll TIMED OUT ${m.label}`:O?.message||String(O),T.warn(`[sub-graph] status poll for ${p} could not reach the API (${A}), will retry`);continue}if(!g.ok){if(g.status>=500){T.warn(`[sub-graph] status poll for ${p} returned ${g.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${g.status}`)}let h;try{h=await g.json()}catch(O){A=U(O)?`poll body read TIMED OUT ${m.label}`:O?.message||String(O),T.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${A}), will retry`);continue}let w=h?.data||h?.execution||h;if(f=w?.status||f,tr.has(f)){if(f!=="completed"){let z=new Error(`Sub-graph '${n}' (${p}) ended in status '${f}'`);throw z.subgraphJobId=p,z.subgraphStatus=f,z}let O=w?.finalState||w?.state||{},G=Ft(O,e.output);return T.info(`[sub-graph] '${n}' (${p}) completed after ${I} polls`),G}}throw be(n,p,o,f,A)}import{existsSync as Wt,readFileSync as cr}from"node:fs";import{join as Je,dirname as Ht}from"node:path";var Ie=class{static async loadContext(e,t,r={}){let o={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Ht(Je(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let S=l.replace(/\.[^.]+$/,"").toLowerCase();o[S]=u}}}let s=r.discovery||{};for(let[a,l]of Object.entries(s))try{let u=Je(t,l);Wt(u)&&(o[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return o}static async findAndMergeContextFiles(e,t,r){let o=[],i=t;for(;i.startsWith(r);){let s=Je(i,e);if(Wt(s))try{o.unshift(await this.loadFile(s))}catch(l){console.warn(`[workflow] could not load ${e} from ${s}: ${l.message}`)}let a=Ht(i);if(a===i)break;i=a}return o.length===0?null:o.every(s=>typeof s=="string")?o.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 Ct,existsSync as De,writeFileSync as Pt,unlinkSync as Bn}from"node:fs";import{join as Z,resolve as Rt}from"node:path";import{config as jn}from"dotenv";import{zodToJsonSchema as Nt}from"zod-to-json-schema";import{z as we}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 m=(new Error("session trace").stack||"").split(`
38
+ `):o.every(s=>typeof s=="object")?Object.assign({},...o):o[o.length-1]}static async loadFile(e){let t=cr(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),o=await import(r(e).href);return o.default||o}return t}};import{mkdirSync as Yt,existsSync as Ye,writeFileSync as zt,unlinkSync as lr}from"node:fs";import{join as X,resolve as Zt}from"node:path";import{config as ur}from"dotenv";import{zodToJsonSchema as Jt}from"zod-to-json-schema";import{z as Te}from"zod";import dr from"handlebars";function pr({traceFrom:n,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:o}){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=${r} mkdir=${o?"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
- ${m}`)}}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 Fn(){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 Rt(String(e).trim())}catch{return String(e).trim()}}function Wn(){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=at.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=Rt(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 m=e.paths?.output||fe;r=Z(n,m,st,a)}let u=!De(r);return u&&Ct(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 Se=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 m=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof i.input=="function"?l=i.input(m):i.input&&typeof i.input=="object"?l=i.input:l={},kt(i.workflow,{input:l,async:i.async===!0,conversationId:typeof i.conversationId=="function"?i.conversationId(m):i.conversationId,output:i.output,timeoutMs:i.timeoutMs,pollIntervalMs:i.pollIntervalMs,signal:m?._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 p=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:p,data:{nodeType:p,label:l}});let h={};c._isCustomCode&&typeof c.execute=="function"&&(h.customCode=c.execute.toString());let v=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;v&&(h.description=v);let A=this.nodePrompts.get(l);if(A)h.prompt=A;else if(typeof c.prompt=="function")try{let y=c.prompt({});typeof y=="string"&&y.trim()&&(h.prompt=y,h.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(h.executeCode=c.customExecute.toString());let T=c?.config?.dispatchesWorkflow;if(typeof T=="string"&&T.trim())h.dispatchesWorkflow=T.trim();else if(Array.isArray(T)){let y=[...new Set(T.filter(w=>typeof w=="string").map(w=>w.trim()).filter(Boolean))];y.length&&(h.dispatchesWorkflow=y)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(h.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let y=null;if(typeof we?.toJSONSchema=="function")try{y=we.toJSONSchema(c.outputSchema)}catch{}if(!y)try{y=Nt(c.outputSchema,{target:"openApi3"})}catch{}h.outputSchema=y?{jsonSchema:y,variables:this._flattenJsonSchemaToVariables(y)}:{schema:c.outputSchema}}else h.outputSchema={schema:c.outputSchema};let f=(this.resolvedToolsMap||{})[l];f?.toolIds&&(h.tools=f.toolIds);let _=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;_&&_.length>0&&(h.skills=[..._]);let b=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;b&&b.length>0&&(h.plugins=b.map(y=>y&&typeof y=="object"?{...y}:y));let g=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;g&&g.length>0&&(h.stores=g.map(y=>y&&typeof y=="object"?{...y}:y)),Object.keys(h).length>0&&(t[l]=h)}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 p of c)o.push({source:l,target:p});else if(c.conditional){let p=this.conditionalCodeMap.get(l)||c.routes.toString(),h=this._inferConditionalTargets(c.routes,c.labels),v=c.labels||{},A=this.nodes.get(l),T=A?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!A,f=l;if(!T){let _=`${l}__branch`;e.push({id:_,type:"decision",data:{nodeType:"decision",label:_}}),o.push({source:l,target:_}),f=_}for(let _ of h){let b={source:f,target:_,data:{conditionalCode:p}};v[_]&&(b.label=v[_]),o.push(b)}}let r=l=>{if(!l)return null;if(typeof we?.toJSONSchema=="function")try{return we.toJSONSchema(l)}catch{}try{return Nt(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),m=r(this.contextSchema);return{nodes:i,edges:o,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:m}}_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),m=[];for(;m.length<e.length;){let l;if(d.length>0){if(d.sort((c,p)=>o.get(c)-o.get(p)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,p)=>o.get(c)-o.get(p))[0];a.add(l),u.delete(l),m.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 m}_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,m;for(;(m=d.exec(o))!==null;)u.add(m[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(I){let S=new Error(`agent.normalizeInput() rejected the trigger input: ${I?.message||I}`);throw S.cause=I,S.code=I?.code||"NORMALIZE_INPUT_FAILED",S}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 I=Z(i,".zibby.config.js");De(I)&&(a=(await import(I)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let I=a?.agent;I?.provider?u=I.provider:I?.gemini?u="gemini":I?.claude?u="claude":I?.cursor?u="cursor":I?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},m=this._runtimeSchema();if(m){let I=m.safeParse(t);if(!I.success){let S=I.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),S.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${S.join(", ")}`)}P.step("State validated against schema")}let l=Fn(),c=t.sessionPath||l;c||Wn();let{sessionPath:p,sessionTimestamp:h,sessionId:v}=Jn({cwd:i,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});P.step(`Session ${v}`);let A=await ye.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 ue({...t,config:a,agentType:u,outputPath:T,sessionPath:p,sessionTimestamp:h,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:r.signal}),_=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:b}=await Promise.resolve().then(()=>(he(),lt)),g=a.skills&&typeof a.skills=="object"?a.skills:{},y=Object.values(g).filter(I=>I&&typeof I=="object"&&typeof I.id=="string"),w=I=>{for(let S of y)if(S.id===I)return S;return b(I)},$=new Set;for(let[,I]of this.nodes)for(let S of I.config?.skills||[])$.add(S);for(let I of $){let S=w(I);if(typeof S?.middleware=="function")try{let R=await S.middleware();typeof R=="function"&&_.set(I,R)}catch{}}let{backEdges:X,joinDegree:Lt}=this._analyzeFlow(),be=new Map,Q=[],Ie=(I,S,R)=>{if(!I||I==="END")return;let D=Lt.get(I)||0;if(R&&D>1&&!X.has(`${S}->${I}`)){let ee=(be.get(I)||0)+1;if(ee<D){be.set(I,ee);return}be.set(I,0)}Q.includes(I)||Q.push(I)};this.entryPoint&&Q.push(this.entryPoint);let ae=[],We=a?.recursionLimit??100,Ut=0;try{for(;Q.length>0;){let S=Q.pop();if(!S||S==="END")continue;if(++Ut>We)throw new Error(`Workflow exceeded recursion limit (${We}) \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 R=Z(p,it);if(De(R)){try{Bn(R)}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(S);if(!D)throw new Error(`Node '${S}' not found in graph`);let ee=JSON.stringify({sessionPath:p,sessionTimestamp:h,currentNode:S,createdAt:new Date().toISOString(),config:f.get("config")}),Ft=Z(p,K);Pt(Ft,ee,"utf-8");let Ge=f.get("config")?.paths?.output||fe,Wt=Z(i,Ge,K);Ct(Z(i,Ge),{recursive:!0});try{Pt(Wt,ee,"utf-8")}catch{}let He=t.onPipelineProgress;if(typeof He=="function")try{He({cwd:i,sessionPath:p,sessionId:v,outputBase:f.get("config")?.paths?.output||fe,currentNode:S})}catch{}let Gt=(this.resolvedToolsMap||{})[S]||null;f.set("_currentNodeTools",Gt);let Ht=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Ht[S]||{}),P.nodeStart(S);let Je=Date.now(),ce=this.nodePrompts.get(S);if(!this._invokeAgent){let x=await Promise.resolve().then(()=>(se(),re));this._invokeAgent=x.invokeAgent}let Jt=this._invokeAgent,Ee={},zt=D.config?.skills||[];for(let x of zt){let C=w(x);if(typeof C?.invokeAgentOptions=="function")try{let k=C.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:S});k&&typeof k=="object"&&(Ee={...Ee,...k})}catch(k){console.warn(`[graph] skill '${x}' invokeAgentOptions threw: ${k.message}`)}}let ze=async(x,C,k={})=>{let M=Jt(x,C,{...Ee,...k,signal:r.signal});return M.catch(()=>{}),r.signal.aborted?M:Promise.race([M,new Promise((q,L)=>{let B=()=>{setTimeout(()=>{let qe=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${s}ms`);qe.name="AbortError",L(qe)},s)};r.signal.addEventListener("abort",B,{once:!0})})])},Yt=async(x={},C={})=>{let k=C.prompt||"";if(ce){let M=this._compiledPrompts.get(S);M||(M=Dn.compile(ce,{noEscape:!0}),this._compiledPrompts.set(S,M));try{k=M(x)}catch(q){throw console.error(`\u274C Template rendering failed for node '${S}':`,q.message),new Error(`Template rendering failed: ${q.message}`,{cause:q})}}else if(!k)throw new Error(`No prompt template configured for node '${S}' 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:S})},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 "${S}": 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:S,promptTemplate:ce,getPromptTemplate:()=>ce};try{let x=(D.config?.skills||[]).map(B=>_.get(B)).filter(Boolean),C=[...this.middleware,...x],k;k=await mt(e,r.signal,async()=>C.length>0?this._composeMiddleware(C,S,async()=>D.execute(Ze,f),f.getAll(),f):D.execute(Ze,f));let M=Date.now()-Je;if(ae.push({node:S,success:k.success,duration:M,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:S,error:k.error});let B=(D.config?.retries||0)+1;throw P.nodeFailed(S,k.error,{duration:M}),new Error(`Node '${S}' failed after ${B} attempt(s): ${k.error}`)}f.update({[S]:k.output});let q=this._summarizeNodeOutput(S,k.output);P.nodeComplete(S,{duration:M,details:q});let L=this.edges.get(S);if(L)if(L.conditional){let B=L.routes(f.getAll());P.route(S,B),Ie(B,S,!1)}else if(Array.isArray(L))for(let B=L.length-1;B>=0;B--)Ie(L[B],S,!0);else Ie(L,S,!0)}catch(x){throw P.isInsideNode&&P.nodeFailed(S,x.message,{duration:Date.now()-Je}),f.set("failed",!0),f.set("failedAt",S),x}}P.graphComplete();let I={success:!0,state:f.getAll(),executionLog:ae};return e&&typeof e.onComplete=="function"&&await e.onComplete(I),I}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(I){console.warn(`[workflow] agent.cleanup() failed: ${I.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 Mt(n){return Ue.get(n)}function Fe(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,p)=>c?.[p],e);if(d===void 0)continue;let m=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
- ${m}`),a.includes(".")||i.add(u)}return s.length===0?n:`${n}
41
+ ${S}`)}}function fr(){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 hr(){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 Zt(String(e).trim())}catch{return String(e).trim()}}function gr(){fr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function mr({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 yr(n={}){let e=mt.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,o=n.paths?.sessionPrefix;return o?`${o}_${r}`:r}function Sr({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let o=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let u=Zt(String(process.env.ZIBBY_SESSION_PATH));u&&(o=u,s="ZIBBY_SESSION_PATH")}catch{}let a;if(o)a=String(o).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,s="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,s="config.sessionId"):(a=yr(e),s="generated")}i=i??Date.now();let S=e.paths?.output||Se;o=X(n,S,ht,a)}let l=!Ye(o);return l&&Yt(o,{recursive:!0}),(l||s!=="initialState.sessionPath")&&pr({traceFrom:r,sessionId:a,sessionPath:o,idSource:s,mkdirFresh:l}),mr({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var Ae=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,r={}){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 u=>{let S=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof s.input=="function"?d=s.input(S):s.input&&typeof s.input=="object"?d=s.input:d={},Gt(s.workflow,{input:d,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:u?.agent})}},l=new W(a);return l.name=e,this.nodes.set(e,l),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let o=!(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(o?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){let r=this.edges.get(e);return r===void 0?this.edges.set(e,t):typeof r=="string"?r!==t&&this.edges.set(e,[r,t]):Array.isArray(r)?r.includes(t)||r.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:r}={}){let o=this.edges.get(e);return o!==void 0&&!o.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(o)?o.join(", "):o}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:r}),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,r=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&&r(s)}t.set(i,2)};this.entryPoint&&r(this.entryPoint);let o=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||o.set(s,(o.get(s)||0)+1);return{backEdges:e,joinDegree:o}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,o,i){let s=r;for(let a=e.length-1;a>=0;a--){let l=e[a],u=s;s=()=>l(t,u,o,i)}return s()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let y=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:y,data:{nodeType:y,label:d}});let p={};c._isCustomCode&&typeof c.execute=="function"&&(p.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&&(p.description=b);let v=this.nodePrompts.get(d);if(v)p.prompt=v;else if(typeof c.prompt=="function")try{let h=c.prompt({});typeof h=="string"&&h.trim()&&(p.prompt=h,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 h=[...new Set($.filter(w=>typeof w=="string").map(w=>w.trim()).filter(Boolean))];h.length&&(p.dispatchesWorkflow=h)}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 h=null;if(typeof Te?.toJSONSchema=="function")try{h=Te.toJSONSchema(c.outputSchema)}catch{}if(!h)try{h=Jt(c.outputSchema,{target:"openApi3"})}catch{}p.outputSchema=h?{jsonSchema:h,variables:this._flattenJsonSchemaToVariables(h)}:{schema:c.outputSchema}}else p.outputSchema={schema:c.outputSchema};let f=(this.resolvedToolsMap||{})[d];f?.toolIds&&(p.tools=f.toolIds);let I=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;I&&I.length>0&&(p.skills=[...I]);let A=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;A&&A.length>0&&(p.plugins=A.map(h=>h&&typeof h=="object"?{...h}:h));let m=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;m&&m.length>0&&(p.stores=m.map(h=>h&&typeof h=="object"?{...h}:h));let g=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(g&&g.length>0){let h=new Set,w=[];for(let O of g){let G=typeof O=="string"?O.trim():"";!G||h.has(G)||(h.add(G),w.push(G))}w.length>0&&(p.uses=w)}Object.keys(p).length>0&&(t[d]=p)}let r=[];for(let[d,c]of this.edges)if(typeof c=="string")r.push({source:d,target:c});else if(Array.isArray(c))for(let y of c)r.push({source:d,target:y});else if(c.conditional){let y=this.conditionalCodeMap.get(d)||c.routes.toString(),p=this._inferConditionalTargets(c.routes,c.labels),b=c.labels||{},v=this.nodes.get(d),$=v?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!v,f=d;if(!$){let I=`${d}__branch`;e.push({id:I,type:"decision",data:{nodeType:"decision",label:I}}),r.push({source:d,target:I}),f=I}for(let I of p){let A={source:f,target:I,data:{conditionalCode:y}};b[I]&&(A.label=b[I]),r.push(A)}}let o=d=>{if(!d)return null;if(typeof Te?.toJSONSchema=="function")try{return Te.toJSONSchema(d)}catch{}try{return Jt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of r)if(d.target==="END"){i+=1;let c=`END__${i}`;d.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:d,target:c})}let s=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=o(a||this.stateSchema),u=o(this.inputSchema),S=o(this.contextSchema);return{nodes:s,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:S}}_topoOrderNodes(e,t){let r=new Map(e.map((d,c)=>[d.id,c])),o=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),s=new Map(e.map(d=>[d.id,[]]));for(let d of t)s.has(d.source)&&i.has(d.target)&&(s.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(r.keys()),u=[...l].filter(d=>i.get(d)===0),S=[];for(;S.length<e.length;){let d;if(u.length>0){if(u.sort((c,y)=>r.get(c)-r.get(y)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,y)=>r.get(c)-r.get(y))[0];a.add(d),l.delete(d),S.push(o.get(d));for(let c of s.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return S}_inferConditionalTargets(e,t){let r=e.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(r))!==null;){let u=s[2]!==void 0?s[2]:s[3];u!==void 0&&u!==""&&o.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of o)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,S;for(;(S=u.exec(r))!==null;)l.add(S[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let o=e.$ref.replace("#/definitions/","");r=e.definitions[o]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],o=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(o)){let l=t?`${t}.${s}`:s;r.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${l}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[o,i]of Object.entries(t))if(!(o==="success"||o==="raw"||o==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${o}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);r.push(l?`${o}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${o}: ${s} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){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 o=new AbortController;r.signal&&(r.signal.aborted?o.abort():r.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();ur({path:X(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let E=X(s,".zibby.config.js");Ye(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 u=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(", ")}`)}R.step("State validated against schema")}let d=hr(),c=t.sessionPath||d;c||gr();let{sessionPath:y,sessionTimestamp:p,sessionId:b}=Sr({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});R.step(`Session ${b}`);let v=await Ie.loadContext(t.specPath||"",s,u);Object.keys(v).length>0&&R.step(`Context loaded: ${Object.keys(v).join(", ")}`);let $=t.outputPath;!$&&t.specPath&&(e?.calculateOutputPath?$=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ge({...t,config:a,agentType:l,outputPath:$,sessionPath:y,sessionTimestamp:p,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),I=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:A}=await Promise.resolve().then(()=>(we(),Et)),m=a.skills&&typeof a.skills=="object"?a.skills:{},g=Object.values(m).filter(E=>E&&typeof E=="object"&&typeof E.id=="string"),h=E=>{for(let _ of g)if(_.id===E)return _;return A(E)},w=new Set;for(let[,E]of this.nodes)for(let _ of E.config?.skills||[])w.add(_);for(let E of w){let _=h(E);if(typeof _?.middleware=="function")try{let C=await _.middleware();typeof C=="function"&&I.set(E,C)}catch{}}let{backEdges:O,joinDegree:G}=this._analyzeFlow(),z=new Map,ne=[],$e=(E,_,C)=>{if(!E||E==="END")return;let L=G.get(E)||0;if(C&&L>1&&!O.has(`${_}->${E}`)){let re=(z.get(E)||0)+1;if(re<L){z.set(E,re);return}z.set(E,0)}ne.includes(E)||ne.push(E)};this.entryPoint&&ne.push(this.entryPoint);let pe=[],Ve=a?.recursionLimit??100,Qt=0;try{for(;ne.length>0;){let _=ne.pop();if(!_||_==="END")continue;if(++Qt>Ve)throw new Error(`Workflow exceeded recursion limit (${Ve}) \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(y,gt);if(Ye(C)){try{lr(C)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
42
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),R.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:pe,stoppedExternally:!0};let L=this.nodes.get(_);if(!L)throw new Error(`Node '${_}' not found in graph`);let re=JSON.stringify({sessionPath:y,sessionTimestamp:p,currentNode:_,createdAt:new Date().toISOString(),config:f.get("config")}),en=X(y,ee);zt(en,re,"utf-8");let Xe=f.get("config")?.paths?.output||Se,tn=X(s,Xe,ee);Yt(X(s,Xe),{recursive:!0});try{zt(tn,re,"utf-8")}catch{}let Qe=t.onPipelineProgress;if(typeof Qe=="function")try{Qe({cwd:s,sessionPath:y,sessionId:b,outputBase:f.get("config")?.paths?.output||Se,currentNode:_})}catch{}let nn=(this.resolvedToolsMap||{})[_]||null;f.set("_currentNodeTools",nn);let rn=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",rn[_]||{}),R.nodeStart(_);let et=Date.now(),fe=this.nodePrompts.get(_);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(ce(),ae));this._invokeAgent=k.invokeAgent}let on=this._invokeAgent,xe={},sn=L.config?.skills||[];for(let k of sn){let P=h(k);if(typeof P?.invokeAgentOptions=="function")try{let x=P.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:_});x&&typeof x=="object"&&(xe={...xe,...x})}catch(x){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${x.message}`)}}let tt=async(k,P,x={})=>{let B=on(k,P,{...xe,...x,signal:o.signal});return B.catch(()=>{}),o.signal.aborted?B:Promise.race([B,new Promise((Q,F)=>{let D=()=>{setTimeout(()=>{let ot=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);ot.name="AbortError",F(ot)},i)};o.signal.addEventListener("abort",D,{once:!0})})])},an=async(k={},P={})=>{let x=P.prompt||"";if(fe){let B=this._compiledPrompts.get(_);B||(B=dr.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 tt(x,{state:f.getAll(),images:P.images||[]},{model:P.model||f.get("model"),workspace:f.get("workspace"),schema:P.schema,...P,signal:o.signal,nodeName:_})},nt=f.getAll(),cn=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of cn)Object.prototype.hasOwnProperty.call(nt,k)&&console.warn(`[workflow] node "${_}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let rt={...nt,state:f,invokeAgent:an,_coreInvokeAgent:tt,agent:e,nodeId:_,promptTemplate:fe,getPromptTemplate:()=>fe};try{let k=(L.config?.skills||[]).map(D=>I.get(D)).filter(Boolean),P=[...this.middleware,...k],x;x=await kt(e,o.signal,async()=>P.length>0?this._composeMiddleware(P,_,async()=>L.execute(rt,f),f.getAll(),f):L.execute(rt,f));let B=Date.now()-et;if(pe.push({node:_,success:x.success,duration:B,timestamp:new Date().toISOString()}),!x.success){if(o.signal.aborted)return R.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:pe,stoppedExternally:!0};f.append("errors",{node:_,error:x.error});let D=Number.isInteger(x.attempts)&&x.attempts>0?x.attempts:(L.config?.retries||0)+1;throw R.nodeFailed(_,x.error,{duration:B}),new Error(`Node '${_}' failed after ${D} attempt(s): ${x.error}`)}f.update({[_]:x.output});let Q=this._summarizeNodeOutput(_,x.output);R.nodeComplete(_,{duration:B,details:Q});let F=this.edges.get(_);if(F)if(F.conditional){let D=F.routes(f.getAll());R.route(_,D),$e(D,_,!1)}else if(Array.isArray(F))for(let D=F.length-1;D>=0;D--)$e(F[D],_,!0);else $e(F,_,!0)}catch(k){throw R.isInsideNode&&R.nodeFailed(_,k.message,{duration:Date.now()-et}),f.set("failed",!0),f.set("failedAt",_),k}}R.graphComplete();let E={success:!0,state:f.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 Ze=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Ze]||(globalThis[Ze]=new Map);var qe=globalThis[Ze];function wr(n,e){qe.set(n,e)}function qt(n){return qe.get(n)}function Ke(n){return qe.has(n)}wr("ai_agent",{name:"ai_agent",factory:!0,create:(n,e={})=>({name:n,_isCustomCode:!0,execute:async t=>{let r=t?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(ce(),ae))).invokeAgent);let o=e.extraPromptInstructions||"Execute the task based on the current state.",i=_r(o,t),s=await r(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 _r(n,e){let t=/@([\w.]+)/g,r=new Set,o;for(;(o=t.exec(n))!==null;)r.add(o[1]);if(r.size===0)return n;let i=[],s=new Set;for(let a of r){let l=a.split(".")[0];if(s.has(l))continue;let u=a.split(".").reduce((c,y)=>c?.[y],e);if(u===void 0)continue;let S=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),d=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${d}
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
- `)}`}he();W();var Zn={};function jt(n,e){if(Array.isArray(e))return Bt(e);let t=Zn[n];return!t||t.length===0?null:Bt(t)}function Bt(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){E.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}}W();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 Se(e);e.stateSchema&&s.setStateSchema(e.stateSchema);let i=new Set,a=new Map,u={};for(let c of t){let p=_e(c);a.set(c.id,{...c,resolvedType:p}),p==="decision"&&i.add(c.id)}for(let[c,p]of a){if(i.has(c))continue;let h=p.resolvedType,v=r[c]||{},A=jt(h,v.tools);A&&(u[c]=A);let T={};v.prompt&&(T.prompt=v.prompt);let f=Fe(h);if(E.debug(`[workflow] compiler: node "${c}" type="${h}" registered=${f}`),v.customCode&&!f)s.addNode(c,Dt(c,v.customCode,v),T),s.setNodeType(c,h);else if(f){let _=Mt(h);_.factory?s.addNode(c,_.create(c,{...v,resolvedTools:A}),T):s.addNode(c,_,T),s.setNodeType(c,h)}else if(v.executeCode)s.addNode(c,Dt(c,v.executeCode,v),T),s.setNodeType(c,h);else throw new j(`Unknown node type "${h}" 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 m=t.find(c=>!i.has(c.id)&&!d.has(c.id));if(!m)throw new j("Could not determine entry point: no node without incoming edges found");s.setEntryPoint(m.id);let l=qn(o,"source");for(let c of o)if(!i.has(c.source))if(i.has(c.target)){let p=c.target,h=l.get(p)||[];if(h.length===0)throw new j(`Decision node "${p}" has no outgoing edges`);let v=Kn(p,h,i);s.addConditionalEdges(c.source,v)}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=_e(a);if(u==="decision"||Fe(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=>_e(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(m=>m.source===a);u.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),u.some(m=>m.data?.conditionalCode||m.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=>_e(e)!=="decision").map(e=>e.id)}function _e(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 m=u(d);return s.has(m)||E.warn(`[workflow] conditional route from "${n}" returned "${m}" which is not in valid targets: ${[...s].join(", ")}`),m}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return i}function Dt(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 $e<"u"?$e: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();J();var br={};function Vt(n,e){if(Array.isArray(e))return Kt(e);let t=br[n];return!t||t.length===0?null:Kt(t)}function Kt(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},r=[];for(let o of n){let i=ie(o);if(!i){T.warn(`[workflow] unknown skill "${o}" \u2014 skipping`);continue}r.push(o);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:o})}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:o}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}J();function Bo(n,e={}){let{nodes:t,edges:r,nodeConfigs:o={}}=n;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(r))throw new j("Graph edges must be an array");let i=new Ae(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let s=new Set,a=new Map,l={};for(let c of t){let y=ve(c);a.set(c.id,{...c,resolvedType:y}),y==="decision"&&s.add(c.id)}for(let[c,y]of a){if(s.has(c))continue;let p=y.resolvedType,b=o[c]||{},v=Vt(p,b.tools);v&&(l[c]=v);let $={};b.prompt&&($.prompt=b.prompt);let f=Ke(p);if(T.debug(`[workflow] compiler: node "${c}" type="${p}" registered=${f}`),b.customCode&&!f)i.addNode(c,Xt(c,b.customCode,b),$),i.setNodeType(c,p);else if(f){let I=qt(p);I.factory?i.addNode(c,I.create(c,{...b,resolvedTools:v}),$):i.addNode(c,I,$),i.setNodeType(c,p)}else if(b.executeCode)i.addNode(c,Xt(c,b.executeCode,b),$),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 u=new Set;for(let c of r)s.has(c.target)||u.add(c.target);let S=t.find(c=>!s.has(c.id)&&!u.has(c.id));if(!S)throw new j("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(S.id);let d=Er(r,"source");for(let c of r)if(!s.has(c.source))if(s.has(c.target)){let y=c.target,p=d.get(y)||[];if(p.length===0)throw new j(`Decision node "${y}" has no outgoing edges`);let b=Ir(y,p,s);i.addConditionalEdges(c.source,b)}else i.addEdge(c.source,c.target);return i}function Do(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"||Ke(l))continue;let u=t[a.id]||{};u.customCode||u.executeCode||e.push(`Unknown node type "${l}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let r=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)r.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),r.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let o=new Set(n.nodes.filter(a=>ve(a)==="decision").map(a=>a.id)),i=new Set;for(let a of n.edges)o.has(a.target)||i.add(a.target);let s=n.nodes.filter(a=>!o.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 o){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 Uo(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 Er(n,e){let t=new Map;for(let r of n){let o=r[e];t.has(o)||t.set(o,[]),t.get(o).push(r)}return t}function Ir(n,e,t){let r=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!r)throw new j(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let o=r.data?.conditionalCode||r.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),s;try{let l=new Function(`return (${o})`)();s=u=>{let S=l(u);return i.has(S)||T.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 Xt(n,e,t={}){let r;try{r=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new j(`Failed to compile customCode for node "${n}": ${s.message}`)}let o=r(async(...s)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(ce(),ae));return a(...s)},typeof Oe<"u"?Oe: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 o(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,Bo as compileGraph,Uo as extractSteps,Do as validateGraphConfig};