@zibby/agent-workflow 0.6.8 → 0.6.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- var wo=Object.defineProperty;var xe=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var Se=(o,e,t)=>()=>{if(t)throw t[0];try{return o&&(e=o(o=0)),e}catch(n){throw t=[n],n}};var dt=(o,e)=>{for(var t in e)wo(o,t,{get:e[t],enumerable:!0})};function Eo(o){ae.impl={...pt,...o}}var ut,pt,ae,v,W=Se(()=>{ut=()=>{},pt={debug:ut,info:ut,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},ae={impl:pt};v={debug:(...o)=>ae.impl.debug?.(...o),info:(...o)=>ae.impl.info?.(...o),warn:(...o)=>ae.impl.warn?.(...o),error:(...o)=>ae.impl.error?.(...o)}});var Me,Be=Se(()=>{Me=class{constructor(e,t,n=0){this.name=e,this.description=t,this.priority=n}async invoke(e,t={}){throw new Error(`${this.constructor.name}.invoke() must be implemented`)}canHandle(e){throw new Error(`${this.constructor.name}.canHandle() must be implemented`)}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var kt={};dt(kt,{clearSkills:()=>Tt,getAllSkills:()=>vt,getSkill:()=>q,getSkillSource:()=>It,hasSkill:()=>bt,listSkillIds:()=>$t,registerSkill:()=>Et});function Et(o,e={}){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:n=!1}=e,s=o.id;if(H.has(s)&&!n){let i=de.get(s);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${s}" 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).`)}}H.set(s,Object.freeze({...o})),t===void 0?de.delete(s):de.set(s,t)}function q(o){return H.get(o)||null}function bt(o){return H.has(o)}function It(o){return de.get(o)||null}function vt(){return new Map(H)}function $t(){return Array.from(H.keys())}function Tt(){H.clear(),de.clear()}var De,Le,H,de,ue=Se(()=>{De=Symbol.for("@zibby/agent-workflow.skills"),Le=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[De]||(globalThis[De]=new Map);globalThis[Le]||(globalThis[Le]=new Map);H=globalThis[De],de=globalThis[Le]});var pe={};dt(pe,{getAgentStrategy:()=>Ge,invokeAgent:()=>Nt,listStrategies:()=>xt,registerStrategy:()=>At,resolveInvocationExtras:()=>Ue,resolveInvocationModel:()=>We});function At(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=z.findIndex(t=>t.getName()===o.getName());e>=0?z[e]=o:z.push(o)}function xt(){return z.map(o=>o.getName())}function We({config:o={},options:e={},strategyName:t,envModel:n,nodeConfigModel:s}={}){let i=o.models||{},r=typeof s=="string"&&s.trim()&&s.trim()!=="auto"?s.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,u=o.agent?.[t]?.model||null,h=(typeof n=="string"?n.trim():"")||null;return r||a||l||u||e.model||h||null}function Ue({options:o={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||o.workspace,schema:o.schema||t.schema,images:o.images||t.images||[],skills:o.skills||t.skills||[],extraMcpServers:o.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:o.plugins||t.plugins||[]}}function Ge(o={}){let{state:e={},preferredAgent:t=null}=o,n=t||e.agentType||process.env.AGENT_TYPE;if(!n){let i=z.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}v.debug(`[workflow] agent selection: requested=${n}`);let s=z.find(i=>i.getName()===n);if(!s){let i=z.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${i}`)}if(!s.canHandle(o))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return v.debug(`[workflow] using agent: ${s.getName()}`),s}async function Nt(o,e={},t={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:n},i=Ge(s),r=n.config||t.config||{},a=n._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",u=!l||l===i.name?a.model:null,h=We({config:r,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:u}),d={...t,model:h,...Ue({options:t,stateView:n,context:e}),config:r},c=o,w=d.skills||[];if(w.length>0&&!t.skipPromptFragments){let $=t.connectedIntegrations;if(!$){let p=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof p=="string"&&p.trim()!==""){$={};for(let I of p.split(",").map(T=>T.trim()).filter(Boolean))$[I]=!0}}let b=p=>{let I=p&&p.requiresIntegration;return!I||!$?!0:(Array.isArray(I)?I:[I]).some(O=>$[O]===!0)},f=i.name==="assistant",m=p=>p?.inProcessOnly!==!0||f,S=w.map(p=>{let I=q(p);if(!b(I)||!m(I))return null;let T=I?.promptFragment;return typeof T=="function"?T():T}).filter(Boolean);S.length>0&&(c+=`
1
+ var wo=Object.defineProperty;var Ne=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var _e=(o,e,t)=>()=>{if(t)throw t[0];try{return o&&(e=o(o=0)),e}catch(n){throw t=[n],n}};var ut=(o,e)=>{for(var t in e)wo(o,t,{get:e[t],enumerable:!0})};function Eo(o){ce.impl={...ft,...o}}var pt,ft,ce,I,U=_e(()=>{pt=()=>{},ft={debug:pt,info:pt,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},ce={impl:ft};I={debug:(...o)=>ce.impl.debug?.(...o),info:(...o)=>ce.impl.info?.(...o),warn:(...o)=>ce.impl.warn?.(...o),error:(...o)=>ce.impl.error?.(...o)}});var Be,De=_e(()=>{Be=class{constructor(e,t,n=0){this.name=e,this.description=t,this.priority=n}async invoke(e,t={}){throw new Error(`${this.constructor.name}.invoke() must be implemented`)}canHandle(e){throw new Error(`${this.constructor.name}.canHandle() must be implemented`)}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var At={};ut(At,{clearSkills:()=>kt,getAllSkills:()=>$t,getSkill:()=>X,getSkillSource:()=>vt,hasSkill:()=>It,listSkillIds:()=>Tt,registerSkill:()=>bt});function bt(o,e={}){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:n=!1}=e,s=o.id;if(z.has(s)&&!n){let i=ue.get(s);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${s}" 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).`)}}z.set(s,Object.freeze({...o})),t===void 0?ue.delete(s):ue.set(s,t)}function X(o){return z.get(o)||null}function It(o){return z.has(o)}function vt(o){return ue.get(o)||null}function $t(){return new Map(z)}function Tt(){return Array.from(z.keys())}function kt(){z.clear(),ue.clear()}var Le,Fe,z,ue,pe=_e(()=>{Le=Symbol.for("@zibby/agent-workflow.skills"),Fe=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Le]||(globalThis[Le]=new Map);globalThis[Fe]||(globalThis[Fe]=new Map);z=globalThis[Le],ue=globalThis[Fe]});var fe={};ut(fe,{getAgentStrategy:()=>He,invokeAgent:()=>Ot,listStrategies:()=>Nt,registerStrategy:()=>xt,resolveInvocationExtras:()=>Ge,resolveInvocationModel:()=>Ue});function xt(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=J.findIndex(t=>t.getName()===o.getName());e>=0?J[e]=o:J.push(o)}function Nt(){return J.map(o=>o.getName())}function Ue({config:o={},options:e={},strategyName:t,envModel:n,nodeConfigModel:s}={}){let i=o.models||{},r=typeof s=="string"&&s.trim()&&s.trim()!=="auto"?s.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,u=o.agent?.[t]?.model||null,h=(typeof n=="string"?n.trim():"")||null;return r||a||l||u||e.model||h||null}function Ge({options:o={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||o.workspace,schema:o.schema||t.schema,images:o.images||t.images||[],skills:o.skills||t.skills||[],extraMcpServers:o.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:o.plugins||t.plugins||[]}}function He(o={}){let{state:e={},preferredAgent:t=null}=o,n=t||e.agentType||process.env.AGENT_TYPE;if(!n){let i=J.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}I.debug(`[workflow] agent selection: requested=${n}`);let s=J.find(i=>i.getName()===n);if(!s){let i=J.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${i}`)}if(!s.canHandle(o))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${s.getName()}`),s}async function Ot(o,e={},t={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:n},i=He(s),r=n.config||t.config||{},a=n._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",u=!l||l===i.name?a.model:null,h=Ue({config:r,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:u}),d={...t,model:h,...Ge({options:t,stateView:n,context:e}),config:r},c=o,w=d.skills||[];if(w.length>0&&!t.skipPromptFragments){let v=t.connectedIntegrations;if(!v){let p=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof p=="string"&&p.trim()!==""){v={};for(let _ of p.split(",").map(k=>k.trim()).filter(Boolean))v[_]=!0}}let b=p=>{let _=p&&p.requiresIntegration;return!_||!v?!0:(Array.isArray(_)?_:[_]).some(T=>v[T]===!0)},f=i.name==="assistant",m=p=>p?.inProcessOnly!==!0||f,$=w.map(p=>{let _=X(p);if(!b(_)||!m(_))return null;let k=_?.promptFragment;return typeof k=="function"?k():k}).filter(Boolean);$.length>0&&(c+=`
2
2
 
3
- ${S.join(`
3
+ ${$.join(`
4
4
 
5
- `)}`)}let g=n._currentNodeConfig?.stores;if(Array.isArray(g)&&g.length>0&&typeof g[0]=="object"){let $=g.length<=8,b=g.map(f=>{let m=f?.id??f?.storeId??"",S=(f?.name??"").toString().trim()||m,p=f?.type?` \xB7 ${f.type}`:"",I=(f?.description||"").toString().replace(/\s+/g," ").trim(),T=`- ${S} \xB7 ${I||"(no description)"}${p} (id: ${m})`;if($&&f?.schema&&typeof f.schema=="object"){let O=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);O.length&&(T+=`
6
- fields: ${O.join(", ")}`)}return T});c+=`
5
+ `)}`)}let g=n._currentNodeConfig?.stores;if(Array.isArray(g)&&g.length>0&&typeof g[0]=="object"){let v=g.length<=8,b=g.map(f=>{let m=f?.id??f?.storeId??"",$=(f?.name??"").toString().trim()||m,p=f?.type?` \xB7 ${f.type}`:"",_=(f?.description||"").toString().replace(/\s+/g," ").trim(),k=`- ${$} \xB7 ${_||"(no description)"}${p} (id: ${m})`;if(v&&f?.schema&&typeof f.schema=="object"){let T=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);T.length&&(k+=`
6
+ fields: ${T.join(", ")}`)}return k});c+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
9
9
  ${b.join(`
@@ -14,32 +14,32 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
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
16
  ${E}
17
- `),v.debug(`[workflow] prompt length: ${c.length} chars`),i.invoke(c,d)}var Fe,z,X=Se(()=>{Be();W();ue();Fe=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Fe]||(globalThis[Fe]=[]);z=globalThis[Fe]});var So=new Set(["__proto__","constructor","prototype"]);function Ne(o){if(So.has(o))throw new Error(`Invalid state key: "${o}"`)}var se=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){Ne(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let n of t)Ne(n);this._history.push({...this._state});for(let n of t)this._state[n]=e[n]}append(e,t){Ne(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 ie=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 n=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of n)try{return this.validate(JSON.parse(s))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[n,s]of Object.entries(this.schema)){if(s.required&&!(n in e)&&t.push(`Missing required field: ${n}`),n in e&&s.type){let i=typeof e[n];i!==s.type&&t.push(`Field '${n}' expected ${s.type}, got ${i}`)}if(s.validate&&n in e){let i=s.validate(e[n]);i&&t.push(`Field '${n}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
17
+ `),I.debug(`[workflow] prompt length: ${c.length} chars`),i.invoke(c,d)}var We,J,Q=_e(()=>{De();U();pe();We=Symbol.for("@zibby/agent-workflow.strategies");globalThis[We]||(globalThis[We]=[]);J=globalThis[We]});var So=new Set(["__proto__","constructor","prototype"]);function Oe(o){if(So.has(o))throw new Error(`Invalid state key: "${o}"`)}var ie=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){Oe(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let n of t)Oe(n);this._history.push({...this._state});for(let n of t)this._state[n]=e[n]}append(e,t){Oe(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 Y from"handlebars";var ae=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 n=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of n)try{return this.validate(JSON.parse(s))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[n,s]of Object.entries(this.schema)){if(s.required&&!(n in e)&&t.push(`Missing required field: ${n}`),n in e&&s.type){let i=typeof e[n];i!==s.type&&t.push(`Field '${n}' expected ${s.type}, got ${i}`)}if(s.validate&&n in e){let i=s.validate(e[n]);i&&t.push(`Field '${n}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
18
18
  ${t.join(`
19
- `)}`);return e}},_o={string:(o=!0)=>({type:"string",required:o}),number:(o=!0)=>({type:"number",required:o}),boolean:(o=!0)=>({type:"boolean",required:o}),array:(o=!0)=>({type:"object",required:o,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(o,e=!0)=>({type:"string",required:e,validate:t=>o.includes(t)?null:`must be one of: ${o.join(", ")}`})};W();import{writeFileSync as He,readFileSync as Ot,existsSync as Pt,mkdirSync as ko}from"node:fs";import{join as ze,dirname as Ao}from"node:path";import N from"chalk";var _t="__WORKFLOW_GRAPH_LOG__",ce=N.gray("\u2502"),bo=N.gray("\u250C"),ft=N.gray("\u2514"),Oe=N.green("\u25C6"),ht=N.hex("#c084fc")("\u25C6"),gt=N.hex("#2dd4bf")("\u25C6"),Pe=N.red("\u25C6"),mt=`${ce} `,yt=2;function wt(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function St(o,e){return(t,n,s)=>{if(typeof t!="string")return o(t,n,s);let i=process.stdout.columns||120,r="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(r+=mt,e.col=yt,e.lineStart=!1),l===`
19
+ `)}`);return e}},_o={string:(o=!0)=>({type:"string",required:o}),number:(o=!0)=>({type:"number",required:o}),boolean:(o=!0)=>({type:"boolean",required:o}),array:(o=!0)=>({type:"object",required:o,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(o,e=!0)=>({type:"string",required:e,validate:t=>o.includes(t)?null:`must be one of: ${o.join(", ")}`})};U();import{writeFileSync as ze,readFileSync as Pt,existsSync as Ct,mkdirSync as ko}from"node:fs";import{join as Je,dirname as Ao}from"node:path";import O from"chalk";var Et="__WORKFLOW_GRAPH_LOG__",le=O.gray("\u2502"),bo=O.gray("\u250C"),ht=O.gray("\u2514"),Pe=O.green("\u25C6"),gt=O.hex("#c084fc")("\u25C6"),mt=O.hex("#2dd4bf")("\u25C6"),Ce=O.red("\u25C6"),yt=`${le} `,wt=2;function St(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function _t(o,e){return(t,n,s)=>{if(typeof t!="string")return o(t,n,s);let i=process.stdout.columns||120,r="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(r+=yt,e.col=wt,e.lineStart=!1),l===`
20
20
  `?(r+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,r+=l):e.inEsc?(r+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,r+=l,e.col>=i&&(r+=`
21
- ${mt}`,e.col=yt))}return o(r,n,s)}}var _e=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=St(this._origStdoutWrite,e),process.stderr.write=St(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
21
+ ${yt}`,e.col=wt))}return o(r,n,s)}}var Ee=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=_t(this._origStdoutWrite,e),process.stderr.write=_t(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=`${_t}${JSON.stringify(e)}
24
+ `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Et}${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(Oe,e):process.stdout.write.bind(process.stdout)(`${ce} ${Oe} ${e}
29
- `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(ht,e):process.stdout.write.bind(process.stdout)(`${ce} ${ht} ${e}
30
- `)}stepMemory(e){let t=N.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(gt,t):process.stdout.write.bind(process.stdout)(`${ce} ${gt} ${t}
31
- `)}stepFail(e){this._origStdoutWrite?this._writeDot(Pe,N.red(e)):process.stdout.write.bind(process.stdout)(`${ce} ${Pe} ${N.red(e)}
32
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${bo} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:n,details:s}=t;if(s)for(let r of s)this._rawWrite(`${Oe} ${r}`);let i=n?N.dim(` ${wt(n)}`):"";this._rawWrite(`${ft} ${N.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,n={}){this._stopIntercepting();let{duration:s}=n,i=s?N.dim(` ${wt(s)}`):"";this._rawWrite(`${Pe} ${N.red(t)}`),this._rawWrite(`${ft} ${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(){}},x=new _e;var le=".zibby/output",Ce="sessions",G=".session-info.json",Re=".zibby-stop",Io="result.json",vo="raw_stream_output.txt",$o="events.json",To=Object.freeze(["codebase-memory","code-scan","artifact"]),je=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];J.helpers.inc||J.registerHelper("inc",o=>Number(o)+1);J.helpers.json||J.registerHelper("json",o=>JSON.stringify(o,null,2));J.helpers.eq||J.registerHelper("eq",(o,e)=>o===e);var F=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 ie(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 v.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let n=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=d=>t&&typeof t.get=="function"?t.get(d):e?.[d];if(typeof this.customExecute=="function"){v.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let d=await this.customExecute(e);return typeof d=="object"&&d!==null&&d.success===!1?{success:!1,error:d.error||"Node execution failed",raw:d.raw||null}:this.isZodSchema?(v.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(d),raw:null}):{success:!0,output:d,raw:null}}catch(d){return v.error(`[workflow] node '${this.name}' failed: ${d.message}`),d.name==="ZodError"&&v.error(`Schema errors: ${JSON.stringify(d.issues||d.errors,null,2)}`),{success:!1,error:d.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=J.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(n())):i=this.prompt;let r=s("_skillHints");r&&(i=`${r}
28
+ `)}step(e){this._origStdoutWrite?this._writeDot(Pe,e):process.stdout.write.bind(process.stdout)(`${le} ${Pe} ${e}
29
+ `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(gt,e):process.stdout.write.bind(process.stdout)(`${le} ${gt} ${e}
30
+ `)}stepMemory(e){let t=O.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(mt,t):process.stdout.write.bind(process.stdout)(`${le} ${mt} ${t}
31
+ `)}stepFail(e){this._origStdoutWrite?this._writeDot(Ce,O.red(e)):process.stdout.write.bind(process.stdout)(`${le} ${Ce} ${O.red(e)}
32
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${bo} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:n,details:s}=t;if(s)for(let r of s)this._rawWrite(`${Pe} ${r}`);let i=n?O.dim(` ${St(n)}`):"";this._rawWrite(`${ht} ${O.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,n={}){this._stopIntercepting();let{duration:s}=n,i=s?O.dim(` ${St(s)}`):"";this._rawWrite(`${Ce} ${O.red(t)}`),this._rawWrite(`${ht} ${O.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(O.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},N=new Ee;var de=".zibby/output",Re="sessions",H=".session-info.json",je=".zibby-stop",Io="result.json",vo="raw_stream_output.txt",$o="events.json",To=Object.freeze(["codebase-memory","code-scan","artifact"]),Me=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];Y.helpers.inc||Y.registerHelper("inc",o=>Number(o)+1);Y.helpers.json||Y.registerHelper("json",o=>JSON.stringify(o,null,2));Y.helpers.eq||Y.registerHelper("eq",(o,e)=>o===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 ae(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return I.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let n=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=d=>t&&typeof t.get=="function"?t.get(d):e?.[d];if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let d=await this.customExecute(e);return typeof d=="object"&&d!==null&&d.success===!1?{success:!1,error:d.error||"Node execution failed",raw:d.raw||null}:this.isZodSchema?(I.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(d),raw:null}):{success:!0,output:d,raw:null}}catch(d){return I.error(`[workflow] node '${this.name}' failed: ${d.message}`),d.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(d.issues||d.errors,null,2)}`),{success:!1,error:d.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=Y.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(n())):i=this.prompt;let r=s("_skillHints");r&&(i=`${r}
33
33
 
34
- ${i}`);let a=n(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let d=ze(u,G);if(Pt(d)){let w=JSON.parse(Ot(d,"utf-8"));w.currentNode=this.name,He(d,JSON.stringify(w,null,2),"utf-8")}let c=ze(u,"..",G);if(Pt(c))try{let w=JSON.parse(Ot(c,"utf-8"));w.currentNode=this.name,He(c,JSON.stringify(w,null,2),"utf-8")}catch{}}}catch(d){v.debug(`[workflow] could not update session info: ${d.message}`)}let h=null;for(let d=0;d<=this.retries;d++)try{v.debug(`[workflow] node '${this.name}' attempt ${d}`);let c=n().config||{},w=c.agents||{},g=this.config.agent??w[this.name]??null,E={state:n()};g&&(E.preferredAgent=g);let $={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:u,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},b=e?._coreInvokeAgent;b||(b=(await Promise.resolve().then(()=>(X(),pe))).invokeAgent);let f=await b(i,E,$),m,S;if(typeof f=="string"?(m=f,S=null):f.structured?(m=f.raw||JSON.stringify(f.structured,null,2),S=f.structured):(m=f.raw||JSON.stringify(f,null,2),S=f.extracted||null),u)try{let p=ze(u,this.name,"raw_stream_output.txt");ko(Ao(p),{recursive:!0}),He(p,typeof m=="string"?m:JSON.stringify(m),"utf-8")}catch(p){v.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&S){v.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(S,null,2)}`);let p=S;if(typeof this.onComplete=="function")try{p=await this.onComplete(n(),S)}catch(I){v.warn(`[workflow] onComplete hook failed: ${I.message}`)}return{success:!0,output:p,raw:m}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:m}),raw:m}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(m);return v.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),x.step("Output parsed"),{success:!0,output:p,raw:m}}return{success:!0,output:m,raw:m}}catch(c){h=c,d<this.retries&&v.info(`[workflow] node '${this.name}' failed, retrying (${d+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};W();W();import{mkdirSync as Oo,existsSync as Z,statSync as Ut,readdirSync as Gt,rmSync as Po}from"node:fs";import{spawn as Lt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as Co}from"node:url";import{AsyncLocalStorage as Ro}from"node:async_hooks";import{AsyncLocalStorage as xo}from"node:async_hooks";var fe=new xo;function Q(){let o=fe.getStore();return o||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 Ct(o,e){let t=fe.getStore()||Q(),n=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null,agent:o.agent!==void 0?o.agent:t.agent??null,signal:o.signal!==void 0?o.signal:t.signal??null});return fe.run(n,e)}function Rt(o,e,t){let n=fe.getStore()||Q(),s=Object.freeze({...n,agent:o??n.agent??null,signal:e??n.signal??null});return fe.run(s,t)}var Je=new Map,Ye=new Map,jt=new Map;function Mt(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Je.set(o,e),Ye.set(o,"ready"),jt.set(o,{...t,cachedAt:Date.now()})}function Bt(o,e){Ye.set(o,"failed"),jt.set(o,{error:e?.message||String(e),failedAt:Date.now()}),Je.delete(o)}function Dt(o){return Ye.get(o)==="ready"?Je.get(o):null}var Ee=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function jo(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var P=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"}},Ft=new Ro,Wt=Promise.resolve();async function Mo(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([r,a])=>typeof r=="string"&&r&&typeof a=="string"):[];if(t.length===0)return e();let n=Ft.getStore()===!0,s=null;if(!n){let r=Wt;Wt=new Promise(a=>{s=a}),await r}let i=new Map;try{for(let[r,a]of t)i.set(r,Object.prototype.hasOwnProperty.call(process.env,r)?process.env[r]:void 0),process.env[r]=a;return v.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await Ft.run(!0,e)}finally{for(let[r,a]of i)a===void 0?delete process.env[r]:process.env[r]=a;s&&s()}}function Bo(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,n=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!n||!s)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:s}}async function Do({apiBase:o,authToken:e,body:t}){let n;try{n=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(i){throw new P("network",`begin fetch failed: ${i.message}`)}let s=null;try{s=await n.json()}catch{}if(!n.ok){if(n.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(n.status===429){let i=s?.quotaInfo||{},r=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw r.code="SUBGRAPH_QUOTA_EXCEEDED",r.status=429,r.quotaInfo=i,r}if(n.status===400&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new P("begin-status",`begin returned ${n.status}`)}return s?.data||s}async function Y({apiBase:o,authToken:e,payload:t}){try{let n=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});n.ok||v.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){v.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function Lo(o,e){let t=U(e,".ready"),n=U(e,"graph.mjs");if(Z(t)&&Z(n))return;Oo(e,{recursive:!0});let s=U(e,".lock"),i=!1;try{let{openSync:r,closeSync:a}=await import("node:fs"),l=r(s,"wx");a(l),i=!0}catch(r){if(r.code!=="EEXIST")throw r}if(!i){let r=Date.now()+3e4;for(;Date.now()<r;){if(Z(t)&&Z(n))return;await new Promise(a=>setTimeout(a,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let h=Lt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),d=Lt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(d.stdin);let c,w,g=()=>{if(c!==void 0&&w!==void 0){if(c!==0)return u(new Error(`curl exited ${c}`));if(w!==0)return u(new Error(`tar exited ${w}`));l()}};h.on("close",E=>{c=E,g()}),d.on("close",E=>{w=E,g()}),h.on("error",u),d.on("error",u)});let{writeFileSync:r,unlinkSync:a}=await import("node:fs");r(t,"");try{a(s)}catch{}}catch(r){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new P("bundle-extract-failed",r.message)}}async function Fo(o){let e=U(o,"graph.mjs");if(!Z(e))throw new P("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(Co(e).href)}catch(s){throw new P("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let n=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!n)throw new P("entry-class-missing","no buildGraph() class export found");return n}async function Ht(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=Q(),n;try{n=Bo()}catch(p){throw p}v.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let s=await Do({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:r,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:h,bundleReady:d,nodeConfigs:c}=s,w=jo();if(r&&r!==w)throw await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new P("runtime-mismatch",`${w} vs ${r}`);if(!d||!a)throw await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new P("no-bundle","workflow bundle not built yet");let g=Dt(o);if(!g){let p=U(Ee,`${h}@${u||"0"}`);try{await Lo(a,p);try{Uo()}catch{}}catch(I){throw I.fallback&&await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:I.message,code:I.reason}}}),I}try{g=await Fo(p),Mt(o,g,{workflowUuid:h,version:u,runtimeTag:r,cacheDir:p})}catch(I){throw Bt(o,I),await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:I.message,code:I.reason||"IMPORT_FAILED"}}}),I.fallback?I:new P("import-failed",I.message)}}let E=Date.now(),$=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,b=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...b?{nodeConfigs:c}:{}},m,S;try{m=await Mo($,async()=>{let I=await(typeof g=="function"&&g.prototype?.buildGraph?new g:g).buildGraph();return Ct({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>I.run(e.parentAgent,f,{signal:e.signal}))}),S=m&&typeof m=="object"&&"state"in m?m.state:m}catch(p){throw await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-E}}),p}if(m&&typeof m=="object"&&m.stoppedExternally){await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",finalState:S,durationMs:Date.now()-E}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:S,durationMs:Date.now()-E}}),{finalState:S,executionId:i}}function Wo(o){let e=0,t=[o];for(;t.length;){let n=t.pop(),s;try{s=Ut(n)}catch{continue}if(s.isDirectory()){let i;try{i=Gt(n)}catch{continue}for(let r of i)t.push(U(n,r))}else e+=s.size}return e}function Uo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Z(Ee))return{evicted:0,freedBytes:0};let e=Gt(Ee),t=[],n=0;for(let a of e){let l=U(Ee,a),u;try{u=Ut(l)}catch{continue}let h=u.isDirectory()?Wo(l):u.size;n+=h,t.push({name:a,full:l,size:h,mtimeMs:u.mtimeMs})}if(n<=o)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(o*.7),i=0,r=0;for(let a of t){if(n-i<=s)break;if(!Z(U(a.full,".lock")))try{Po(a.full,{recursive:!0,force:!0}),i+=a.size,r+=1}catch(l){v.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return r>0&&v.info(`[sub-graph cache] evicted ${r} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:r,freedBytes:i,totalBytes:n-i}}catch(e){return v.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Go=2e3,Ho=600*1e3,zo=new Set(["completed","failed","canceled","timeout"]);function Jo(){let o=process.env.PROGRESS_API_URL;if(!o)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 o.replace(/\/executions\/?$/,"")}function Yo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Zo(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Vo(){return process.env.EXECUTION_ID||null}function zt(o,e){return e==null?o:typeof e=="function"?e(o):typeof e=="string"?e.split(".").reduce((t,n)=>t==null?t:t[n],o):o}async function Ze(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=Q();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=n)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{v.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:S}=await Ht(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=zt(S,e.output);return v.info(`[sub-graph] '${o}' completed in-process`),p}catch(S){if(S instanceof P||S?.fallback)v.info(`[sub-graph] in-process fallback for '${o}': ${S.reason||"unknown"} \u2014 using HTTP`);else throw S}let s=Jo(),i=Yo(),r=Zo(),a=Vo(),l=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(o)}/trigger`,u={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};v.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let h=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(u)});if(!h.ok){let S=null,p="";try{S=await h.json(),p=S?.error||S?.message||JSON.stringify(S)}catch{p=await h.text().catch(()=>"")}if(h.status===429){let T=S?.quotaInfo||{},O=new Error(`Sub-graph '${o}' blocked by execution quota (${T.used??"?"}/${T.limit??"?"} on plan ${T.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=o,O.quotaInfo=T,O}if(h.status===400){let T=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw T.code="SUBGRAPH_INVALID_INPUT",T.status=400,T.subgraph=o,T.validationErrors=S?.validationErrors||null,T.missing=S?.missing||null,T}let I=new Error(`Sub-graph '${o}' trigger rejected (${h.status}): ${p}`);throw I.code="SUBGRAPH_TRIGGER_FAILED",I.status=h.status,I.subgraph=o,I}let d=await h.json(),c=d?.data?.jobId||d?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(d).slice(0,200)}`);if(e.async)return v.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let w=Number.isFinite(e.timeoutMs)?e.timeoutMs:Ho,g=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Go,E=`${s}/executions/${encodeURIComponent(c)}`,$=Date.now()+w,b="accepted",f=0;for(;Date.now()<$;){await new Promise(T=>setTimeout(T,g)),f+=1;let S=await fetch(E,{headers:{Authorization:`Bearer ${r}`}});if(!S.ok){if(S.status>=500){v.warn(`[sub-graph] status poll for ${c} returned ${S.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${S.status}`)}let p=await S.json(),I=p?.data||p?.execution||p;if(b=I?.status||b,zo.has(b)){if(b!=="completed"){let te=new Error(`Sub-graph '${o}' (${c}) ended in status '${b}'`);throw te.subgraphJobId=c,te.subgraphStatus=b,te}let T=I?.finalState||I?.state||{},O=zt(T,e.output);return v.info(`[sub-graph] '${o}' (${c}) completed after ${f} polls`),O}}let m=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(w/1e3)}s (last status: ${b})`);throw m.subgraphJobId=c,m.subgraphStatus=b,m}import{existsSync as Jt,readFileSync as Ko}from"node:fs";import{join as Ve,dirname as Yt}from"node:path";var he=class{static async loadContext(e,t,n={}){let s={},i=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Yt(Ve(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let h=l.replace(/\.[^.]+$/,"").toLowerCase();s[h]=u}}}let r=n.discovery||{};for(let[a,l]of Object.entries(r))try{let u=Ve(t,l);Jt(u)&&(s[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(e,t,n){let s=[],i=t;for(;i.startsWith(n);){let r=Ve(i,e);if(Jt(r))try{s.unshift(await this.loadFile(r))}catch(l){console.warn(`[workflow] could not load ${e} from ${r}: ${l.message}`)}let a=Yt(i);if(a===i)break;i=a}return s.length===0?null:s.every(r=>typeof r=="string")?s.join(`
34
+ ${i}`);let a=n(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let d=Je(u,H);if(Ct(d)){let w=JSON.parse(Pt(d,"utf-8"));w.currentNode=this.name,ze(d,JSON.stringify(w,null,2),"utf-8")}let c=Je(u,"..",H);if(Ct(c))try{let w=JSON.parse(Pt(c,"utf-8"));w.currentNode=this.name,ze(c,JSON.stringify(w,null,2),"utf-8")}catch{}}}catch(d){I.debug(`[workflow] could not update session info: ${d.message}`)}let h=null;for(let d=0;d<=this.retries;d++)try{I.debug(`[workflow] node '${this.name}' attempt ${d}`);let c=n().config||{},w=c.agents||{},g=this.config.agent??w[this.name]??null,E={state:n()};g&&(E.preferredAgent=g);let v={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:u,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},b=e?._coreInvokeAgent;b||(b=(await Promise.resolve().then(()=>(Q(),fe))).invokeAgent);let f=await b(i,E,v),m,$;if(typeof f=="string"?(m=f,$=null):f.structured?(m=f.raw||JSON.stringify(f.structured,null,2),$=f.structured):(m=f.raw||JSON.stringify(f,null,2),$=f.extracted||null),u)try{let p=Je(u,this.name,"raw_stream_output.txt");ko(Ao(p),{recursive:!0}),ze(p,typeof m=="string"?m:JSON.stringify(m),"utf-8")}catch(p){I.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&$){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify($,null,2)}`);let p=$;if(typeof this.onComplete=="function")try{p=await this.onComplete(n(),$)}catch(_){I.warn(`[workflow] onComplete hook failed: ${_.message}`)}return{success:!0,output:p,raw:m}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:m}),raw:m}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(m);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),N.step("Output parsed"),{success:!0,output:p,raw:m}}return{success:!0,output:m,raw:m}}catch(c){h=c,d<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${d+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};U();U();import{mkdirSync as Oo,existsSync as V,statSync as Gt,readdirSync as Ht,rmSync as Po}from"node:fs";import{spawn as Ft}from"node:child_process";import{join as G}from"node:path";import{pathToFileURL as Co}from"node:url";import{AsyncLocalStorage as Ro}from"node:async_hooks";import{AsyncLocalStorage as xo}from"node:async_hooks";var he=new xo;function ee(){let o=he.getStore();return o||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 Rt(o,e){let t=he.getStore()||ee(),n=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null,agent:o.agent!==void 0?o.agent:t.agent??null,signal:o.signal!==void 0?o.signal:t.signal??null});return he.run(n,e)}function jt(o,e,t){let n=he.getStore()||ee(),s=Object.freeze({...n,agent:o??n.agent??null,signal:e??n.signal??null});return he.run(s,t)}var Ye=new Map,Ze=new Map,Mt=new Map;function Bt(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Ye.set(o,e),Ze.set(o,"ready"),Mt.set(o,{...t,cachedAt:Date.now()})}function Dt(o,e){Ze.set(o,"failed"),Mt.set(o,{error:e?.message||String(e),failedAt:Date.now()}),Ye.delete(o)}function Lt(o){return Ze.get(o)==="ready"?Ye.get(o):null}var be=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function jo(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var P=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"}},Wt=new Ro,Ut=Promise.resolve();async function Mo(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([r,a])=>typeof r=="string"&&r&&typeof a=="string"):[];if(t.length===0)return e();let n=Wt.getStore()===!0,s=null;if(!n){let r=Ut;Ut=new Promise(a=>{s=a}),await r}let i=new Map;try{for(let[r,a]of t)i.set(r,Object.prototype.hasOwnProperty.call(process.env,r)?process.env[r]:void 0),process.env[r]=a;return I.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await Wt.run(!0,e)}finally{for(let[r,a]of i)a===void 0?delete process.env[r]:process.env[r]=a;s&&s()}}function Bo(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,n=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!n||!s)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:s}}async function Do({apiBase:o,authToken:e,body:t}){let n;try{n=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(i){throw new P("network",`begin fetch failed: ${i.message}`)}let s=null;try{s=await n.json()}catch{}if(!n.ok){if(n.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(n.status===429){let i=s?.quotaInfo||{},r=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw r.code="SUBGRAPH_QUOTA_EXCEEDED",r.status=429,r.quotaInfo=i,r}if(n.status===400&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new P("begin-status",`begin returned ${n.status}`)}return s?.data||s}async function Z({apiBase:o,authToken:e,payload:t}){try{let n=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});n.ok||I.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){I.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function Lo(o,e){let t=G(e,".ready"),n=G(e,"graph.mjs");if(V(t)&&V(n))return;Oo(e,{recursive:!0});let s=G(e,".lock"),i=!1;try{let{openSync:r,closeSync:a}=await import("node:fs"),l=r(s,"wx");a(l),i=!0}catch(r){if(r.code!=="EEXIST")throw r}if(!i){let r=Date.now()+3e4;for(;Date.now()<r;){if(V(t)&&V(n))return;await new Promise(a=>setTimeout(a,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let h=Ft("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),d=Ft("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(d.stdin);let c,w,g=()=>{if(c!==void 0&&w!==void 0){if(c!==0)return u(new Error(`curl exited ${c}`));if(w!==0)return u(new Error(`tar exited ${w}`));l()}};h.on("close",E=>{c=E,g()}),d.on("close",E=>{w=E,g()}),h.on("error",u),d.on("error",u)});let{writeFileSync:r,unlinkSync:a}=await import("node:fs");r(t,"");try{a(s)}catch{}}catch(r){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new P("bundle-extract-failed",r.message)}}async function Fo(o){let e=G(o,"graph.mjs");if(!V(e))throw new P("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(Co(e).href)}catch(s){throw new P("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let n=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!n)throw new P("entry-class-missing","no buildGraph() class export found");return n}async function zt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=ee(),n;try{n=Bo()}catch(p){throw p}I.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let s=await Do({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:r,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:h,bundleReady:d,nodeConfigs:c}=s,w=jo();if(r&&r!==w)throw await Z({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new P("runtime-mismatch",`${w} vs ${r}`);if(!d||!a)throw await Z({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new P("no-bundle","workflow bundle not built yet");let g=Lt(o);if(!g){let p=G(be,`${h}@${u||"0"}`);try{await Lo(a,p);try{Uo()}catch{}}catch(_){throw _.fallback&&await Z({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason}}}),_}try{g=await Fo(p),Bt(o,g,{workflowUuid:h,version:u,runtimeTag:r,cacheDir:p})}catch(_){throw Dt(o,_),await Z({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason||"IMPORT_FAILED"}}}),_.fallback?_:new P("import-failed",_.message)}}let E=Date.now(),v=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,b=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...b?{nodeConfigs:c}:{}},m,$;try{m=await Mo(v,async()=>{let _=await(typeof g=="function"&&g.prototype?.buildGraph?new g:g).buildGraph();return Rt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>_.run(e.parentAgent,f,{signal:e.signal}))}),$=m&&typeof m=="object"&&"state"in m?m.state:m}catch(p){throw await Z({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-E}}),p}if(m&&typeof m=="object"&&m.stoppedExternally){await Z({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",finalState:$,durationMs:Date.now()-E}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await Z({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:$,durationMs:Date.now()-E}}),{finalState:$,executionId:i}}function Wo(o){let e=0,t=[o];for(;t.length;){let n=t.pop(),s;try{s=Gt(n)}catch{continue}if(s.isDirectory()){let i;try{i=Ht(n)}catch{continue}for(let r of i)t.push(G(n,r))}else e+=s.size}return e}function Uo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!V(be))return{evicted:0,freedBytes:0};let e=Ht(be),t=[],n=0;for(let a of e){let l=G(be,a),u;try{u=Gt(l)}catch{continue}let h=u.isDirectory()?Wo(l):u.size;n+=h,t.push({name:a,full:l,size:h,mtimeMs:u.mtimeMs})}if(n<=o)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(o*.7),i=0,r=0;for(let a of t){if(n-i<=s)break;if(!V(G(a.full,".lock")))try{Po(a.full,{recursive:!0,force:!0}),i+=a.size,r+=1}catch(l){I.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return r>0&&I.info(`[sub-graph cache] evicted ${r} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:r,freedBytes:i,totalBytes:n-i}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Go=2e3,Ho=600*1e3,zo=new Set(["completed","failed","canceled","timeout"]);function Jo(){let o=process.env.PROGRESS_API_URL;if(!o)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 o.replace(/\/executions\/?$/,"")}function Yo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Zo(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Vo(){return process.env.EXECUTION_ID||null}function Jt(o,e){return e==null?o:typeof e=="function"?e(o):typeof e=="string"?e.split(".").reduce((t,n)=>t==null?t:t[n],o):o}async function Ve(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=ee();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=n)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:p}=await zt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),_=Jt(p,e.output);return I.info(`[sub-graph] '${o}' completed in-process`),_}catch(p){if(p instanceof P||p?.fallback)I.info(`[sub-graph] in-process fallback for '${o}': ${p.reason||"unknown"} \u2014 using HTTP`);else throw p}let s=Jo(),i=Yo(),r=Zo(),a=Vo(),l=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(o)}/trigger`,u={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let h=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(u)});if(!h.ok){let p=null,_="";try{p=await h.json(),_=p?.error||p?.message||JSON.stringify(p)}catch{_=await h.text().catch(()=>"")}if(h.status===429){let T=p?.quotaInfo||{},D=new Error(`Sub-graph '${o}' blocked by execution quota (${T.used??"?"}/${T.limit??"?"} on plan ${T.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw D.code="SUBGRAPH_QUOTA_EXCEEDED",D.status=429,D.subgraph=o,D.quotaInfo=T,D}if(h.status===400){let T=new Error(`Sub-graph '${o}' rejected input: ${_}`);throw T.code="SUBGRAPH_INVALID_INPUT",T.status=400,T.subgraph=o,T.validationErrors=p?.validationErrors||null,T.missing=p?.missing||null,T}let k=new Error(`Sub-graph '${o}' trigger rejected (${h.status}): ${_}`);throw k.code="SUBGRAPH_TRIGGER_FAILED",k.status=h.status,k.subgraph=o,k}let d=await h.json(),c=d?.data?.jobId||d?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(d).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let w=Number.isFinite(e.timeoutMs)?e.timeoutMs:Ho,g=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Go,E=`${s}/executions/${encodeURIComponent(c)}`,v=Date.now()+w,b="accepted",f=0,m=null;for(;Date.now()<v;){await new Promise(T=>setTimeout(T,g)),f+=1;let p;try{p=await fetch(E,{headers:{Authorization:`Bearer ${r}`}})}catch(T){m=T?.message||String(T),I.warn(`[sub-graph] status poll for ${c} could not reach the API (${m}), will retry`);continue}if(!p.ok){if(p.status>=500){I.warn(`[sub-graph] status poll for ${c} returned ${p.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${p.status}`)}let _;try{_=await p.json()}catch(T){m=T?.message||String(T),I.warn(`[sub-graph] status poll for ${c} returned an unreadable body (${m}), will retry`);continue}let k=_?.data||_?.execution||_;if(b=k?.status||b,zo.has(b)){if(b!=="completed"){let oe=new Error(`Sub-graph '${o}' (${c}) ended in status '${b}'`);throw oe.subgraphJobId=c,oe.subgraphStatus=b,oe}let T=k?.finalState||k?.state||{},D=Jt(T,e.output);return I.info(`[sub-graph] '${o}' (${c}) completed after ${f} polls`),D}}let $=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(w/1e3)}s (last status: ${b})`+(m?`; the status API was unreachable on the last attempt (${m})`:""));throw $.subgraphJobId=c,$.subgraphStatus=b,m&&($.subgraphTransportError=m),$}import{existsSync as Yt,readFileSync as Ko}from"node:fs";import{join as Ke,dirname as Zt}from"node:path";var ge=class{static async loadContext(e,t,n={}){let s={},i=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Zt(Ke(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let h=l.replace(/\.[^.]+$/,"").toLowerCase();s[h]=u}}}let r=n.discovery||{};for(let[a,l]of Object.entries(r))try{let u=Ke(t,l);Yt(u)&&(s[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(e,t,n){let s=[],i=t;for(;i.startsWith(n);){let r=Ke(i,e);if(Yt(r))try{s.unshift(await this.loadFile(r))}catch(l){console.warn(`[workflow] could not load ${e} from ${r}: ${l.message}`)}let a=Zt(i);if(a===i)break;i=a}return s.length===0?null:s.every(r=>typeof r=="string")?s.join(`
35
35
 
36
36
  ---
37
37
 
38
- `):s.every(r=>typeof r=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=Ko(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:n}=await import("url"),s=await import(n(e).href);return s.default||s}return t}};import{mkdirSync as Kt,existsSync as Ke,writeFileSync as Zt,unlinkSync as qo}from"node:fs";import{join as V,resolve as qt}from"node:path";import{config as Xo}from"dotenv";import{zodToJsonSchema as Vt}from"zod-to-json-schema";import{z as be}from"zod";import Qo from"handlebars";function en({traceFrom:o,sessionId:e,sessionPath:t,idSource:n,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let r=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${o} pid=${process.pid} ppid=${r} sessionId=${e} source=${n} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let h=(new Error("session trace").stack||"").split(`
38
+ `):s.every(r=>typeof r=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=Ko(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:n}=await import("url"),s=await import(n(e).href);return s.default||s}return t}};import{mkdirSync as qt,existsSync as qe,writeFileSync as Vt,unlinkSync as qo}from"node:fs";import{join as K,resolve as Xt}from"node:path";import{config as Xo}from"dotenv";import{zodToJsonSchema as Kt}from"zod-to-json-schema";import{z as Ie}from"zod";import Qo from"handlebars";function en({traceFrom:o,sessionId:e,sessionPath:t,idSource:n,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let r=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${o} pid=${process.pid} ppid=${r} sessionId=${e} source=${n} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let h=(new Error("session trace").stack||"").split(`
39
39
  `).slice(2,14).join(`
40
40
  `);console.log(`[zibby:session] stack (${o}):
41
- ${h}`)}}function Xt(){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 Qt(){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 qt(String(e).trim())}catch{return String(e).trim()}}function eo(){Xt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function to({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function oo(o={}){let e=je.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,s=o.paths?.sessionPrefix;return s?`${s}_${n}`:n}function no({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,r="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=qt(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,r="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).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,r="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,r="config.sessionId"):(a=oo(e),r="generated")}i=i??Date.now();let h=e.paths?.output||le;s=V(o,h,Ce,a)}let l=!Ke(s);return l&&Kt(s,{recursive:!0}),(l||r!=="initialState.sessionPath")&&en({traceFrom:n,sessionId:a,sessionPath:s,idSource:r,mkdirFresh:l}),to({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var ee=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,n={}){if(!(t instanceof F)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let r=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:r.workflow,retries:r.retries,onComplete:r.onComplete,execute:async u=>{let h=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof r.input=="function"?d=r.input(h):r.input&&typeof r.input=="object"?d=r.input:d={},Ze(r.workflow,{input:d,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(h):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:h?._signal,parentAgent:u?.agent})}},l=new F(a);return l.name=e,this.nodes.set(e,l),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let s=!(t instanceof F)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof F?t:new F(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){let n=this.edges.get(e);return n===void 0?this.edges.set(e,t):typeof n=="string"?n!==t&&this.edges.set(e,[n,t]):Array.isArray(n)?n.includes(t)||n.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:n}={}){let s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:n}),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,n=i=>{t.set(i,1);for(let r of this._simpleTargets(i)){if(!r||r==="END")continue;let a=t.get(r)||0;a===1?e.add(`${i}->${r}`):a===0&&n(r)}t.set(i,2)};this.entryPoint&&n(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let r of this._simpleTargets(i))!r||r==="END"||e.has(`${i}->${r}`)||s.set(r,(s.get(r)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,s,i){let r=n;for(let a=e.length-1;a>=0;a--){let l=e[a],u=r;r=()=>l(t,u,s,i)}return r()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let w=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:w,data:{nodeType:w,label:d}});let g={};c._isCustomCode&&typeof c.execute=="function"&&(g.customCode=c.execute.toString());let E=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;E&&(g.description=E);let $=this.nodePrompts.get(d);if($)g.prompt=$;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(g.prompt=p,g.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(g.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(g.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(g.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof be?.toJSONSchema=="function")try{p=be.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Vt(c.outputSchema,{target:"openApi3"})}catch{}g.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else g.outputSchema={schema:c.outputSchema};let b=(this.resolvedToolsMap||{})[d];b?.toolIds&&(g.tools=b.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(g.skills=[...f]);let m=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;m&&m.length>0&&(g.plugins=m.map(p=>p&&typeof p=="object"?{...p}:p));let S=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;S&&S.length>0&&(g.stores=S.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(g).length>0&&(t[d]=g)}let n=[];for(let[d,c]of this.edges)if(typeof c=="string")n.push({source:d,target:c});else if(Array.isArray(c))for(let w of c)n.push({source:d,target:w});else if(c.conditional){let w=this.conditionalCodeMap.get(d)||c.routes.toString(),g=this._inferConditionalTargets(c.routes,c.labels),E=c.labels||{},$=this.nodes.get(d),b=$?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!$,f=d;if(!b){let m=`${d}__branch`;e.push({id:m,type:"decision",data:{nodeType:"decision",label:m}}),n.push({source:d,target:m}),f=m}for(let m of g){let S={source:f,target:m,data:{conditionalCode:w}};E[m]&&(S.label=E[m]),n.push(S)}}let s=d=>{if(!d)return null;if(typeof be?.toJSONSchema=="function")try{return be.toJSONSchema(d)}catch{}try{return Vt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of n)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"}}),n.push({source:d,target:c})}let r=this._topoOrderNodes(e,n),a=this._runtimeSchema(),l=s(a||this.stateSchema),u=s(this.inputSchema),h=s(this.contextSchema);return{nodes:r,edges:n,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:h}}_topoOrderNodes(e,t){let n=new Map(e.map((d,c)=>[d.id,c])),s=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),r=new Map(e.map(d=>[d.id,[]]));for(let d of t)r.has(d.source)&&i.has(d.target)&&(r.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(n.keys()),u=[...l].filter(d=>i.get(d)===0),h=[];for(;h.length<e.length;){let d;if(u.length>0){if(u.sort((c,w)=>n.get(c)-n.get(w)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,w)=>n.get(c)-n.get(w))[0];a.add(d),l.delete(d),h.push(s.get(d));for(let c of r.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return h}_inferConditionalTargets(e,t){let n=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,r;for(;(r=i.exec(n))!==null;){let u=r[2]!==void 0?r[2]:r[3];u!==void 0&&u!==""&&s.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 s)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=u.exec(n))!==null;)l.add(h[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");n=e.definitions[s]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],s=e.properties||{},i=e.required||[];for(let[r,a]of Object.entries(s)){let l=t?`${t}.${r}`:r;n.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!i.includes(r)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${l}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${s}: ${i}`);else if(Array.isArray(i)){let r=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);n.push(l?`${s}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${s}: ${r} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){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(_){let y=new Error(`agent.normalizeInput() rejected the trigger input: ${_?.message||_}`);throw y.cause=_,y.code=_?.code||"NORMALIZE_INPUT_FAILED",y}let s=new AbortController;n.signal&&(n.signal.aborted?s.abort():n.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();Xo({path:V(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let _=V(r,".zibby.config.js");Ke(_)&&(a=(await import(_)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let _=a?.agent;_?.provider?l=_.provider:_?.gemini?l="gemini":_?.claude?l="claude":_?.cursor?l="cursor":_?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},h=this._runtimeSchema();if(h){let _=h.safeParse(t);if(!_.success){let y=_.error.issues.map(j=>`${j.path.join(".")}: ${j.message}`);throw console.error("\u274C Initial state validation failed:"),y.forEach(j=>console.error(` - ${j}`)),new Error(`State validation failed: ${y.join(", ")}`)}x.step("State validated against schema")}let d=Qt(),c=t.sessionPath||d;c||eo();let{sessionPath:w,sessionTimestamp:g,sessionId:E}=no({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});x.step(`Session ${E}`);let $=await he.loadContext(t.specPath||"",r,u);Object.keys($).length>0&&x.step(`Context loaded: ${Object.keys($).join(", ")}`);let b=t.outputPath;!b&&t.specPath&&(e?.calculateOutputPath?b=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new se({...t,config:a,agentType:l,outputPath:b,sessionPath:w,sessionTimestamp:g,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),m=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:S}=await Promise.resolve().then(()=>(ue(),kt)),p=a.skills&&typeof a.skills=="object"?a.skills:{},I=Object.values(p).filter(_=>_&&typeof _=="object"&&typeof _.id=="string"),T=_=>{for(let y of I)if(y.id===_)return y;return S(_)},O=new Set;for(let[,_]of this.nodes)for(let y of _.config?.skills||[])O.add(y);for(let _ of O){let y=T(_);if(typeof y?.middleware=="function")try{let j=await y.middleware();typeof j=="function"&&m.set(_,j)}catch{}}let{backEdges:te,joinDegree:ao}=this._analyzeFlow(),Te=new Map,oe=[],ke=(_,y,j)=>{if(!_||_==="END")return;let D=ao.get(_)||0;if(j&&D>1&&!te.has(`${y}->${_}`)){let ne=(Te.get(_)||0)+1;if(ne<D){Te.set(_,ne);return}Te.set(_,0)}oe.includes(_)||oe.push(_)};this.entryPoint&&oe.push(this.entryPoint);let me=[],nt=a?.recursionLimit??100,co=0;try{for(;oe.length>0;){let y=oe.pop();if(!y||y==="END")continue;if(++co>nt)throw new Error(`Workflow exceeded recursion limit (${nt}) \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 j=V(w,Re);if(Ke(j)){try{qo(j)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
42
- \u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:me,stoppedExternally:!0};let D=this.nodes.get(y);if(!D)throw new Error(`Node '${y}' not found in graph`);let ne=JSON.stringify({sessionPath:w,sessionTimestamp:g,currentNode:y,createdAt:new Date().toISOString(),config:f.get("config")}),lo=V(w,G);Zt(lo,ne,"utf-8");let rt=f.get("config")?.paths?.output||le,uo=V(r,rt,G);Kt(V(r,rt),{recursive:!0});try{Zt(uo,ne,"utf-8")}catch{}let st=t.onPipelineProgress;if(typeof st=="function")try{st({cwd:r,sessionPath:w,sessionId:E,outputBase:f.get("config")?.paths?.output||le,currentNode:y})}catch{}let po=(this.resolvedToolsMap||{})[y]||null;f.set("_currentNodeTools",po);let fo=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",fo[y]||{}),x.nodeStart(y);let it=Date.now(),ye=this.nodePrompts.get(y);if(!this._invokeAgent){let A=await Promise.resolve().then(()=>(X(),pe));this._invokeAgent=A.invokeAgent}let ho=this._invokeAgent,Ae={},go=D.config?.skills||[];for(let A of go){let C=T(A);if(typeof C?.invokeAgentOptions=="function")try{let k=C.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:y});k&&typeof k=="object"&&(Ae={...Ae,...k})}catch(k){console.warn(`[graph] skill '${A}' invokeAgentOptions threw: ${k.message}`)}}let at=async(A,C,k={})=>{let M=ho(A,C,{...Ae,...k,signal:s.signal});return M.catch(()=>{}),s.signal.aborted?M:Promise.race([M,new Promise((K,L)=>{let R=()=>{setTimeout(()=>{let re=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);re.name="AbortError",L(re)},i)};s.signal.addEventListener("abort",R,{once:!0})})])},mo=async(A={},C={})=>{let k=C.prompt||"";if(ye){let M=this._compiledPrompts.get(y);M||(M=Qo.compile(ye,{noEscape:!0}),this._compiledPrompts.set(y,M));try{k=M(A)}catch(K){throw console.error(`\u274C Template rendering failed for node '${y}':`,K.message),new Error(`Template rendering failed: ${K.message}`,{cause:K})}}else if(!k)throw new Error(`No prompt template configured for node '${y}' and no prompt provided in options`);return at(k,{state:f.getAll(),images:C.images||[]},{model:C.model||f.get("model"),workspace:f.get("workspace"),schema:C.schema,...C,signal:s.signal})},ct=f.getAll(),yo=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let A of yo)Object.prototype.hasOwnProperty.call(ct,A)&&console.warn(`[workflow] node "${y}": state key "${A}" is shadowed by the engine context prop; read it via context.state.get('${A}')`);let lt={...ct,state:f,invokeAgent:mo,_coreInvokeAgent:at,agent:e,nodeId:y,promptTemplate:ye,getPromptTemplate:()=>ye};try{let A=(D.config?.skills||[]).map(R=>m.get(R)).filter(Boolean),C=[...this.middleware,...A],k;k=await Rt(e,s.signal,async()=>C.length>0?this._composeMiddleware(C,y,async()=>D.execute(lt,f),f.getAll(),f):D.execute(lt,f));let M=Date.now()-it;if(me.push({node:y,success:k.success,duration:M,timestamp:new Date().toISOString()}),!k.success){if(s.signal.aborted)return x.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:me,stoppedExternally:!0};f.append("errors",{node:y,error:k.error});let R=D.config?.retries||0,re=`${y}_retries`,we=f.getAll()[re]||0;if(we<R){x.stepInfo(`Retrying (attempt ${we+1}/${R})`),f.update({[re]:we+1,[`${y}_raw`]:k.raw});continue}throw x.nodeFailed(y,k.error,{duration:M}),new Error(`Node '${y}' failed after ${we} attempts: ${k.error}`)}f.update({[y]:k.output});let K=this._summarizeNodeOutput(y,k.output);x.nodeComplete(y,{duration:M,details:K});let L=this.edges.get(y);if(L)if(L.conditional){let R=L.routes(f.getAll());x.route(y,R),ke(R,y,!1)}else if(Array.isArray(L))for(let R=L.length-1;R>=0;R--)ke(L[R],y,!0);else ke(L,y,!0)}catch(A){throw x.isInsideNode&&x.nodeFailed(y,A.message,{duration:Date.now()-it}),f.set("failed",!0),f.set("failedAt",y),A}}x.graphComplete();let _={success:!0,state:f.getAll(),executionLog:me};return e&&typeof e.onComplete=="function"&&await e.onComplete(_),_}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(_){console.warn(`[workflow] agent.cleanup() failed: ${_.message}`)}}}};var qe=Symbol.for("@zibby/agent-workflow.nodes");globalThis[qe]||(globalThis[qe]=new Map);var ge=globalThis[qe];function ro(o,e){ge.set(o,e)}function Xe(o){return ge.get(o)}function Ie(o){return ge.has(o)}function tn(){return Array.from(ge.keys())}function Qe(o){let e=ge.get(o);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}ro("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let n=t?._coreInvokeAgent;n||(n=(await Promise.resolve().then(()=>(X(),pe))).invokeAgent);let s=e.extraPromptInstructions||"Execute the task based on the current state.",i=on(s,t),r=await n(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:r,nodeId:o},raw:typeof r=="string"?r:r.raw}}})});function on(o,e){let t=/@([\w.]+)/g,n=new Set,s;for(;(s=t.exec(o))!==null;)n.add(s[1]);if(n.size===0)return o;let i=[],r=new Set;for(let a of n){let l=a.split(".")[0];if(r.has(l))continue;let u=a.split(".").reduce((c,w)=>c?.[w],e);if(u===void 0)continue;let h=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}
41
+ ${h}`)}}function Qt(){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 eo(){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 Xt(String(e).trim())}catch{return String(e).trim()}}function to(){Qt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function oo({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function no(o={}){let e=Me.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,s=o.paths?.sessionPrefix;return s?`${s}_${n}`:n}function ro({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,r="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=Xt(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,r="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).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,r="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,r="config.sessionId"):(a=no(e),r="generated")}i=i??Date.now();let h=e.paths?.output||de;s=K(o,h,Re,a)}let l=!qe(s);return l&&qt(s,{recursive:!0}),(l||r!=="initialState.sessionPath")&&en({traceFrom:n,sessionId:a,sessionPath:s,idSource:r,mkdirFresh:l}),oo({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var te=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,n={}){if(!(t instanceof W)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let r=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:r.workflow,retries:r.retries,onComplete:r.onComplete,execute:async u=>{let h=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof r.input=="function"?d=r.input(h):r.input&&typeof r.input=="object"?d=r.input:d={},Ve(r.workflow,{input:d,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(h):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:h?._signal,parentAgent:u?.agent})}},l=new W(a);return l.name=e,this.nodes.set(e,l),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let s=!(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(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){let n=this.edges.get(e);return n===void 0?this.edges.set(e,t):typeof n=="string"?n!==t&&this.edges.set(e,[n,t]):Array.isArray(n)?n.includes(t)||n.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:n}={}){let s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:n}),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,n=i=>{t.set(i,1);for(let r of this._simpleTargets(i)){if(!r||r==="END")continue;let a=t.get(r)||0;a===1?e.add(`${i}->${r}`):a===0&&n(r)}t.set(i,2)};this.entryPoint&&n(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let r of this._simpleTargets(i))!r||r==="END"||e.has(`${i}->${r}`)||s.set(r,(s.get(r)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,s,i){let r=n;for(let a=e.length-1;a>=0;a--){let l=e[a],u=r;r=()=>l(t,u,s,i)}return r()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let w=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:w,data:{nodeType:w,label:d}});let g={};c._isCustomCode&&typeof c.execute=="function"&&(g.customCode=c.execute.toString());let E=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;E&&(g.description=E);let v=this.nodePrompts.get(d);if(v)g.prompt=v;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(g.prompt=p,g.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(g.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(g.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(g.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof Ie?.toJSONSchema=="function")try{p=Ie.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Kt(c.outputSchema,{target:"openApi3"})}catch{}g.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else g.outputSchema={schema:c.outputSchema};let b=(this.resolvedToolsMap||{})[d];b?.toolIds&&(g.tools=b.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(g.skills=[...f]);let m=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;m&&m.length>0&&(g.plugins=m.map(p=>p&&typeof p=="object"?{...p}:p));let $=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;$&&$.length>0&&(g.stores=$.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(g).length>0&&(t[d]=g)}let n=[];for(let[d,c]of this.edges)if(typeof c=="string")n.push({source:d,target:c});else if(Array.isArray(c))for(let w of c)n.push({source:d,target:w});else if(c.conditional){let w=this.conditionalCodeMap.get(d)||c.routes.toString(),g=this._inferConditionalTargets(c.routes,c.labels),E=c.labels||{},v=this.nodes.get(d),b=v?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!v,f=d;if(!b){let m=`${d}__branch`;e.push({id:m,type:"decision",data:{nodeType:"decision",label:m}}),n.push({source:d,target:m}),f=m}for(let m of g){let $={source:f,target:m,data:{conditionalCode:w}};E[m]&&($.label=E[m]),n.push($)}}let s=d=>{if(!d)return null;if(typeof Ie?.toJSONSchema=="function")try{return Ie.toJSONSchema(d)}catch{}try{return Kt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of n)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"}}),n.push({source:d,target:c})}let r=this._topoOrderNodes(e,n),a=this._runtimeSchema(),l=s(a||this.stateSchema),u=s(this.inputSchema),h=s(this.contextSchema);return{nodes:r,edges:n,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:h}}_topoOrderNodes(e,t){let n=new Map(e.map((d,c)=>[d.id,c])),s=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),r=new Map(e.map(d=>[d.id,[]]));for(let d of t)r.has(d.source)&&i.has(d.target)&&(r.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(n.keys()),u=[...l].filter(d=>i.get(d)===0),h=[];for(;h.length<e.length;){let d;if(u.length>0){if(u.sort((c,w)=>n.get(c)-n.get(w)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,w)=>n.get(c)-n.get(w))[0];a.add(d),l.delete(d),h.push(s.get(d));for(let c of r.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return h}_inferConditionalTargets(e,t){let n=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,r;for(;(r=i.exec(n))!==null;){let u=r[2]!==void 0?r[2]:r[3];u!==void 0&&u!==""&&s.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 s)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=u.exec(n))!==null;)l.add(h[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");n=e.definitions[s]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],s=e.properties||{},i=e.required||[];for(let[r,a]of Object.entries(s)){let l=t?`${t}.${r}`:r;n.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!i.includes(r)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${l}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${s}: ${i}`);else if(Array.isArray(i)){let r=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);n.push(l?`${s}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${s}: ${r} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(S){let y=new Error(`agent.normalizeInput() rejected the trigger input: ${S?.message||S}`);throw y.cause=S,y.code=S?.code||"NORMALIZE_INPUT_FAILED",y}let s=new AbortController;n.signal&&(n.signal.aborted?s.abort():n.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();Xo({path:K(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let S=K(r,".zibby.config.js");qe(S)&&(a=(await import(S)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let S=a?.agent;S?.provider?l=S.provider:S?.gemini?l="gemini":S?.claude?l="claude":S?.cursor?l="cursor":S?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},h=this._runtimeSchema();if(h){let S=h.safeParse(t);if(!S.success){let y=S.error.issues.map(j=>`${j.path.join(".")}: ${j.message}`);throw console.error("\u274C Initial state validation failed:"),y.forEach(j=>console.error(` - ${j}`)),new Error(`State validation failed: ${y.join(", ")}`)}N.step("State validated against schema")}let d=eo(),c=t.sessionPath||d;c||to();let{sessionPath:w,sessionTimestamp:g,sessionId:E}=ro({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});N.step(`Session ${E}`);let v=await ge.loadContext(t.specPath||"",r,u);Object.keys(v).length>0&&N.step(`Context loaded: ${Object.keys(v).join(", ")}`);let b=t.outputPath;!b&&t.specPath&&(e?.calculateOutputPath?b=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ie({...t,config:a,agentType:l,outputPath:b,sessionPath:w,sessionTimestamp:g,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),m=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:$}=await Promise.resolve().then(()=>(pe(),At)),p=a.skills&&typeof a.skills=="object"?a.skills:{},_=Object.values(p).filter(S=>S&&typeof S=="object"&&typeof S.id=="string"),k=S=>{for(let y of _)if(y.id===S)return y;return $(S)},T=new Set;for(let[,S]of this.nodes)for(let y of S.config?.skills||[])T.add(y);for(let S of T){let y=k(S);if(typeof y?.middleware=="function")try{let j=await y.middleware();typeof j=="function"&&m.set(S,j)}catch{}}let{backEdges:D,joinDegree:oe}=this._analyzeFlow(),ke=new Map,ne=[],Ae=(S,y,j)=>{if(!S||S==="END")return;let L=oe.get(S)||0;if(j&&L>1&&!D.has(`${y}->${S}`)){let re=(ke.get(S)||0)+1;if(re<L){ke.set(S,re);return}ke.set(S,0)}ne.includes(S)||ne.push(S)};this.entryPoint&&ne.push(this.entryPoint);let ye=[],rt=a?.recursionLimit??100,co=0;try{for(;ne.length>0;){let y=ne.pop();if(!y||y==="END")continue;if(++co>rt)throw new Error(`Workflow exceeded recursion limit (${rt}) \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 j=K(w,je);if(qe(j)){try{qo(j)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
42
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),N.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ye,stoppedExternally:!0};let L=this.nodes.get(y);if(!L)throw new Error(`Node '${y}' not found in graph`);let re=JSON.stringify({sessionPath:w,sessionTimestamp:g,currentNode:y,createdAt:new Date().toISOString(),config:f.get("config")}),lo=K(w,H);Vt(lo,re,"utf-8");let st=f.get("config")?.paths?.output||de,uo=K(r,st,H);qt(K(r,st),{recursive:!0});try{Vt(uo,re,"utf-8")}catch{}let it=t.onPipelineProgress;if(typeof it=="function")try{it({cwd:r,sessionPath:w,sessionId:E,outputBase:f.get("config")?.paths?.output||de,currentNode:y})}catch{}let po=(this.resolvedToolsMap||{})[y]||null;f.set("_currentNodeTools",po);let fo=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",fo[y]||{}),N.nodeStart(y);let at=Date.now(),we=this.nodePrompts.get(y);if(!this._invokeAgent){let x=await Promise.resolve().then(()=>(Q(),fe));this._invokeAgent=x.invokeAgent}let ho=this._invokeAgent,xe={},go=L.config?.skills||[];for(let x of go){let C=k(x);if(typeof C?.invokeAgentOptions=="function")try{let A=C.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:y});A&&typeof A=="object"&&(xe={...xe,...A})}catch(A){console.warn(`[graph] skill '${x}' invokeAgentOptions threw: ${A.message}`)}}let ct=async(x,C,A={})=>{let M=ho(x,C,{...xe,...A,signal:s.signal});return M.catch(()=>{}),s.signal.aborted?M:Promise.race([M,new Promise((q,F)=>{let R=()=>{setTimeout(()=>{let se=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);se.name="AbortError",F(se)},i)};s.signal.addEventListener("abort",R,{once:!0})})])},mo=async(x={},C={})=>{let A=C.prompt||"";if(we){let M=this._compiledPrompts.get(y);M||(M=Qo.compile(we,{noEscape:!0}),this._compiledPrompts.set(y,M));try{A=M(x)}catch(q){throw console.error(`\u274C Template rendering failed for node '${y}':`,q.message),new Error(`Template rendering failed: ${q.message}`,{cause:q})}}else if(!A)throw new Error(`No prompt template configured for node '${y}' and no prompt provided in options`);return ct(A,{state:f.getAll(),images:C.images||[]},{model:C.model||f.get("model"),workspace:f.get("workspace"),schema:C.schema,...C,signal:s.signal})},lt=f.getAll(),yo=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let x of yo)Object.prototype.hasOwnProperty.call(lt,x)&&console.warn(`[workflow] node "${y}": state key "${x}" is shadowed by the engine context prop; read it via context.state.get('${x}')`);let dt={...lt,state:f,invokeAgent:mo,_coreInvokeAgent:ct,agent:e,nodeId:y,promptTemplate:we,getPromptTemplate:()=>we};try{let x=(L.config?.skills||[]).map(R=>m.get(R)).filter(Boolean),C=[...this.middleware,...x],A;A=await jt(e,s.signal,async()=>C.length>0?this._composeMiddleware(C,y,async()=>L.execute(dt,f),f.getAll(),f):L.execute(dt,f));let M=Date.now()-at;if(ye.push({node:y,success:A.success,duration:M,timestamp:new Date().toISOString()}),!A.success){if(s.signal.aborted)return N.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ye,stoppedExternally:!0};f.append("errors",{node:y,error:A.error});let R=L.config?.retries||0,se=`${y}_retries`,Se=f.getAll()[se]||0;if(Se<R){N.stepInfo(`Retrying (attempt ${Se+1}/${R})`),f.update({[se]:Se+1,[`${y}_raw`]:A.raw});continue}throw N.nodeFailed(y,A.error,{duration:M}),new Error(`Node '${y}' failed after ${Se} attempts: ${A.error}`)}f.update({[y]:A.output});let q=this._summarizeNodeOutput(y,A.output);N.nodeComplete(y,{duration:M,details:q});let F=this.edges.get(y);if(F)if(F.conditional){let R=F.routes(f.getAll());N.route(y,R),Ae(R,y,!1)}else if(Array.isArray(F))for(let R=F.length-1;R>=0;R--)Ae(F[R],y,!0);else Ae(F,y,!0)}catch(x){throw N.isInsideNode&&N.nodeFailed(y,x.message,{duration:Date.now()-at}),f.set("failed",!0),f.set("failedAt",y),x}}N.graphComplete();let S={success:!0,state:f.getAll(),executionLog:ye};return e&&typeof e.onComplete=="function"&&await e.onComplete(S),S}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(S){console.warn(`[workflow] agent.cleanup() failed: ${S.message}`)}}}};var Xe=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Xe]||(globalThis[Xe]=new Map);var me=globalThis[Xe];function so(o,e){me.set(o,e)}function Qe(o){return me.get(o)}function ve(o){return me.has(o)}function tn(){return Array.from(me.keys())}function et(o){let e=me.get(o);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}so("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let n=t?._coreInvokeAgent;n||(n=(await Promise.resolve().then(()=>(Q(),fe))).invokeAgent);let s=e.extraPromptInstructions||"Execute the task based on the current state.",i=on(s,t),r=await n(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:r,nodeId:o},raw:typeof r=="string"?r:r.raw}}})});function on(o,e){let t=/@([\w.]+)/g,n=new Set,s;for(;(s=t.exec(o))!==null;)n.add(s[1]);if(n.size===0)return o;let i=[],r=new Set;for(let a of n){let l=a.split(".")[0];if(r.has(l))continue;let u=a.split(".").reduce((c,w)=>c?.[w],e);if(u===void 0)continue;let h=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
43
  ${h}`),a.includes(".")||r.add(l)}return i.length===0?o:`${o}
44
44
 
45
45
  ---
@@ -47,16 +47,16 @@ ${h}`),a.includes(".")||r.add(l)}return i.length===0?o:`${o}
47
47
 
48
48
  ${i.join(`
49
49
 
50
- `)}`}ue();W();var ve={};function tt(o,e){if(Array.isArray(e))return et(e);let t=ve[o];return!t||t.length===0?null:et(t)}function et(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},n=[];for(let s of o){let i=q(s);if(!i){v.warn(`[workflow] unknown skill "${s}" \u2014 skipping`);continue}n.push(s);for(let r of i.tools||[])e.push({name:r.name,description:r.description,input_schema:r.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let r=i.resolve();r&&(t[i.serverName]={...r,toolPrefix:s})}else{let r={};for(let a of i.envKeys||[]){let l=process.env[a];l&&(r[a]=l)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:r,toolPrefix:s}}}return n.length===0?null:{toolIds:n,claudeTools:e,mcpServers:t}}W();function nn(o,e={}){let{nodes:t,edges:n,nodeConfigs:s={}}=o;if(!Array.isArray(t)||t.length===0)throw new B("Graph must have at least one node");if(!Array.isArray(n))throw new B("Graph edges must be an array");let i=new ee(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let r=new Set,a=new Map,l={};for(let c of t){let w=$e(c);a.set(c.id,{...c,resolvedType:w}),w==="decision"&&r.add(c.id)}for(let[c,w]of a){if(r.has(c))continue;let g=w.resolvedType,E=s[c]||{},$=tt(g,E.tools);$&&(l[c]=$);let b={};E.prompt&&(b.prompt=E.prompt);let f=Ie(g);if(v.debug(`[workflow] compiler: node "${c}" type="${g}" registered=${f}`),E.customCode&&!f)i.addNode(c,so(c,E.customCode,E),b),i.setNodeType(c,g);else if(f){let m=Xe(g);m.factory?i.addNode(c,m.create(c,{...E,resolvedTools:$}),b):i.addNode(c,m,b),i.setNodeType(c,g)}else if(E.executeCode)i.addNode(c,so(c,E.executeCode,E),b),i.setNodeType(c,g);else throw new B(`Unknown node type "${g}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=l;let u=new Set;for(let c of n)r.has(c.target)||u.add(c.target);let h=t.find(c=>!r.has(c.id)&&!u.has(c.id));if(!h)throw new B("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(h.id);let d=an(n,"source");for(let c of n)if(!r.has(c.source))if(r.has(c.target)){let w=c.target,g=d.get(w)||[];if(g.length===0)throw new B(`Decision node "${w}" has no outgoing edges`);let E=cn(w,g,r);i.addConditionalEdges(c.source,E)}else i.addEdge(c.source,c.target);return i}function rn(o){let e=[];if(!o||typeof o!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(o.nodes)||o.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(o.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=o.nodeConfigs||{};for(let a of o.nodes){let l=$e(a);if(l==="decision"||Ie(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 n=new Set(o.nodes.map(a=>a.id));for(let a of o.edges)n.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),n.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let s=new Set(o.nodes.filter(a=>$e(a)==="decision").map(a=>a.id)),i=new Set;for(let a of o.edges)s.has(a.target)||i.add(a.target);let r=o.nodes.filter(a=>!s.has(a.id)&&!i.has(a.id));r.length===0?e.push("No entry point found (every node has incoming edges)"):r.length>1&&e.push(`Multiple entry points found: ${r.map(a=>a.id).join(", ")}`);for(let a of s){let l=o.edges.filter(h=>h.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(h=>h.data?.conditionalCode||h.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function sn(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>$e(e)!=="decision").map(e=>e.id)}function $e(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function an(o,e){let t=new Map;for(let n of o){let s=n[e];t.has(s)||t.set(s,[]),t.get(s).push(n)}return t}function cn(o,e,t){let n=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!n)throw new B(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let s=n.data?.conditionalCode||n.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),r;try{let l=new Function(`return (${s})`)();r=u=>{let h=l(u);return i.has(h)||v.warn(`[workflow] conditional route from "${o}" returned "${h}" which is not in valid targets: ${[...i].join(", ")}`),h}}catch(a){throw new B(`Failed to compile conditionalCode for "${o}": ${a.message}`)}return r}function so(o,e,t={}){let n;try{n=new Function("invokeAgent","require","console",`return (${e})`)}catch(r){throw new B(`Failed to compile customCode for node "${o}": ${r.message}`)}let s=n(async(...r)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(X(),pe));return a(...r)},typeof xe<"u"?xe:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:i,execute:async r=>{try{let a=await s(r);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 B=class extends Error{constructor(e){super(e),this.name="CompilationError"}};ue();var ot=/^[a-z][a-z0-9_]{0,40}$/;function ln(o){if(o==null)return[];if(!Array.isArray(o))return["stores must be an array of { name, description } objects"];let e=[],t=new Map;return o.forEach((n,s)=>{if(n==null||typeof n!="object"||Array.isArray(n)){e.push(`stores[${s}] must be an object { name, description }`);return}let{name:i}=n;if(typeof i!="string"||i.length===0){e.push(`stores[${s}] is missing a string "name"`);return}ot.test(i)||e.push(`stores[${s}] name "${i}" is invalid \u2014 must match ${ot} (lowercase letter first, then up to 40 of [a-z0-9_])`),t.has(i)?e.push(`stores[${s}] duplicate store name "${i}" (also at index ${t.get(i)}) \u2014 store names must be unique within a workflow`):t.set(i,s)}),e}Be();X();function dn(o,e={}){let{nodes:t,edges:n,nodeConfigs:s={}}=o,i=new Set,r=[],a=new Map;for(let $ of t){let b=$.data?.nodeType||$.type;a.set($.id,b),b==="decision"?i.add($.id):r.push({id:$.id,nodeType:b,label:$.data?.label||$.id})}let l=r.some($=>{let b=s[$.id]||{};return!b.customCode&&!b.executeCode}),{toolsPerNode:u,toolIdsByVar:h}=wn(r,s),{simpleEdges:d,conditionalEdges:c}=Sn(n,i),w=_n(r,n,i),g=[],E=e.workflowType||"workflow";return g.push(pn(e)),g.push(fn(E,{usesRegisteredNodes:l})),g.push(hn(h)),g.push(gn(E)),g.push(mn(r,s)),g.push(yn(r,w,d,c,u,E)),g.filter(Boolean).join(`
50
+ `)}`}pe();U();var $e={};function ot(o,e){if(Array.isArray(e))return tt(e);let t=$e[o];return!t||t.length===0?null:tt(t)}function tt(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},n=[];for(let s of o){let i=X(s);if(!i){I.warn(`[workflow] unknown skill "${s}" \u2014 skipping`);continue}n.push(s);for(let r of i.tools||[])e.push({name:r.name,description:r.description,input_schema:r.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let r=i.resolve();r&&(t[i.serverName]={...r,toolPrefix:s})}else{let r={};for(let a of i.envKeys||[]){let l=process.env[a];l&&(r[a]=l)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:r,toolPrefix:s}}}return n.length===0?null:{toolIds:n,claudeTools:e,mcpServers:t}}U();function nn(o,e={}){let{nodes:t,edges:n,nodeConfigs:s={}}=o;if(!Array.isArray(t)||t.length===0)throw new B("Graph must have at least one node");if(!Array.isArray(n))throw new B("Graph edges must be an array");let i=new te(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let r=new Set,a=new Map,l={};for(let c of t){let w=Te(c);a.set(c.id,{...c,resolvedType:w}),w==="decision"&&r.add(c.id)}for(let[c,w]of a){if(r.has(c))continue;let g=w.resolvedType,E=s[c]||{},v=ot(g,E.tools);v&&(l[c]=v);let b={};E.prompt&&(b.prompt=E.prompt);let f=ve(g);if(I.debug(`[workflow] compiler: node "${c}" type="${g}" registered=${f}`),E.customCode&&!f)i.addNode(c,io(c,E.customCode,E),b),i.setNodeType(c,g);else if(f){let m=Qe(g);m.factory?i.addNode(c,m.create(c,{...E,resolvedTools:v}),b):i.addNode(c,m,b),i.setNodeType(c,g)}else if(E.executeCode)i.addNode(c,io(c,E.executeCode,E),b),i.setNodeType(c,g);else throw new B(`Unknown node type "${g}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=l;let u=new Set;for(let c of n)r.has(c.target)||u.add(c.target);let h=t.find(c=>!r.has(c.id)&&!u.has(c.id));if(!h)throw new B("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(h.id);let d=an(n,"source");for(let c of n)if(!r.has(c.source))if(r.has(c.target)){let w=c.target,g=d.get(w)||[];if(g.length===0)throw new B(`Decision node "${w}" has no outgoing edges`);let E=cn(w,g,r);i.addConditionalEdges(c.source,E)}else i.addEdge(c.source,c.target);return i}function rn(o){let e=[];if(!o||typeof o!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(o.nodes)||o.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(o.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=o.nodeConfigs||{};for(let a of o.nodes){let l=Te(a);if(l==="decision"||ve(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 n=new Set(o.nodes.map(a=>a.id));for(let a of o.edges)n.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),n.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let s=new Set(o.nodes.filter(a=>Te(a)==="decision").map(a=>a.id)),i=new Set;for(let a of o.edges)s.has(a.target)||i.add(a.target);let r=o.nodes.filter(a=>!s.has(a.id)&&!i.has(a.id));r.length===0?e.push("No entry point found (every node has incoming edges)"):r.length>1&&e.push(`Multiple entry points found: ${r.map(a=>a.id).join(", ")}`);for(let a of s){let l=o.edges.filter(h=>h.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(h=>h.data?.conditionalCode||h.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function sn(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>Te(e)!=="decision").map(e=>e.id)}function Te(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function an(o,e){let t=new Map;for(let n of o){let s=n[e];t.has(s)||t.set(s,[]),t.get(s).push(n)}return t}function cn(o,e,t){let n=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!n)throw new B(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let s=n.data?.conditionalCode||n.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),r;try{let l=new Function(`return (${s})`)();r=u=>{let h=l(u);return i.has(h)||I.warn(`[workflow] conditional route from "${o}" returned "${h}" which is not in valid targets: ${[...i].join(", ")}`),h}}catch(a){throw new B(`Failed to compile conditionalCode for "${o}": ${a.message}`)}return r}function io(o,e,t={}){let n;try{n=new Function("invokeAgent","require","console",`return (${e})`)}catch(r){throw new B(`Failed to compile customCode for node "${o}": ${r.message}`)}let s=n(async(...r)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(Q(),fe));return a(...r)},typeof Ne<"u"?Ne:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:i,execute:async r=>{try{let a=await s(r);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 B=class extends Error{constructor(e){super(e),this.name="CompilationError"}};pe();var nt=/^[a-z][a-z0-9_]{0,40}$/;function ln(o){if(o==null)return[];if(!Array.isArray(o))return["stores must be an array of { name, description } objects"];let e=[],t=new Map;return o.forEach((n,s)=>{if(n==null||typeof n!="object"||Array.isArray(n)){e.push(`stores[${s}] must be an object { name, description }`);return}let{name:i}=n;if(typeof i!="string"||i.length===0){e.push(`stores[${s}] is missing a string "name"`);return}nt.test(i)||e.push(`stores[${s}] name "${i}" is invalid \u2014 must match ${nt} (lowercase letter first, then up to 40 of [a-z0-9_])`),t.has(i)?e.push(`stores[${s}] duplicate store name "${i}" (also at index ${t.get(i)}) \u2014 store names must be unique within a workflow`):t.set(i,s)}),e}De();Q();function dn(o,e={}){let{nodes:t,edges:n,nodeConfigs:s={}}=o,i=new Set,r=[],a=new Map;for(let v of t){let b=v.data?.nodeType||v.type;a.set(v.id,b),b==="decision"?i.add(v.id):r.push({id:v.id,nodeType:b,label:v.data?.label||v.id})}let l=r.some(v=>{let b=s[v.id]||{};return!b.customCode&&!b.executeCode}),{toolsPerNode:u,toolIdsByVar:h}=wn(r,s),{simpleEdges:d,conditionalEdges:c}=Sn(n,i),w=_n(r,n,i),g=[],E=e.workflowType||"workflow";return g.push(pn(e)),g.push(fn(E,{usesRegisteredNodes:l})),g.push(hn(h)),g.push(gn(E)),g.push(mn(r,s)),g.push(yn(r,w,d,c,u,E)),g.filter(Boolean).join(`
51
51
  `)}function un(o){let e={};for(let[t,n]of Object.entries(o)){let{tools:s,...i}=n;Object.keys(i).length>0&&(e[t]=i)}return e}function pn(o){let e=o.workflowType||"workflow";return["// Generated workflow",`// ${o.projectId?`Project: ${o.projectId} | `:""}Type: ${e} | Version: ${o.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
52
52
  `)}function fn(o,{usesRegisteredNodes:e=!0}={}){let t=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return e&&t.push("// import './register-nodes.js'; // register custom node types here"),t.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),t.join(`
53
53
  `)}function hn(o){if(o.size===0)return"";let e=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];for(let[t,n]of o)e.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(n)}); // ${n.join(", ")}`);return e.push(""),e.join(`
54
54
  `)}function gn(o){return["// \u2500\u2500 Node Configs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","const __filename = fileURLToPath(import.meta.url);","const __dirname = dirname(__filename);",`const configPath = join(__dirname, 'workflow-${o}.config.json');`,"const nodeConfigs = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')) : {};",""].join(`
55
- `)}function mn(o,e){let t=["// \u2500\u2500 Node Implementations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",""];for(let n of o){let s=io(n.id),i=e[n.id]?.customCode;if(i)t.push(`// @custom \u2014 modified from default "${n.nodeType}" template`),t.push(`const ${s}_execute = ${i};`);else{let r=Qe(n.nodeType);r?(t.push(`// Default "${n.nodeType}" implementation`),t.push(`const ${s}_execute = ${r};`)):(t.push(`// No template for "${n.nodeType}" \u2014 passthrough`),t.push(`const ${s}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}t.push("")}return t.join(`
56
- `)}function yn(o,e,t,n,s,i){let r=["// \u2500\u2500 Graph Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];r.push("export function buildGraph(options = {}) {"),r.push(" const graph = new WorkflowGraph(options);",""),r.push(" // Nodes");for(let l of o){let u=io(l.id);r.push(` graph.addNode('${l.id}', { name: '${l.id}', execute: ${u}_execute });`),r.push(` graph.setNodeType('${l.id}', '${l.nodeType}');`)}r.push("",` graph.setEntryPoint('${e}');`,""),(t.length>0||n.length>0)&&r.push(" // Edges");for(let l of t)r.push(` graph.addEdge('${l.source}', '${l.target}');`);for(let l of n){let u=l.code.split(`
55
+ `)}function mn(o,e){let t=["// \u2500\u2500 Node Implementations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",""];for(let n of o){let s=ao(n.id),i=e[n.id]?.customCode;if(i)t.push(`// @custom \u2014 modified from default "${n.nodeType}" template`),t.push(`const ${s}_execute = ${i};`);else{let r=et(n.nodeType);r?(t.push(`// Default "${n.nodeType}" implementation`),t.push(`const ${s}_execute = ${r};`)):(t.push(`// No template for "${n.nodeType}" \u2014 passthrough`),t.push(`const ${s}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}t.push("")}return t.join(`
56
+ `)}function yn(o,e,t,n,s,i){let r=["// \u2500\u2500 Graph Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];r.push("export function buildGraph(options = {}) {"),r.push(" const graph = new WorkflowGraph(options);",""),r.push(" // Nodes");for(let l of o){let u=ao(l.id);r.push(` graph.addNode('${l.id}', { name: '${l.id}', execute: ${u}_execute });`),r.push(` graph.setNodeType('${l.id}', '${l.nodeType}');`)}r.push("",` graph.setEntryPoint('${e}');`,""),(t.length>0||n.length>0)&&r.push(" // Edges");for(let l of t)r.push(` graph.addEdge('${l.source}', '${l.target}');`);for(let l of n){let u=l.code.split(`
57
57
  `).map((h,d)=>d===0?h:` ${h}`).join(`
58
58
  `);r.push(` graph.addConditionalEdges('${l.source}', ${u});`)}let a=[];for(let l of o){let u=s.get(l.id);u&&a.push(` '${l.id}': ${u},`)}return a.length>0&&r.push(""," graph.resolvedToolsMap = {",...a," };"),r.push(""," return graph;","}",""),r.push("export { nodeConfigs };",""),r.join(`
59
- `)}function wn(o,e){let t=new Map,n=new Map;for(let s of o){let i=e[s.id]?.tools,r;if(Array.isArray(i)&&i.length>0)r=[...i].sort();else{let a=ve[s.nodeType];a?.length>0&&(r=[...a].sort())}if(r){let a=`${r.map(l=>l.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;t.set(s.id,a),n.has(a)||n.set(a,r)}}return{toolsPerNode:t,toolIdsByVar:n}}function Sn(o,e){let t=[],n=[],s=new Map,i=new Set;for(let r of o)s.has(r.source)||s.set(r.source,[]),s.get(r.source).push(r);for(let r of o)if(!e.has(r.source))if(e.has(r.target)){if(i.has(r.target))continue;i.add(r.target);let l=(s.get(r.target)||[]).find(u=>u.data?.conditionalCode||u.conditionalCode);l&&n.push({source:r.source,code:l.data?.conditionalCode||l.conditionalCode})}else t.push({source:r.source,target:r.target});return{simpleEdges:t,conditionalEdges:n}}function _n(o,e,t){let n=new Set;for(let i of e)t.has(i.target)||n.add(i.target);let s=o.find(i=>!n.has(i.id));return s?s.id:o[0]?.id}function io(o){return o.replace(/[^a-zA-Z0-9]/g,"_")}W();var En=`## Composing deployed agents (wrapper over marketplace bricks)
59
+ `)}function wn(o,e){let t=new Map,n=new Map;for(let s of o){let i=e[s.id]?.tools,r;if(Array.isArray(i)&&i.length>0)r=[...i].sort();else{let a=$e[s.nodeType];a?.length>0&&(r=[...a].sort())}if(r){let a=`${r.map(l=>l.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;t.set(s.id,a),n.has(a)||n.set(a,r)}}return{toolsPerNode:t,toolIdsByVar:n}}function Sn(o,e){let t=[],n=[],s=new Map,i=new Set;for(let r of o)s.has(r.source)||s.set(r.source,[]),s.get(r.source).push(r);for(let r of o)if(!e.has(r.source))if(e.has(r.target)){if(i.has(r.target))continue;i.add(r.target);let l=(s.get(r.target)||[]).find(u=>u.data?.conditionalCode||u.conditionalCode);l&&n.push({source:r.source,code:l.data?.conditionalCode||l.conditionalCode})}else t.push({source:r.source,target:r.target});return{simpleEdges:t,conditionalEdges:n}}function _n(o,e,t){let n=new Set;for(let i of e)t.has(i.target)||n.add(i.target);let s=o.find(i=>!n.has(i.id));return s?s.id:o[0]?.id}function ao(o){return o.replace(/[^a-zA-Z0-9]/g,"_")}U();var En=`## Composing deployed agents (wrapper over marketplace bricks)
60
60
 
61
61
  **Red line: wrapper only.** Marketplace agents are shared LEGO bricks \u2014 NEVER
62
62
  modify a brick template's source and never rebuild its logic from scratch.
@@ -125,4 +125,4 @@ template workflow.json) and paste the exact array. The platform then
125
125
  automatically SUPPRESSES the wrapped members' own subscriptions (any workflow
126
126
  listed in a deployed wrapper's composedOf stops receiving standalone webhook
127
127
  events), so the same event never double-fires a brick inside AND outside the
128
- wrapper. Cron / manual / chat-triggered compositions need nothing special.`;export{Me as AgentStrategy,je as CI_ENV_VARS,En as COMPOSE_KNOWLEDGE,B as CompilationError,he as ContextLoader,le as DEFAULT_OUTPUT_BASE,$o as EVENTS_FILE,ee as Graph,ve as NODE_DEFAULT_TOOLS,To as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,F as Node,ie as OutputParser,vo as RAW_OUTPUT_FILE,Io as RESULT_FILE,Ce as SESSIONS_DIR,G as SESSION_INFO_FILE,Re as STOP_REQUEST_FILE,ot as STORE_NAME_REGEX,_o as SchemaTypes,_e as Timeline,_t as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,ee as WorkflowGraph,se as WorkflowState,eo as clearInheritedSessionEnvForFreshRun,Tt as clearSkills,nn as compileGraph,Ze as dispatchSubgraph,sn as extractSteps,un as generateNodeConfigsJson,dn as generateWorkflowCode,oo as generateWorkflowSessionId,Ge as getAgentStrategy,vt as getAllSkills,Xe as getNodeImpl,Qe as getNodeTemplate,et as getResolvedToolDefinitions,q as getSkill,It as getSkillSource,Ie as hasNode,bt as hasSkill,Nt as invokeAgent,tn as listNodeTypes,$t as listSkillIds,xt as listStrategies,Qt as readPinnedSessionPathFromEnv,ro as registerNode,Et as registerSkill,At as registerStrategy,Ue as resolveInvocationExtras,We as resolveInvocationModel,tt as resolveNodeTools,no as resolveWorkflowSession,Eo as setLogger,Xt as shouldTrustInheritedSessionEnv,to as syncProcessEnvToSession,x as timeline,rn as validateGraphConfig,ln as validateStoreDefs};
128
+ wrapper. Cron / manual / chat-triggered compositions need nothing special.`;export{Be as AgentStrategy,Me as CI_ENV_VARS,En as COMPOSE_KNOWLEDGE,B as CompilationError,ge as ContextLoader,de as DEFAULT_OUTPUT_BASE,$o as EVENTS_FILE,te as Graph,$e as NODE_DEFAULT_TOOLS,To as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,W as Node,ae as OutputParser,vo as RAW_OUTPUT_FILE,Io as RESULT_FILE,Re as SESSIONS_DIR,H as SESSION_INFO_FILE,je as STOP_REQUEST_FILE,nt as STORE_NAME_REGEX,_o as SchemaTypes,Ee as Timeline,Et as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,te as WorkflowGraph,ie as WorkflowState,to as clearInheritedSessionEnvForFreshRun,kt as clearSkills,nn as compileGraph,Ve as dispatchSubgraph,sn as extractSteps,un as generateNodeConfigsJson,dn as generateWorkflowCode,no as generateWorkflowSessionId,He as getAgentStrategy,$t as getAllSkills,Qe as getNodeImpl,et as getNodeTemplate,tt as getResolvedToolDefinitions,X as getSkill,vt as getSkillSource,ve as hasNode,It as hasSkill,Ot as invokeAgent,tn as listNodeTypes,Tt as listSkillIds,Nt as listStrategies,eo as readPinnedSessionPathFromEnv,so as registerNode,bt as registerSkill,xt as registerStrategy,Ge as resolveInvocationExtras,Ue as resolveInvocationModel,ot as resolveNodeTools,ro as resolveWorkflowSession,Eo as setLogger,Qt as shouldTrustInheritedSessionEnv,oo as syncProcessEnvToSession,N as timeline,rn as validateGraphConfig,ln as validateStoreDefs};
@@ -1 +1 @@
1
- var D=()=>{},Z={debug:D,info:D,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},R={impl:Z};var h={debug:(...e)=>R.impl.debug?.(...e),info:(...e)=>R.impl.info?.(...e),warn:(...e)=>R.impl.warn?.(...e),error:(...e)=>R.impl.error?.(...e)};import{mkdirSync as W,existsSync as A,statSync as N,readdirSync as X,rmSync as ee}from"node:fs";import{spawn as J}from"node:child_process";import{join as $}from"node:path";import{pathToFileURL as te}from"node:url";import{AsyncLocalStorage as ne}from"node:async_hooks";import{AsyncLocalStorage as K}from"node:async_hooks";var k=new K;function x(){let e=k.getStore();return e||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 M(e,t){let r=k.getStore()||x(),n=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??r.executionId??null,depth:(r.depth||0)+(e.executionId!==r.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:r.conversationId??null,dispatchMode:e.dispatchMode??null,agent:e.agent!==void 0?e.agent:r.agent??null,signal:e.signal!==void 0?e.signal:r.signal??null});return k.run(n,t)}var U=new Map,j=new Map,L=new Map;function G(e,t,r={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");U.set(e,t),j.set(e,"ready"),L.set(e,{...r,cachedAt:Date.now()})}function H(e,t){j.set(e,"failed"),L.set(e,{error:t?.message||String(t),failedAt:Date.now()}),U.delete(e)}function z(e){return j.get(e)==="ready"?U.get(e):null}var P=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function re(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var f=class extends Error{constructor(t,r){super(`in-process sub-graph fallback: ${t}${r?` (${r})`:""}`),this.fallback=!0,this.reason=t,this.detail=r||null,this.name="SubgraphFallback"}},F=new ne,q=Promise.resolve();async function oe(e,t){let r=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([s,i])=>typeof s=="string"&&s&&typeof i=="string"):[];if(r.length===0)return t();let n=F.getStore()===!0,a=null;if(!n){let s=q;q=new Promise(i=>{a=i}),await s}let o=new Map;try{for(let[s,i]of r)o.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=i;return h.debug(`[in-process subgraph] scoped ${r.length} child env var(s)${n?" (nested)":""}`),await F.run(!0,t)}finally{for(let[s,i]of o)i===void 0?delete process.env[s]:process.env[s]=i;a&&a()}}function se(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),r=e||t,n=process.env.PROJECT_ID,a=process.env.PROJECT_API_TOKEN;if(!r||!n||!a)throw new f("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:r,projectId:n,authToken:a}}async function ae({apiBase:e,authToken:t,body:r}){let n;try{n=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)})}catch(o){throw new f("network",`begin fetch failed: ${o.message}`)}let a=null;try{a=await n.json()}catch{}if(!n.ok){if(n.status===404){let o=new Error(`Sub-graph child '${r.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(n.status===429){let o=a?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${o.used??"?"}/${o.limit??"?"} on ${o.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=o,s}if(n.status===400&&a?.validationErrors){let o=new Error(`Sub-graph rejected input: ${a?.error||a?.message||"validation failed"}`);throw o.code="SUBGRAPH_INVALID_INPUT",o.status=400,o.validationErrors=a.validationErrors,o.missing=a.missing,o}throw new f("begin-status",`begin returned ${n.status}`)}return a?.data||a}async function T({apiBase:e,authToken:t,payload:r}){try{let n=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});n.ok||h.warn(`[in-process subgraph] finalize returned ${n.status} for ${r.childExecutionId}`)}catch(n){h.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function ie(e,t){let r=$(t,".ready"),n=$(t,"graph.mjs");if(A(r)&&A(n))return;W(t,{recursive:!0});let a=$(t,".lock"),o=!1;try{let{openSync:s,closeSync:i}=await import("node:fs"),y=s(a,"wx");i(y),o=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!o){let s=Date.now()+3e4;for(;Date.now()<s;){if(A(r)&&A(n))return;await new Promise(i=>setTimeout(i,100))}throw new f("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((y,b)=>{let p=J("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),S=J("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(S.stdin);let d,E,w=()=>{if(d!==void 0&&E!==void 0){if(d!==0)return b(new Error(`curl exited ${d}`));if(E!==0)return b(new Error(`tar exited ${E}`));y()}};p.on("close",v=>{d=v,w()}),S.on("close",v=>{E=v,w()}),p.on("error",b),S.on("error",b)});let{writeFileSync:s,unlinkSync:i}=await import("node:fs");s(r,"");try{i(a)}catch{}}catch(s){try{let{unlinkSync:i}=await import("node:fs");i(a)}catch{}throw new f("bundle-extract-failed",s.message)}}async function ce(e){let t=$(e,"graph.mjs");if(!A(t))throw new f("entry-missing",`graph.mjs missing under ${e}`);let r;try{r=await import(te(t).href)}catch(a){throw new f("import-failed",`${a?.code||a?.name||"unknown"}: ${a.message}`)}let n=r.default||Object.values(r).find(a=>typeof a=="function"&&a.prototype?.buildGraph);if(!n)throw new f("entry-class-missing","no buildGraph() class export found");return n}async function Y(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let r=x(),n;try{n=se()}catch(c){throw c}h.debug(`[in-process subgraph] begin '${e}' parent=${r.executionId||"<root>"}`);let a=await ae({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:r.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:o,runtimeTag:s,bundlePresignedUrl:i,sourcesPresignedUrl:y,workflowVersion:b,workflowUuid:p,bundleReady:S,nodeConfigs:d}=a,E=re();if(s&&s!==E)throw await T({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,discard:!0}}),new f("runtime-mismatch",`${E} vs ${s}`);if(!S||!i)throw await T({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,discard:!0}}),new f("no-bundle","workflow bundle not built yet");let w=z(e);if(!w){let c=$(P,`${p}@${b||"0"}`);try{await ie(i,c);try{le()}catch{}}catch(l){throw l.fallback&&await T({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,status:"failed",error:{message:l.message,code:l.reason}}}),l}try{w=await ce(c),G(e,w,{workflowUuid:p,version:b,runtimeTag:s,cacheDir:c})}catch(l){throw H(e,l),await T({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,status:"failed",error:{message:l.message,code:l.reason||"IMPORT_FAILED"}}}),l.fallback?l:new f("import-failed",l.message)}}let v=Date.now(),C=a.env&&typeof a.env=="object"&&!Array.isArray(a.env)?a.env:null,m=d&&typeof d=="object"&&!Array.isArray(d)&&Object.keys(d).length>0,B={...t.input||{},...m?{nodeConfigs:d}:{}},I,u;try{I=await oe(C,async()=>{let l=await(typeof w=="function"&&w.prototype?.buildGraph?new w:w).buildGraph();return M({executionId:o,parentExecutionId:r.executionId,conversationId:t.conversationId!==void 0?t.conversationId:r.conversationId,dispatchMode:"inprocess"},()=>l.run(t.parentAgent,B,{signal:t.signal}))}),u=I&&typeof I=="object"&&"state"in I?I.state:I}catch(c){throw await T({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,status:"failed",error:{message:c.message,code:c.code||"CHILD_THREW",stack:c.stack},durationMs:Date.now()-v}}),c}if(I&&typeof I=="object"&&I.stoppedExternally){await T({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,status:"canceled",finalState:u,durationMs:Date.now()-v}});let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=o,c}return await T({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,status:"completed",finalState:u,durationMs:Date.now()-v}}),{finalState:u,executionId:o}}function ue(e){let t=0,r=[e];for(;r.length;){let n=r.pop(),a;try{a=N(n)}catch{continue}if(a.isDirectory()){let o;try{o=X(n)}catch{continue}for(let s of o)r.push($(n,s))}else t+=a.size}return t}function le({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!A(P))return{evicted:0,freedBytes:0};let t=X(P),r=[],n=0;for(let i of t){let y=$(P,i),b;try{b=N(y)}catch{continue}let p=b.isDirectory()?ue(y):b.size;n+=p,r.push({name:i,full:y,size:p,mtimeMs:b.mtimeMs})}if(n<=e)return{evicted:0,freedBytes:0,totalBytes:n};r.sort((i,y)=>i.mtimeMs-y.mtimeMs);let a=Math.floor(e*.7),o=0,s=0;for(let i of r){if(n-o<=a)break;if(!A($(i.full,".lock")))try{ee(i.full,{recursive:!0,force:!0}),o+=i.size,s+=1}catch(y){h.debug(`[sub-graph cache] evict skip ${i.name}: ${y.message}`)}}return s>0&&h.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(o/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:o,totalBytes:n-o}}catch(t){return h.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var de=2e3,pe=600*1e3,he=new Set(["completed","failed","canceled","timeout"]);function ge(){let e=process.env.PROGRESS_API_URL;if(!e)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 e.replace(/\/executions\/?$/,"")}function fe(){let e=process.env.PROJECT_ID;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return e}function ye(){let e=process.env.PROJECT_API_TOKEN;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return e}function be(){return process.env.EXECUTION_ID||null}function V(e,t){return t==null?e:typeof t=="function"?t(e):typeof t=="string"?t.split(".").reduce((r,n)=>r==null?r:r[n],e):e}async function Ce(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let r=x();t.parentAgent==null&&r.agent&&(t.parentAgent=r.agent),t.signal==null&&r.signal&&(t.signal=r.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((r.depth||0)>=n)throw new Error(`dispatchSubgraph('${e}'): sub-graph depth ${r.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{h.debug(`[sub-graph] trying in-process for '${e}'`);let{finalState:u}=await Y(e,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),c=V(u,t.output);return h.info(`[sub-graph] '${e}' completed in-process`),c}catch(u){if(u instanceof f||u?.fallback)h.info(`[sub-graph] in-process fallback for '${e}': ${u.reason||"unknown"} \u2014 using HTTP`);else throw u}let a=ge(),o=fe(),s=ye(),i=be(),y=`${a}/projects/${encodeURIComponent(o)}/workflows/${encodeURIComponent(e)}/trigger`,b={input:t.input||{},...i?{parentExecutionId:i}:{},...t.conversationId?{conversationId:t.conversationId}:{}};h.info(`[sub-graph] dispatching '${e}' (${t.async?"async":"sync"}) from parent ${i||"<none>"}`);let p=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(b)});if(!p.ok){let u=null,c="";try{u=await p.json(),c=u?.error||u?.message||JSON.stringify(u)}catch{c=await p.text().catch(()=>"")}if(p.status===429){let g=u?.quotaInfo||{},_=new Error(`Sub-graph '${e}' blocked by execution quota (${g.used??"?"}/${g.limit??"?"} on plan ${g.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw _.code="SUBGRAPH_QUOTA_EXCEEDED",_.status=429,_.subgraph=e,_.quotaInfo=g,_}if(p.status===400){let g=new Error(`Sub-graph '${e}' rejected input: ${c}`);throw g.code="SUBGRAPH_INVALID_INPUT",g.status=400,g.subgraph=e,g.validationErrors=u?.validationErrors||null,g.missing=u?.missing||null,g}let l=new Error(`Sub-graph '${e}' trigger rejected (${p.status}): ${c}`);throw l.code="SUBGRAPH_TRIGGER_FAILED",l.status=p.status,l.subgraph=e,l}let S=await p.json(),d=S?.data?.jobId||S?.jobId;if(!d)throw new Error(`Sub-graph '${e}' trigger returned no jobId: ${JSON.stringify(S).slice(0,200)}`);if(t.async)return h.info(`[sub-graph] async dispatch of '${e}' \u2192 jobId=${d} (not waiting)`),{jobId:d,status:"accepted",workflow:e};let E=Number.isFinite(t.timeoutMs)?t.timeoutMs:pe,w=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:de,v=`${a}/executions/${encodeURIComponent(d)}`,C=Date.now()+E,m="accepted",B=0;for(;Date.now()<C;){await new Promise(g=>setTimeout(g,w)),B+=1;let u=await fetch(v,{headers:{Authorization:`Bearer ${s}`}});if(!u.ok){if(u.status>=500){h.warn(`[sub-graph] status poll for ${d} returned ${u.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${d}: ${u.status}`)}let c=await u.json(),l=c?.data||c?.execution||c;if(m=l?.status||m,he.has(m)){if(m!=="completed"){let O=new Error(`Sub-graph '${e}' (${d}) ended in status '${m}'`);throw O.subgraphJobId=d,O.subgraphStatus=m,O}let g=l?.finalState||l?.state||{},_=V(g,t.output);return h.info(`[sub-graph] '${e}' (${d}) completed after ${B} polls`),_}}let I=new Error(`Sub-graph '${e}' (${d}) timed out after ${Math.round(E/1e3)}s (last status: ${m})`);throw I.subgraphJobId=d,I.subgraphStatus=m,I}export{Ce as dispatchSubgraph};
1
+ var M=()=>{},K={debug:M,info:M,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},R={impl:K};var g={debug:(...e)=>R.impl.debug?.(...e),info:(...e)=>R.impl.info?.(...e),warn:(...e)=>R.impl.warn?.(...e),error:(...e)=>R.impl.error?.(...e)};import{mkdirSync as ee,existsSync as x,statSync as X,readdirSync as Y,rmSync as te}from"node:fs";import{spawn as F}from"node:child_process";import{join as T}from"node:path";import{pathToFileURL as ne}from"node:url";import{AsyncLocalStorage as re}from"node:async_hooks";import{AsyncLocalStorage as Q}from"node:async_hooks";var U=new Q;function B(){let e=U.getStore();return e||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 L(e,t){let r=U.getStore()||B(),n=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??r.executionId??null,depth:(r.depth||0)+(e.executionId!==r.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:r.conversationId??null,dispatchMode:e.dispatchMode??null,agent:e.agent!==void 0?e.agent:r.agent??null,signal:e.signal!==void 0?e.signal:r.signal??null});return U.run(n,t)}var j=new Map,D=new Map,G=new Map;function H(e,t,r={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");j.set(e,t),D.set(e,"ready"),G.set(e,{...r,cachedAt:Date.now()})}function z(e,t){D.set(e,"failed"),G.set(e,{error:t?.message||String(t),failedAt:Date.now()}),j.delete(e)}function J(e){return D.get(e)==="ready"?j.get(e):null}var C=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function se(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var f=class extends Error{constructor(t,r){super(`in-process sub-graph fallback: ${t}${r?` (${r})`:""}`),this.fallback=!0,this.reason=t,this.detail=r||null,this.name="SubgraphFallback"}},q=new re,N=Promise.resolve();async function ae(e,t){let r=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([a,c])=>typeof a=="string"&&a&&typeof c=="string"):[];if(r.length===0)return t();let n=q.getStore()===!0,o=null;if(!n){let a=N;N=new Promise(c=>{o=c}),await a}let s=new Map;try{for(let[a,c]of r)s.set(a,Object.prototype.hasOwnProperty.call(process.env,a)?process.env[a]:void 0),process.env[a]=c;return g.debug(`[in-process subgraph] scoped ${r.length} child env var(s)${n?" (nested)":""}`),await q.run(!0,t)}finally{for(let[a,c]of s)c===void 0?delete process.env[a]:process.env[a]=c;o&&o()}}function oe(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),r=e||t,n=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!r||!n||!o)throw new f("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:r,projectId:n,authToken:o}}async function ie({apiBase:e,authToken:t,body:r}){let n;try{n=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)})}catch(s){throw new f("network",`begin fetch failed: ${s.message}`)}let o=null;try{o=await n.json()}catch{}if(!n.ok){if(n.status===404){let s=new Error(`Sub-graph child '${r.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(n.status===429){let s=o?.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(n.status===400&&o?.validationErrors){let s=new Error(`Sub-graph rejected input: ${o?.error||o?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=o.validationErrors,s.missing=o.missing,s}throw new f("begin-status",`begin returned ${n.status}`)}return o?.data||o}async function A({apiBase:e,authToken:t,payload:r}){try{let n=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});n.ok||g.warn(`[in-process subgraph] finalize returned ${n.status} for ${r.childExecutionId}`)}catch(n){g.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function ce(e,t){let r=T(t,".ready"),n=T(t,"graph.mjs");if(x(r)&&x(n))return;ee(t,{recursive:!0});let o=T(t,".lock"),s=!1;try{let{openSync:a,closeSync:c}=await import("node:fs"),y=a(o,"wx");c(y),s=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!s){let a=Date.now()+3e4;for(;Date.now()<a;){if(x(r)&&x(n))return;await new Promise(c=>setTimeout(c,100))}throw new f("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((y,b)=>{let p=F("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),m=F("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(m.stdin);let l,I,w=()=>{if(l!==void 0&&I!==void 0){if(l!==0)return b(new Error(`curl exited ${l}`));if(I!==0)return b(new Error(`tar exited ${I}`));y()}};p.on("close",S=>{l=S,w()}),m.on("close",S=>{I=S,w()}),p.on("error",b),m.on("error",b)});let{writeFileSync:a,unlinkSync:c}=await import("node:fs");a(r,"");try{c(o)}catch{}}catch(a){try{let{unlinkSync:c}=await import("node:fs");c(o)}catch{}throw new f("bundle-extract-failed",a.message)}}async function ue(e){let t=T(e,"graph.mjs");if(!x(t))throw new f("entry-missing",`graph.mjs missing under ${e}`);let r;try{r=await import(ne(t).href)}catch(o){throw new f("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let n=r.default||Object.values(r).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!n)throw new f("entry-class-missing","no buildGraph() class export found");return n}async function V(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let r=B(),n;try{n=oe()}catch(i){throw i}g.debug(`[in-process subgraph] begin '${e}' parent=${r.executionId||"<root>"}`);let o=await ie({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:r.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:s,runtimeTag:a,bundlePresignedUrl:c,sourcesPresignedUrl:y,workflowVersion:b,workflowUuid:p,bundleReady:m,nodeConfigs:l}=o,I=se();if(a&&a!==I)throw await A({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,discard:!0}}),new f("runtime-mismatch",`${I} vs ${a}`);if(!m||!c)throw await A({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,discard:!0}}),new f("no-bundle","workflow bundle not built yet");let w=J(e);if(!w){let i=T(C,`${p}@${b||"0"}`);try{await ce(c,i);try{de()}catch{}}catch(u){throw u.fallback&&await A({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:u.message,code:u.reason}}}),u}try{w=await ue(i),H(e,w,{workflowUuid:p,version:b,runtimeTag:a,cacheDir:i})}catch(u){throw z(e,u),await A({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:u.message,code:u.reason||"IMPORT_FAILED"}}}),u.fallback?u:new f("import-failed",u.message)}}let S=Date.now(),O=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,E=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,P={...t.input||{},...E?{nodeConfigs:l}:{}},h,$;try{h=await ae(O,async()=>{let u=await(typeof w=="function"&&w.prototype?.buildGraph?new w:w).buildGraph();return L({executionId:s,parentExecutionId:r.executionId,conversationId:t.conversationId!==void 0?t.conversationId:r.conversationId,dispatchMode:"inprocess"},()=>u.run(t.parentAgent,P,{signal:t.signal}))}),$=h&&typeof h=="object"&&"state"in h?h.state:h}catch(i){throw await A({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:i.message,code:i.code||"CHILD_THREW",stack:i.stack},durationMs:Date.now()-S}}),i}if(h&&typeof h=="object"&&h.stoppedExternally){await A({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"canceled",finalState:$,durationMs:Date.now()-S}});let i=new Error(`Sub-graph '${e}' canceled by parent abort`);throw i.code="SUBGRAPH_CANCELED",i.subgraphJobId=s,i}return await A({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"completed",finalState:$,durationMs:Date.now()-S}}),{finalState:$,executionId:s}}function le(e){let t=0,r=[e];for(;r.length;){let n=r.pop(),o;try{o=X(n)}catch{continue}if(o.isDirectory()){let s;try{s=Y(n)}catch{continue}for(let a of s)r.push(T(n,a))}else t+=o.size}return t}function de({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!x(C))return{evicted:0,freedBytes:0};let t=Y(C),r=[],n=0;for(let c of t){let y=T(C,c),b;try{b=X(y)}catch{continue}let p=b.isDirectory()?le(y):b.size;n+=p,r.push({name:c,full:y,size:p,mtimeMs:b.mtimeMs})}if(n<=e)return{evicted:0,freedBytes:0,totalBytes:n};r.sort((c,y)=>c.mtimeMs-y.mtimeMs);let o=Math.floor(e*.7),s=0,a=0;for(let c of r){if(n-s<=o)break;if(!x(T(c.full,".lock")))try{te(c.full,{recursive:!0,force:!0}),s+=c.size,a+=1}catch(y){g.debug(`[sub-graph cache] evict skip ${c.name}: ${y.message}`)}}return a>0&&g.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:s,totalBytes:n-s}}catch(t){return g.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var pe=2e3,he=600*1e3,ge=new Set(["completed","failed","canceled","timeout"]);function fe(){let e=process.env.PROGRESS_API_URL;if(!e)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 e.replace(/\/executions\/?$/,"")}function ye(){let e=process.env.PROJECT_ID;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return e}function be(){let e=process.env.PROJECT_API_TOKEN;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return e}function we(){return process.env.EXECUTION_ID||null}function Z(e,t){return t==null?e:typeof t=="function"?t(e):typeof t=="string"?t.split(".").reduce((r,n)=>r==null?r:r[n],e):e}async function Oe(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let r=B();t.parentAgent==null&&r.agent&&(t.parentAgent=r.agent),t.signal==null&&r.signal&&(t.signal=r.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((r.depth||0)>=n)throw new Error(`dispatchSubgraph('${e}'): sub-graph depth ${r.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{g.debug(`[sub-graph] trying in-process for '${e}'`);let{finalState:i}=await V(e,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),u=Z(i,t.output);return g.info(`[sub-graph] '${e}' completed in-process`),u}catch(i){if(i instanceof f||i?.fallback)g.info(`[sub-graph] in-process fallback for '${e}': ${i.reason||"unknown"} \u2014 using HTTP`);else throw i}let o=fe(),s=ye(),a=be(),c=we(),y=`${o}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(e)}/trigger`,b={input:t.input||{},...c?{parentExecutionId:c}:{},...t.conversationId?{conversationId:t.conversationId}:{}};g.info(`[sub-graph] dispatching '${e}' (${t.async?"async":"sync"}) from parent ${c||"<none>"}`);let p=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(b)});if(!p.ok){let i=null,u="";try{i=await p.json(),u=i?.error||i?.message||JSON.stringify(i)}catch{u=await p.text().catch(()=>"")}if(p.status===429){let d=i?.quotaInfo||{},_=new Error(`Sub-graph '${e}' blocked by execution quota (${d.used??"?"}/${d.limit??"?"} on plan ${d.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw _.code="SUBGRAPH_QUOTA_EXCEEDED",_.status=429,_.subgraph=e,_.quotaInfo=d,_}if(p.status===400){let d=new Error(`Sub-graph '${e}' rejected input: ${u}`);throw d.code="SUBGRAPH_INVALID_INPUT",d.status=400,d.subgraph=e,d.validationErrors=i?.validationErrors||null,d.missing=i?.missing||null,d}let v=new Error(`Sub-graph '${e}' trigger rejected (${p.status}): ${u}`);throw v.code="SUBGRAPH_TRIGGER_FAILED",v.status=p.status,v.subgraph=e,v}let m=await p.json(),l=m?.data?.jobId||m?.jobId;if(!l)throw new Error(`Sub-graph '${e}' trigger returned no jobId: ${JSON.stringify(m).slice(0,200)}`);if(t.async)return g.info(`[sub-graph] async dispatch of '${e}' \u2192 jobId=${l} (not waiting)`),{jobId:l,status:"accepted",workflow:e};let I=Number.isFinite(t.timeoutMs)?t.timeoutMs:he,w=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:pe,S=`${o}/executions/${encodeURIComponent(l)}`,O=Date.now()+I,E="accepted",P=0,h=null;for(;Date.now()<O;){await new Promise(d=>setTimeout(d,w)),P+=1;let i;try{i=await fetch(S,{headers:{Authorization:`Bearer ${a}`}})}catch(d){h=d?.message||String(d),g.warn(`[sub-graph] status poll for ${l} could not reach the API (${h}), will retry`);continue}if(!i.ok){if(i.status>=500){g.warn(`[sub-graph] status poll for ${l} returned ${i.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${l}: ${i.status}`)}let u;try{u=await i.json()}catch(d){h=d?.message||String(d),g.warn(`[sub-graph] status poll for ${l} returned an unreadable body (${h}), will retry`);continue}let v=u?.data||u?.execution||u;if(E=v?.status||E,ge.has(E)){if(E!=="completed"){let k=new Error(`Sub-graph '${e}' (${l}) ended in status '${E}'`);throw k.subgraphJobId=l,k.subgraphStatus=E,k}let d=v?.finalState||v?.state||{},_=Z(d,t.output);return g.info(`[sub-graph] '${e}' (${l}) completed after ${P} polls`),_}}let $=new Error(`Sub-graph '${e}' (${l}) timed out after ${Math.round(I/1e3)}s (last status: ${E})`+(h?`; the status API was unreachable on the last attempt (${h})`:""));throw $.subgraphJobId=l,$.subgraphStatus=E,h&&($.subgraphTransportError=h),$}export{Oe as dispatchSubgraph};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/agent-workflow",
3
- "version": "0.6.8",
3
+ "version": "0.6.9",
4
4
  "description": "Graph-based AI agent workflow orchestration. Bring your own agent strategies.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",