@zibby/agent-workflow 2.0.10 → 2.0.12

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/graph.js CHANGED
@@ -1,42 +1,43 @@
1
- var en=Object.defineProperty;var ue=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var Qe=(n,e)=>{for(var t in e)en(n,t,{get:e[t],enumerable:!0})};var et,nn,Ie,fe,I,ne=ue(()=>{et=()=>{},nn={debug:et,info:et,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},Ie=Symbol.for("@zibby/agent-workflow.logger");globalThis[Ie]||(globalThis[Ie]={impl:nn});fe=globalThis[Ie],I={debug:(...n)=>fe.impl.debug?.(...n),info:(...n)=>fe.impl.info?.(...n),warn:(...n)=>fe.impl.warn?.(...n),error:(...n)=>fe.impl.error?.(...n)}});var gt=ue(()=>{});var mt={};Qe(mt,{clearSkills:()=>wn,getAllSkills:()=>Sn,getSkill:()=>Me,getSkillSource:()=>yn,hasSkill:()=>mn,listSkillIds:()=>_n,registerSkill:()=>gn});function gn(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:r=!1}=e,o=n.id;if(J.has(o)&&!r){let i=oe.get(o);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${o}" is already registered by ${a}; ${l} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}J.set(o,Object.freeze({...n})),t===void 0?oe.delete(o):oe.set(o,t)}function Me(n){return J.get(n)||null}function mn(n){return J.has(n)}function yn(n){return oe.get(n)||null}function Sn(){return new Map(J)}function _n(){return Array.from(J.keys())}function wn(){J.clear(),oe.clear()}var ke,Re,J,oe,Pe=ue(()=>{ke=Symbol.for("@zibby/agent-workflow.skills"),Re=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[ke]||(globalThis[ke]=new Map);globalThis[Re]||(globalThis[Re]=new Map);J=globalThis[ke],oe=globalThis[Re]});var Ce={};Qe(Ce,{EFFORT_LEVELS:()=>Be,getAgentStrategy:()=>wt,invokeAgent:()=>In,listStrategies:()=>En,registerStrategy:()=>bn,resolveInvocationEffort:()=>St,resolveInvocationExtras:()=>_t,resolveInvocationModel:()=>yt});function bn(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=z.findIndex(t=>t.getName()===n.getName());e>=0?z[e]=n:z.push(n)}function En(){return z.map(n=>n.getName())}function yt({config:n={},options:e={},strategyName:t,envModel:r,nodeConfigModel:o}={}){let i=n.models||{},s=typeof o=="string"&&o.trim()?o.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,d=n.agent?.[t]?.model||null,E=(typeof r=="string"?r.trim():"")||null;return s||a||l||d||e.model||E||null}function St({options:n={},envEffort:e,nodeConfigEffort:t}={}){let r=[t,n.effort,e].map(o=>typeof o=="string"?o.trim().toLowerCase():"").find(Boolean);return r?Be.indexOf(r)===-1?(I.warn(`[workflow] ignoring unknown effort "${r}" \u2014 expected one of ${Be.join(", ")}`),null):r:null}function _t({options:n={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],extraMcpServers:n.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:n.plugins||t.plugins||[]}}function wt(n={}){let{state:e={},preferredAgent:t=null}=n,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let i=z.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}I.debug(`[workflow] agent selection: requested=${r}`);let o=z.find(i=>i.getName()===r);if(!o){let i=z.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!o.canHandle(n))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${o.getName()}`),o}async function In(n,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},o={...e,state:r},i=wt(o),s=r.config||t.config||{},a=r._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",d=!l||l===i.name?a.model:null,E=yt({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:d}),u=!l||l===i.name?a.effort:null,c=St({options:t,envEffort:process.env.EFFORT,nodeConfigEffort:u}),_={...t,model:E,...c?{effort:c}:{},..._t({options:t,stateView:r,context:e}),config:s},p=n,A=_.skills||[];if(A.length>0&&!t.skipPromptFragments){let h=t.connectedIntegrations;if(!h){let f=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof f=="string"&&f.trim()!==""){h={};for(let g of f.split(",").map($=>$.trim()).filter(Boolean))h[g]=!0}}let T=f=>{let g=f&&f.requiresIntegration;return!g||!h?!0:(Array.isArray(g)?g:[g]).some(N=>h[N]===!0)},w=i.name==="assistant",y=f=>f?.inProcessOnly!==!0||w,m=A.map(f=>{let g=Me(f);if(!T(g)||!y(g))return null;let $=g?.promptFragment;return typeof $=="function"?$():$}).filter(Boolean);m.length>0&&(p+=`
1
+ var pn=Object.defineProperty;var ye=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var ot=(n,e)=>{for(var t in e)pn(n,t,{get:e[t],enumerable:!0})};var st,hn,xe,we,v,ae=ye(()=>{st=()=>{},hn={debug:st,info:st,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},xe=Symbol.for("@zibby/agent-workflow.logger");globalThis[xe]||(globalThis[xe]={impl:hn});we=globalThis[xe],v={debug:(...n)=>we.impl.debug?.(...n),info:(...n)=>we.impl.info?.(...n),warn:(...n)=>we.impl.warn?.(...n),error:(...n)=>we.impl.error?.(...n)}});var wt=ye(()=>{});var bt={};ot(bt,{clearSkills:()=>xn,getAllSkills:()=>Mn,getSkill:()=>Le,getSkillSource:()=>On,hasSkill:()=>$n,listSkillIds:()=>Rn,registerSkill:()=>vn});function vn(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:r=!1}=e,o=n.id;if(K.has(o)&&!r){let i=le.get(o);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${o}" is already registered by ${a}; ${l} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}K.set(o,Object.freeze({...n})),t===void 0?le.delete(o):le.set(o,t)}function Le(n){return K.get(n)||null}function $n(n){return K.has(n)}function On(n){return le.get(n)||null}function Mn(){return new Map(K)}function Rn(){return Array.from(K.keys())}function xn(){K.clear(),le.clear()}var De,je,K,le,Fe=ye(()=>{De=Symbol.for("@zibby/agent-workflow.skills"),je=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[De]||(globalThis[De]=new Map);globalThis[je]||(globalThis[je]=new Map);K=globalThis[De],le=globalThis[je]});var He={};ot(He,{EFFORT_LEVELS:()=>We,getAgentStrategy:()=>At,invokeAgent:()=>kn,listStrategies:()=>Nn,registerStrategy:()=>Pn,resolveInvocationEffort:()=>It,resolveInvocationExtras:()=>Tt,resolveInvocationModel:()=>Et});function Pn(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=V.findIndex(t=>t.getName()===n.getName());e>=0?V[e]=n:V.push(n)}function Nn(){return V.map(n=>n.getName())}function Et({config:n={},options:e={},strategyName:t,envModel:r,nodeConfigModel:o}={}){let i=n.models||{},s=typeof o=="string"&&o.trim()?o.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,u=n.agent?.[t]?.model||null,E=(typeof r=="string"?r.trim():"")||null;return s||a||l||u||e.model||E||null}function It({options:n={},envEffort:e,nodeConfigEffort:t}={}){let r=[t,n.effort,e].map(o=>typeof o=="string"?o.trim().toLowerCase():"").find(Boolean);return r?We.indexOf(r)===-1?(v.warn(`[workflow] ignoring unknown effort "${r}" \u2014 expected one of ${We.join(", ")}`),null):r:null}function Tt({options:n={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],extraMcpServers:n.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:n.plugins||t.plugins||[]}}function At(n={}){let{state:e={},preferredAgent:t=null}=n,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let i=V.map(s=>s.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=${r}`);let o=V.find(i=>i.getName()===r);if(!o){let i=V.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!o.canHandle(n))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return v.debug(`[workflow] using agent: ${o.getName()}`),o}async function kn(n,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},o={...e,state:r},i=At(o),s=r.config||t.config||{},a=r._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",u=!l||l===i.name?a.model:null,E=Et({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:u}),d=!l||l===i.name?a.effort:null,c=It({options:t,envEffort:process.env.EFFORT,nodeConfigEffort:d}),h={...t,model:E,...c?{effort:c}:{},...Tt({options:t,stateView:r,context:e}),config:s},f=n,w=h.skills||[];if(w.length>0&&!t.skipPromptFragments){let g=t.connectedIntegrations;if(!g){let p=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof p=="string"&&p.trim()!==""){g={};for(let S of p.split(",").map(y=>y.trim()).filter(Boolean))g[S]=!0}}let b=p=>{let S=p&&p.requiresIntegration;return!S||!g?!0:(Array.isArray(S)?S:[S]).some(M=>g[M]===!0)},I=i.name==="assistant",$=p=>p?.inProcessOnly!==!0||I,m=w.map(p=>{let S=Le(p);if(!b(S)||!$(S))return null;let y=S?.promptFragment;return typeof y=="function"?y():y}).filter(Boolean);m.length>0&&(f+=`
2
2
 
3
3
  ${m.join(`
4
4
 
5
- `)}`)}let v=r._currentNodeConfig?.stores;if(Array.isArray(v)&&v.length>0&&typeof v[0]=="object"){let h=v.length<=8,T=v.map(w=>{let y=w?.id??w?.storeId??"",m=(w?.name??"").toString().trim()||y,f=w?.type?` \xB7 ${w.type}`:"",g=(w?.description||"").toString().replace(/\s+/g," ").trim(),$=`- ${m} \xB7 ${g||"(no description)"}${f} (id: ${y})`;if(h&&w?.schema&&typeof w.schema=="object"){let N=w.schema.properties&&typeof w.schema.properties=="object"?Object.keys(w.schema.properties):Object.keys(w.schema);N.length&&($+=`
6
- fields: ${N.join(", ")}`)}return $});p+=`
5
+ `)}`)}let O=r._currentNodeConfig?.stores;if(Array.isArray(O)&&O.length>0&&typeof O[0]=="object"){let g=O.length<=8,b=O.map(I=>{let $=I?.id??I?.storeId??"",m=(I?.name??"").toString().trim()||$,p=I?.type?` \xB7 ${I.type}`:"",S=(I?.description||"").toString().replace(/\s+/g," ").trim(),y=`- ${m} \xB7 ${S||"(no description)"}${p} (id: ${$})`;if(g&&I?.schema&&typeof I.schema=="object"){let M=I.schema.properties&&typeof I.schema.properties=="object"?Object.keys(I.schema.properties):Object.keys(I.schema);M.length&&(y+=`
6
+ fields: ${M.join(", ")}`)}return y});f+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
9
- ${T.join(`
10
- `)}`}let O=r._currentNodeConfig?.extraPromptInstructions?.trim();return O&&(p+=`
9
+ ${b.join(`
10
+ `)}`}let R=r._currentNodeConfig?.extraPromptInstructions?.trim();return R&&(f+=`
11
11
 
12
12
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
13
13
  PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
14
14
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
15
15
 
16
- ${O}
17
- `),I.debug(`[workflow] prompt length: ${p.length} chars`),i.invoke(p,_)}var Ne,z,Be,Ue=ue(()=>{gt();ne();Pe();Ne=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ne]||(globalThis[Ne]=[]);z=globalThis[Ne];Be=["low","medium","high","xhigh","max"]});var tn=new Set(["__proto__","constructor","prototype"]);function Ee(n){if(tn.has(n))throw new Error(`Invalid state key: "${n}"`)}var de=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){Ee(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)Ee(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){Ee(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 pe=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(o=>o[0]);for(let o of r)try{return this.validate(JSON.parse(o))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,o]of Object.entries(this.schema)){if(o.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&o.type){let i=typeof e[r];i!==o.type&&t.push(`Field '${r}' expected ${o.type}, got ${i}`)}if(o.validate&&r in e){let i=o.validate(e[r]);i&&t.push(`Field '${r}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
16
+ ${R}
17
+ `),v.debug(`[workflow] prompt length: ${f.length} chars`),i.invoke(f,h)}var Ge,V,We,ze=ye(()=>{wt();ae();Fe();Ge=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ge]||(globalThis[Ge]=[]);V=globalThis[Ge];We=["low","medium","high","xhigh","max"]});var fn=new Set(["__proto__","constructor","prototype"]);function Re(n){if(fn.has(n))throw new Error(`Invalid state key: "${n}"`)}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){Re(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)Re(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){Re(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 X from"handlebars";var _e=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(o=>o[0]);for(let o of r)try{return this.validate(JSON.parse(o))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,o]of Object.entries(this.schema)){if(o.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&o.type){let i=typeof e[r];i!==o.type&&t.push(`Field '${r}' expected ${o.type}, got ${i}`)}if(o.validate&&r in e){let i=o.validate(e[r]);i&&t.push(`Field '${r}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
18
18
  ${t.join(`
19
- `)}`);return e}};ne();import{writeFileSync as De,readFileSync as bt,existsSync as Et,mkdirSync as Tn}from"node:fs";import{join as je,dirname as An}from"node:path";import R from"chalk";var rn="__WORKFLOW_GRAPH_LOG__",re=R.gray("\u2502"),on=R.gray("\u250C"),tt=R.gray("\u2514"),Te=R.green("\u25C6"),nt=R.hex("#c084fc")("\u25C6"),rt=R.hex("#2dd4bf")("\u25C6"),Ae=R.red("\u25C6"),ot=`${re} `,st=2;function it(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function at(n,e){return(t,r,o)=>{if(typeof t!="string")return n(t,r,o);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(s+=ot,e.col=st,e.lineStart=!1),l===`
19
+ `)}`);return e}};ae();import{writeFileSync as Je,readFileSync as vt,existsSync as $t,mkdirSync as Bn}from"node:fs";import{join as qe,dirname as Cn}from"node:path";import N from"chalk";var gn="__WORKFLOW_GRAPH_LOG__",ce=N.gray("\u2502"),mn=N.gray("\u250C"),it=N.gray("\u2514"),Pe=N.green("\u25C6"),at=N.hex("#c084fc")("\u25C6"),ct=N.hex("#2dd4bf")("\u25C6"),Ne=N.red("\u25C6"),lt=`${ce} `,ut=2;function dt(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function pt(n,e){return(t,r,o)=>{if(typeof t!="string")return n(t,r,o);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(s+=lt,e.col=ut,e.lineStart=!1),l===`
20
20
  `?(s+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,s+=l):e.inEsc?(s+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,s+=l,e.col>=i&&(s+=`
21
- ${ot}`,e.col=st))}return n(s,r,o)}}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=at(this._origStdoutWrite,e),process.stderr.write=at(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
21
+ ${lt}`,e.col=ut))}return n(s,r,o)}}var ke=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=pt(this._origStdoutWrite,e),process.stderr.write=pt(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=`${rn}${JSON.stringify(e)}
24
+ `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${gn}${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(Te,e):process.stdout.write.bind(process.stdout)(`${re} ${Te} ${e}
29
- `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(nt,e):process.stdout.write.bind(process.stdout)(`${re} ${nt} ${e}
30
- `)}stepMemory(e){let t=R.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(rt,t):process.stdout.write.bind(process.stdout)(`${re} ${rt} ${t}
31
- `)}stepFail(e){this._origStdoutWrite?this._writeDot(Ae,R.red(e)):process.stdout.write.bind(process.stdout)(`${re} ${Ae} ${R.red(e)}
32
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${on} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:o}=t;if(o)for(let s of o)this._rawWrite(`${Te} ${s}`);let i=r?R.dim(` ${it(r)}`):"";this._rawWrite(`${tt} ${R.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:o}=r,i=o?R.dim(` ${it(o)}`):"";this._rawWrite(`${Ae} ${R.red(t)}`),this._rawWrite(`${tt} ${R.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(R.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},P=new $e;var he=".zibby/output",ct="sessions",X=".session-info.json",lt=".zibby-stop";var yr=Object.freeze(["codebase-memory","code-scan","artifact"]),ut=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var sn=Object.freeze({authentication_failed:"deterministic",oauth_org_not_allowed:"deterministic",billing_error:"deterministic",invalid_request:"deterministic",max_output_tokens:"deterministic",rate_limit:"transient",server_error:"transient",unknown:"inconclusive"}),an=Object.freeze([/stream idle timeout/i,/partial response received/i,/no chunks received/i,/stream ended without receiving any events/i,/stream completed without receiving/i,/socket hang up/i,/premature close/i,/\b(?:ECONNRESET|ECONNABORTED|ECONNREFUSED|EPIPE|ETIMEDOUT|EAI_AGAIN|ENETUNREACH|ENETRESET|EHOSTUNREACH)\b/,/\bfetch failed\b/i,/\bnetwork (?:error|timeout)\b/i,/request timed out/i,/\brequest timeout\b/i,/\boverloaded(?:_error)?\b/i,/\brate[_ ]limit(?:_error|ed)?\b/i,/\b(?:HTTP|http_status|status(?:\s*code)?)[:= ]\s*(?:429|5\d\d)\b/i,/\b(?:429|500|502|503|504|529)\s+(?:too many requests|internal server error|bad gateway|service unavailable|gateway time-?out|overloaded)\b/i]),cn=Object.freeze([/\bAbortError\b/,/\bAPIUserAbortError\b/,/\boperation was aborted\b/i,/\bcanceled by parent abort\b/i,/\bstopped by operator\b/i]),ft=/provider error \[([a-z_]+)(?:\s+http\s+(\d{3}))?\]/i;function Oe(n){if(n==null)return"";if(typeof n=="string")return n;if(typeof n!="object")return String(n);let e=n;return[e.message,e.name,e.code,e.providerErrorText,e.cause?.message??(typeof e.cause=="string"?e.cause:void 0),e.cause?.code].filter(r=>typeof r=="string"||typeof r=="number").join(" | ")}function ln(n){if(n&&typeof n=="object"){let t=n.providerErrorKind;if(typeof t=="string"&&t.trim())return t.trim()}let e=ft.exec(Oe(n));return e?e[1].toLowerCase():null}function un(n){if(n&&typeof n=="object"){let r=Number(n.providerErrorStatus);if(Number.isInteger(r)&&r>=100&&r<=599)return r}let e=ft.exec(Oe(n)),t=e&&e[2]?Number(e[2]):NaN;return Number.isInteger(t)?t:null}function dn(n){let e=Oe(n);if(!e)return"deterministic";for(let o of cn)if(o.test(e))return"deterministic";let t=ln(n);if(t){let o=sn[t];if(o==="transient"||o==="deterministic")return o}let r=un(n);if(r===429||r>=500&&r<=599)return"transient";for(let o of an)if(o.test(e))return"transient";return"deterministic"}var dt=2,pn=5;function fn(n=process.env){let e=n?.AGENT_TRANSIENT_RETRIES;if(e==null||String(e).trim()==="")return dt;let t=Number(e);return!Number.isFinite(t)||t<0?dt:Math.min(pn,Math.floor(t))}var ve=5e3,ht=3e4;function hn(n=process.env){let e=n?.AGENT_TRANSIENT_BACKOFF_MS;if(e==null||String(e).trim()==="")return ve;let t=Number(e);return!Number.isFinite(t)||t<0?ve:Math.min(ht,Math.floor(t))}function pt(n,e=Math.random,t=ve){if(!(t>0))return 0;let r=Math.max(1,Math.floor(Number(n)||1)),o=Math.min(ht,t*2**(r-1)),i=1+(e()-.5)*.4;return Math.max(1,Math.round(o*i))}function xe(n,{env:e=process.env,rand:t=Math.random}={}){let r=Math.max(0,Math.floor(Number(n)||0)),o=fn(e),i=hn(e),s=0,a=0;return{get attemptsMade(){return 1+s+a},get transientUsed(){return a},get transientMax(){return o},next(l){let d=dn(l);return s<r?(s+=1,{retry:!0,paidBy:"declared",delayMs:d==="transient"?pt(s,t,i):0,failureClass:d,index:s,of:r}):d==="transient"&&a<o?(a+=1,{retry:!0,paidBy:"transient",delayMs:pt(a,t,i),failureClass:d,index:a,of:o}):{retry:!1,delayMs:0,failureClass:d}}}}async function It(n,e,t,r){if(!e.retry)return!1;if(r())return I.info(`[workflow] node '${n}': run aborted \u2014 not retrying`),!1;let o=t?.message??String(t??"");return e.paidBy==="transient"?I.warn(`[workflow] node '${n}': TRANSIENT provider failure \u2014 ${o}. Retrying in ${Math.round(e.delayMs/1e3)}s (transient retry ${e.index}/${e.of}; the workspace is untouched, so files this node already wrote survive into the retry).`):I.info(`[workflow] node '${n}' failed (${e.failureClass}), retrying (${e.index}/${e.of})\u2026`),e.delayMs>0&&(await new Promise(i=>setTimeout(i,e.delayMs)),r())?(I.info(`[workflow] node '${n}': run aborted during backoff \u2014 not retrying`),!1):!0}Y.helpers.inc||Y.registerHelper("inc",n=>Number(n)+1);Y.helpers.json||Y.registerHelper("json",n=>JSON.stringify(n,null,2));Y.helpers.eq||Y.registerHelper("eq",(n,e)=>n===e);var G=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new pe(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return I.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,o=_=>t&&typeof t.get=="function"?t.get(_):e?.[_],i=()=>o("_signal")?.aborted===!0;if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let _=xe(this.retries),p=null,A=null;for(;;){try{let h=await this.customExecute(e);if(typeof h=="object"&&h!==null&&h.success===!1)A=null,p={success:!1,error:h.error||`node '${this.name}' returned { success: false } with no \`error\` field. On a custom-code node \`success\` is RESERVED: the engine reads it as "this node failed" and stops the graph. If it was meant as a DOMAIN fact (no diff to commit, a PR deliberately skipped), give that fact its own field name and return the outcome \u2014 or set \`error\` to say what actually failed.`,raw:h.raw||null};else return this.isZodSchema?(I.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(h),raw:null}):{success:!0,output:h,raw:null}}catch(h){I.error(`[workflow] node '${this.name}' failed: ${h.message}`),h.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(h.issues||h.errors,null,2)}`),A=h,p={success:!1,error:h.message,raw:null}}let v=A??p?.error,O=_.next(v);if(!await It(this.name,O,v,i))break}return p&&(p.attempts=_.attemptsMade),p}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=Y.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let a=o("_skillHints");a&&(s=`${a}
28
+ `)}step(e){this._origStdoutWrite?this._writeDot(Pe,e):process.stdout.write.bind(process.stdout)(`${ce} ${Pe} ${e}
29
+ `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(at,e):process.stdout.write.bind(process.stdout)(`${ce} ${at} ${e}
30
+ `)}stepMemory(e){let t=N.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(ct,t):process.stdout.write.bind(process.stdout)(`${ce} ${ct} ${t}
31
+ `)}stepFail(e){this._origStdoutWrite?this._writeDot(Ne,N.red(e)):process.stdout.write.bind(process.stdout)(`${ce} ${Ne} ${N.red(e)}
32
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${mn} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:o}=t;if(o)for(let s of o)this._rawWrite(`${Pe} ${s}`);let i=r?N.dim(` ${dt(r)}`):"";this._rawWrite(`${it} ${N.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:o}=r,i=o?N.dim(` ${dt(o)}`):"";this._rawWrite(`${Ne} ${N.red(t)}`),this._rawWrite(`${it} ${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(){}},C=new ke;var be=".zibby/output",ft="sessions",re=".session-info.json",ht=".zibby-stop";var Rr=Object.freeze(["codebase-memory","code-scan","artifact"]),gt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var yn=Object.freeze({authentication_failed:"deterministic",oauth_org_not_allowed:"deterministic",billing_error:"deterministic",invalid_request:"deterministic",max_output_tokens:"deterministic",rate_limit:"transient",server_error:"transient",unknown:"inconclusive"}),Sn=Object.freeze([/stream idle timeout/i,/partial response received/i,/no chunks received/i,/stream ended without receiving any events/i,/stream completed without receiving/i,/socket hang up/i,/premature close/i,/\b(?:ECONNRESET|ECONNABORTED|ECONNREFUSED|EPIPE|ETIMEDOUT|EAI_AGAIN|ENETUNREACH|ENETRESET|EHOSTUNREACH)\b/,/\bfetch failed\b/i,/\bnetwork (?:error|timeout)\b/i,/request timed out/i,/\brequest timeout\b/i,/\boverloaded(?:_error)?\b/i,/\brate[_ ]limit(?:_error|ed)?\b/i,/\b(?:HTTP|http_status|status(?:\s*code)?)[:= ]\s*(?:429|5\d\d)\b/i,/\b(?:429|500|502|503|504|529)\s+(?:too many requests|internal server error|bad gateway|service unavailable|gateway time-?out|overloaded)\b/i]),_n=Object.freeze([/\bAbortError\b/,/\bAPIUserAbortError\b/,/\boperation was aborted\b/i,/\bcanceled by parent abort\b/i,/\bstopped by operator\b/i]),St=/provider error \[([a-z_]+)(?:\s+http\s+(\d{3}))?\]/i;function Ce(n){if(n==null)return"";if(typeof n=="string")return n;if(typeof n!="object")return String(n);let e=n;return[e.message,e.name,e.code,e.providerErrorText,e.cause?.message??(typeof e.cause=="string"?e.cause:void 0),e.cause?.code].filter(r=>typeof r=="string"||typeof r=="number").join(" | ")}function wn(n){if(n&&typeof n=="object"){let t=n.providerErrorKind;if(typeof t=="string"&&t.trim())return t.trim()}let e=St.exec(Ce(n));return e?e[1].toLowerCase():null}function bn(n){if(n&&typeof n=="object"){let r=Number(n.providerErrorStatus);if(Number.isInteger(r)&&r>=100&&r<=599)return r}let e=St.exec(Ce(n)),t=e&&e[2]?Number(e[2]):NaN;return Number.isInteger(t)?t:null}function En(n){let e=Ce(n);if(!e)return"deterministic";for(let o of _n)if(o.test(e))return"deterministic";let t=wn(n);if(t){let o=yn[t];if(o==="transient"||o==="deterministic")return o}let r=bn(n);if(r===429||r>=500&&r<=599)return"transient";for(let o of Sn)if(o.test(e))return"transient";return"deterministic"}var mt=2,In=5;function Tn(n=process.env){let e=n?.AGENT_TRANSIENT_RETRIES;if(e==null||String(e).trim()==="")return mt;let t=Number(e);return!Number.isFinite(t)||t<0?mt:Math.min(In,Math.floor(t))}var Be=5e3,_t=3e4;function An(n=process.env){let e=n?.AGENT_TRANSIENT_BACKOFF_MS;if(e==null||String(e).trim()==="")return Be;let t=Number(e);return!Number.isFinite(t)||t<0?Be:Math.min(_t,Math.floor(t))}function yt(n,e=Math.random,t=Be){if(!(t>0))return 0;let r=Math.max(1,Math.floor(Number(n)||1)),o=Math.min(_t,t*2**(r-1)),i=1+(e()-.5)*.4;return Math.max(1,Math.round(o*i))}function Ue(n,{env:e=process.env,rand:t=Math.random}={}){let r=Math.max(0,Math.floor(Number(n)||0)),o=Tn(e),i=An(e),s=0,a=0;return{get attemptsMade(){return 1+s+a},get transientUsed(){return a},get transientMax(){return o},next(l){let u=En(l);return s<r?(s+=1,{retry:!0,paidBy:"declared",delayMs:u==="transient"?yt(s,t,i):0,failureClass:u,index:s,of:r}):u==="transient"&&a<o?(a+=1,{retry:!0,paidBy:"transient",delayMs:yt(a,t,i),failureClass:u,index:a,of:o}):{retry:!1,delayMs:0,failureClass:u}}}}async function Ot(n,e,t,r){if(!e.retry)return!1;if(r())return v.info(`[workflow] node '${n}': run aborted \u2014 not retrying`),!1;let o=t?.message??String(t??"");return e.paidBy==="transient"?v.warn(`[workflow] node '${n}': TRANSIENT provider failure \u2014 ${o}. Retrying in ${Math.round(e.delayMs/1e3)}s (transient retry ${e.index}/${e.of}; the workspace is untouched, so files this node already wrote survive into the retry).`):v.info(`[workflow] node '${n}' failed (${e.failureClass}), retrying (${e.index}/${e.of})\u2026`),e.delayMs>0&&(await new Promise(i=>setTimeout(i,e.delayMs)),r())?(v.info(`[workflow] node '${n}': run aborted during backoff \u2014 not retrying`),!1):!0}X.helpers.inc||X.registerHelper("inc",n=>Number(n)+1);X.helpers.json||X.registerHelper("json",n=>JSON.stringify(n,null,2));X.helpers.eq||X.registerHelper("eq",(n,e)=>n===e);var H=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 _e(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 r=()=>t&&typeof t.getAll=="function"?t.getAll():e,o=h=>t&&typeof t.get=="function"?t.get(h):e?.[h],i=()=>o("_signal")?.aborted===!0;if(typeof this.customExecute=="function"){v.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let h=Ue(this.retries),f=null,w=null;for(;;){try{let g=await this.customExecute(e);if(typeof g=="object"&&g!==null&&g.success===!1)w=null,f={success:!1,error:g.error||`node '${this.name}' returned { success: false } with no \`error\` field. On a custom-code node \`success\` is RESERVED: the engine reads it as "this node failed" and stops the graph. If it was meant as a DOMAIN fact (no diff to commit, a PR deliberately skipped), give that fact its own field name and return the outcome \u2014 or set \`error\` to say what actually failed.`,raw:g.raw||null};else return this.isZodSchema?(v.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(g),raw:null}):{success:!0,output:g,raw:null}}catch(g){v.error(`[workflow] node '${this.name}' failed: ${g.message}`),g.name==="ZodError"&&v.error(`Schema errors: ${JSON.stringify(g.issues||g.errors,null,2)}`),w=g,f={success:!1,error:g.message,raw:null}}let O=w??f?.error,R=h.next(O);if(!await Ot(this.name,R,O,i))break}return f&&(f.attempts=h.attemptsMade),f}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=X.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let a=o("_skillHints");a&&(s=`${a}
33
33
 
34
- ${s}`);let l=r(),d=l.cwd||process.cwd(),E=l.sessionPath;try{if(E){let _=je(E,X);if(Et(_)){let A=JSON.parse(bt(_,"utf-8"));A.currentNode=this.name,De(_,JSON.stringify(A,null,2),"utf-8")}let p=je(E,"..",X);if(Et(p))try{let A=JSON.parse(bt(p,"utf-8"));A.currentNode=this.name,De(p,JSON.stringify(A,null,2),"utf-8")}catch{}}}catch(_){I.debug(`[workflow] could not update session info: ${_.message}`)}let u=xe(this.retries),c=null;for(;;)try{I.debug(`[workflow] node '${this.name}' attempt ${u.attemptsMade-1}`);let _=r().config||{},p=_.agents||{},A=this.config.agent??p[this.name]??null,v={state:r()};A&&(v.preferredAgent=A);let O={workspace:d,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:E,config:_,nodeName:this.name,timeout:this.config?.timeout||3e5},h=e?._coreInvokeAgent;h||(h=(await Promise.resolve().then(()=>(Ue(),Ce))).invokeAgent);let T=await h(s,v,O),w,y;if(typeof T=="string"?(w=T,y=null):T.structured?(w=T.raw||JSON.stringify(T.structured,null,2),y=T.structured):(w=T.raw||JSON.stringify(T,null,2),y=T.extracted||null),E)try{let m=je(E,this.name,"raw_stream_output.txt");Tn(An(m),{recursive:!0}),De(m,typeof w=="string"?w:JSON.stringify(w),"utf-8")}catch(m){I.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&y){I.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let m=y;if(typeof this.onComplete=="function")try{m=await this.onComplete(r(),y)}catch(f){I.warn(`[workflow] onComplete hook failed: ${f.message}`)}return{success:!0,output:m,raw:w}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:w}),raw:w}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(w);return I.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),P.step("Output parsed"),{success:!0,output:m,raw:w}}return{success:!0,output:w,raw:w}}catch(_){c=_;let p=u.next(_);if(!await It(this.name,p,_,i))break}return{success:!1,error:c.message,raw:null,attempts:u.attemptsMade}}};ne();ne();import{mkdirSync as kn,existsSync as q,statSync as Pt,readdirSync as Nt,rmSync as Rn}from"node:fs";import{spawn as kt}from"node:child_process";import{join as H}from"node:path";import{pathToFileURL as Mn}from"node:url";import{AsyncLocalStorage as Pn}from"node:async_hooks";import{AsyncLocalStorage as $n}from"node:async_hooks";var se=new $n;function Q(){let n=se.getStore();return n||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function Tt(n,e){let t=se.getStore()||Q(),r=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return se.run(r,e)}function At(n,e,t){let r=se.getStore()||Q(),o=Object.freeze({...r,agent:n??r.agent??null,signal:e??r.signal??null});return se.run(o,t)}var Le=new Map,Fe=new Map,$t=new Map;function vt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Le.set(n,e),Fe.set(n,"ready"),$t.set(n,{...t,cachedAt:Date.now()})}function Ot(n,e){Fe.set(n,"failed"),$t.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Le.delete(n)}function xt(n){return Fe.get(n)==="ready"?Le.get(n):null}function ie(n,e,t=process.env){let r=Number(t[n]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):e}function Ge(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function ae(n,e){return Ge(ie(n,e),n)}function j(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}var ge=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Nn(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var M=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}};function me(n,e,t,r="timeout",o=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${r})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=r,o&&(i.subgraphTransportError=o),i}function Bn(n,e=process.env,t=process.uptime()){let r=Number.isFinite(n)?Number(n):null,o=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,s=Number.isFinite(o)&&o>0?o-i:null;if(r===null&&s===null)return null;let a=r===null?s:s===null?r:Math.min(r,s);return Math.max(1,a)}function Cn(n,e){let t=new AbortController,r=!1,o=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(o=setTimeout(()=>{r=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof o.unref=="function"&&o.unref()),{signal:t.signal,timedOut:()=>r,dispose(){o&&(clearTimeout(o),o=null),n&&n.removeEventListener("abort",i)}}}var Rt=new Pn,Mt=Promise.resolve();async function Un(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(t.length===0)return e();let r=Rt.getStore()===!0,o=null;if(!r){let s=Mt;Mt=new Promise(a=>{o=a}),await s}let i=new Map;try{for(let[s,a]of t)i.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=a;return I.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await Rt.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;o&&o()}}function Dn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!t||!r||!o)throw new M("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:o}}async function jn({apiBase:n,authToken:e,body:t}){let r=ae("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal})}catch(s){throw new M(j(s)?"begin-timeout":"network",j(s)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${s.message}`)}let i=null;try{i=await o.json()}catch(s){if(j(s))throw new M("begin-timeout",`begin body read TIMED OUT ${r.label}`)}if(!o.ok){if(o.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(o.status===429){let s=i?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=s,a}if(o.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new M("begin-status",`begin returned ${o.status}`)}return i?.data||i}async function Z({apiBase:n,authToken:e,payload:t}){let r=ae("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal});o.ok||I.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){I.warn(`[in-process subgraph] finalize ${j(o)?`TIMED OUT ${r.label}`:`failed: ${o.message}`}`)}}async function Ln(n,e){let t=H(e,".ready"),r=H(e,"graph.mjs");if(q(t)&&q(r))return;kn(e,{recursive:!0});let o=H(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),l=s(o,"wx");a(l),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(q(t)&&q(r))return;await new Promise(a=>setTimeout(a,100))}throw new M("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,d)=>{let E=Math.ceil(1e4/1e3),u=Math.ceil(ie("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=kt("curl",["-fsSL","--connect-timeout",String(E),"--max-time",String(u),n],{stdio:["ignore","pipe","inherit"]}),_=kt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(_.stdin);let p,A,v=()=>{if(p!==void 0&&A!==void 0){if(p!==0)return d(new Error(`curl exited ${p}`));if(A!==0)return d(new Error(`tar exited ${A}`));l()}};c.on("close",O=>{p=O,v()}),_.on("close",O=>{A=O,v()}),c.on("error",d),_.on("error",d)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(o)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(o)}catch{}throw new M("bundle-extract-failed",s.message)}}async function Fn(n){let e=H(n,"graph.mjs");if(!q(e))throw new M("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(Mn(e).href)}catch(o){throw new M("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=t.default||Object.values(t).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new M("entry-class-missing","no buildGraph() class export found");return r}async function Bt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=Q(),r;try{r=Dn()}catch(f){throw f}I.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let o=await jn({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:d,workflowUuid:E,bundleReady:u,nodeConfigs:c}=o,_=Nn();if(s&&s!==_)throw await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new M("runtime-mismatch",`${_} vs ${s}`);if(!u||!a)throw await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new M("no-bundle","workflow bundle not built yet");let p=xt(n);if(!p){let f=H(ge,`${E}@${d||"0"}`);try{await Ln(a,f);try{Hn()}catch{}}catch(g){throw g.fallback&&await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:g.message,code:g.reason}}}),g}try{p=await Fn(f),vt(n,p,{workflowUuid:E,version:d,runtimeTag:s,cacheDir:f})}catch(g){throw Ot(n,g),await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:g.message,code:g.reason||"IMPORT_FAILED"}}}),g.fallback?g:new M("import-failed",g.message)}}let A=Date.now(),v=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,O=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...O?{nodeConfigs:c}:{}},T=Bn(e.timeoutMs),w=Cn(e.signal,T),y,m;try{y=await Un(v,async()=>{let g=await(typeof p=="function"&&p.prototype?.buildGraph?new p:p).buildGraph();return Tt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>g.run(e.parentAgent,h,{signal:w.signal}))}),m=y&&typeof y=="object"&&"state"in y?y.state:y}catch(f){let g=w.timedOut();throw await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:g?"timeout":"failed",error:g?{message:`aborted at the declared ${Math.round(T/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:f.message,code:f.code||"CHILD_THREW",stack:f.stack},durationMs:Date.now()-A}}),g?me(n,i,T):f}finally{w.dispose()}if(y&&typeof y=="object"&&y.stoppedExternally){let f=w.timedOut();if(await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:f?"timeout":"canceled",finalState:m,durationMs:Date.now()-A}}),f)throw me(n,i,T);let g=new Error(`Sub-graph '${n}' canceled by parent abort`);throw g.code="SUBGRAPH_CANCELED",g.subgraphJobId=i,g}return await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:m,durationMs:Date.now()-A}}),{finalState:m,executionId:i}}function Gn(n){let e=0,t=[n];for(;t.length;){let r=t.pop(),o;try{o=Pt(r)}catch{continue}if(o.isDirectory()){let i;try{i=Nt(r)}catch{continue}for(let s of i)t.push(H(r,s))}else e+=o.size}return e}function Hn({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!q(ge))return{evicted:0,freedBytes:0};let e=Nt(ge),t=[],r=0;for(let a of e){let l=H(ge,a),d;try{d=Pt(l)}catch{continue}let E=d.isDirectory()?Gn(l):d.size;r+=E,t.push({name:a,full:l,size:E,mtimeMs:d.mtimeMs})}if(r<=n)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let o=Math.floor(n*.7),i=0,s=0;for(let a of t){if(r-i<=o)break;if(!q(H(a.full,".lock")))try{Rn(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(l){I.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return s>0&&I.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:r-i}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Jn=2e3,zn=600*1e3,Yn=new Set(["completed","failed","canceled","timeout"]);var Zn=()=>ae("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function qn(n){let e=ie("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return Ge(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function Kn(){let n=process.env.PROGRESS_API_URL;if(!n)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return n.replace(/\/executions\/?$/,"")}function Vn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function Xn(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function Qn(){return process.env.EXECUTION_ID||null}function Ct(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],n):n}async function Ut(n,e={}){if(!n||typeof n!="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 r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(e.timeoutMs)?e.timeoutMs:zn;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:y}=await Bt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:o}),m=Ct(y,e.output);return I.info(`[sub-graph] '${n}' completed in-process`),m}catch(y){if(y instanceof M||y?.fallback)I.info(`[sub-graph] in-process fallback for '${n}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let i=Kn(),s=Vn(),a=Xn(),l=Qn(),d=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(n)}/trigger`,E={input:e.input||{},...l?{parentExecutionId:l}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let u=Zn(),c;try{c=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(E),signal:u.signal})}catch(y){if(!j(y))throw y;let m=new Error(`Sub-graph '${n}' trigger TIMED OUT ${u.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw m.code="SUBGRAPH_TRIGGER_TIMEOUT",m.subgraph=n,m.timedOut=!0,m.cause=y,m}if(!c.ok){let y=null,m="";try{y=await c.json(),m=y?.error||y?.message||JSON.stringify(y)}catch{m=await c.text().catch(()=>"")}if(c.status===429){let g=y?.quotaInfo||{},$=new Error(`Sub-graph '${n}' 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=n,$.quotaInfo=g,$}if(c.status===400){let g=new Error(`Sub-graph '${n}' rejected input: ${m}`);throw g.code="SUBGRAPH_INVALID_INPUT",g.status=400,g.subgraph=n,g.validationErrors=y?.validationErrors||null,g.missing=y?.missing||null,g}let f=new Error(`Sub-graph '${n}' trigger rejected (${c.status}): ${m}`);throw f.code="SUBGRAPH_TRIGGER_FAILED",f.status=c.status,f.subgraph=n,f}let _;try{_=await c.json()}catch(y){if(!j(y))throw y;let m=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${u.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw m.code="SUBGRAPH_TRIGGER_TIMEOUT",m.subgraph=n,m.timedOut=!0,m.cause=y,m}let p=_?.data?.jobId||_?.jobId;if(!p)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(_).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:n};let A=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Jn,v=`${i}/executions/${encodeURIComponent(p)}`,O=Date.now()+o,h="accepted",T=0,w=null;for(;Date.now()<O;){await new Promise($=>setTimeout($,A)),T+=1;let y=qn(O),m;try{m=await fetch(v,{headers:{Authorization:`Bearer ${a}`},signal:y.signal})}catch($){w=j($)?`poll TIMED OUT ${y.label}`:$?.message||String($),I.warn(`[sub-graph] status poll for ${p} could not reach the API (${w}), will retry`);continue}if(!m.ok){if(m.status>=500){I.warn(`[sub-graph] status poll for ${p} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${m.status}`)}let f;try{f=await m.json()}catch($){w=j($)?`poll body read TIMED OUT ${y.label}`:$?.message||String($),I.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${w}), will retry`);continue}let g=f?.data||f?.execution||f;if(h=g?.status||h,Yn.has(h)){if(h!=="completed"){let W=new Error(`Sub-graph '${n}' (${p}) ended in status '${h}'`);throw W.subgraphJobId=p,W.subgraphStatus=h,W}let $=g?.finalState||g?.state||{},N=Ct($,e.output);return I.info(`[sub-graph] '${n}' (${p}) completed after ${T} polls`),N}}throw me(n,p,o,h,w)}import{existsSync as Dt,readFileSync as er}from"node:fs";import{join as He,dirname as jt}from"node:path";var Se=class{static async loadContext(e,t,r={}){let o={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=jt(He(t,e));for(let l of i){let d=await this.findAndMergeContextFiles(l,a,t);if(d){let E=l.replace(/\.[^.]+$/,"").toLowerCase();o[E]=d}}}let s=r.discovery||{};for(let[a,l]of Object.entries(s))try{let d=He(t,l);Dt(d)&&(o[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${l}': ${d.message}`)}return o}static async findAndMergeContextFiles(e,t,r){let o=[],i=t;for(;i.startsWith(r);){let s=He(i,e);if(Dt(s))try{o.unshift(await this.loadFile(s))}catch(l){console.warn(`[workflow] could not load ${e} from ${s}: ${l.message}`)}let a=jt(i);if(a===i)break;i=a}return o.length===0?null:o.every(s=>typeof s=="string")?o.join(`
34
+ ${s}`);let l=r(),u=l.cwd||process.cwd(),E=l.sessionPath;try{if(E){let h=qe(E,re);if($t(h)){let w=JSON.parse(vt(h,"utf-8"));w.currentNode=this.name,Je(h,JSON.stringify(w,null,2),"utf-8")}let f=qe(E,"..",re);if($t(f))try{let w=JSON.parse(vt(f,"utf-8"));w.currentNode=this.name,Je(f,JSON.stringify(w,null,2),"utf-8")}catch{}}}catch(h){v.debug(`[workflow] could not update session info: ${h.message}`)}let d=Ue(this.retries),c=null;for(;;)try{v.debug(`[workflow] node '${this.name}' attempt ${d.attemptsMade-1}`);let h=r().config||{},f=h.agents||{},w=this.config.agent??f[this.name]??null,O={state:r()};w&&(O.preferredAgent=w);let R={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:E,config:h,nodeName:this.name,timeout:this.config?.timeout||3e5},g=e?._coreInvokeAgent;g||(g=(await Promise.resolve().then(()=>(ze(),He))).invokeAgent);let b=await g(s,O,R),I,$;if(typeof b=="string"?(I=b,$=null):b.structured?(I=b.raw||JSON.stringify(b.structured,null,2),$=b.structured):(I=b.raw||JSON.stringify(b,null,2),$=b.extracted||null),E)try{let m=qe(E,this.name,"raw_stream_output.txt");Bn(Cn(m),{recursive:!0}),Je(m,typeof I=="string"?I:JSON.stringify(I),"utf-8")}catch(m){v.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&$){v.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify($,null,2)}`);let m=$;if(typeof this.onComplete=="function")try{m=await this.onComplete(r(),$)}catch(p){v.warn(`[workflow] onComplete hook failed: ${p.message}`)}return{success:!0,output:m,raw:I}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:I}),raw:I}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(I);return v.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),C.step("Output parsed"),{success:!0,output:m,raw:I}}return{success:!0,output:I,raw:I}}catch(h){c=h;let f=d.next(h);if(!await Ot(this.name,f,h,i))break}return{success:!1,error:c.message,raw:null,attempts:d.attemptsMade}}};ae();ae();import{mkdirSync as Fn,existsSync as ee,statSync as Dt,readdirSync as jt,rmSync as Gn}from"node:fs";import{spawn as Bt}from"node:child_process";import{join as Y}from"node:path";import{pathToFileURL as Wn}from"node:url";import{AsyncLocalStorage as Hn}from"node:async_hooks";import{AsyncLocalStorage as Un}from"node:async_hooks";var ue=new Un;function oe(){let n=ue.getStore();return n||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function Mt(n,e){let t=ue.getStore()||oe(),r=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return ue.run(r,e)}function Rt(n,e,t){let r=ue.getStore()||oe(),o=Object.freeze({...r,agent:n??r.agent??null,signal:e??r.signal??null});return ue.run(o,t)}var Ye=new Map,Ze=new Map,xt=new Map;function Pt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Ye.set(n,e),Ze.set(n,"ready"),xt.set(n,{...t,cachedAt:Date.now()})}function Nt(n,e){Ze.set(n,"failed"),xt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Ye.delete(n)}function kt(n){return Ze.get(n)==="ready"?Ye.get(n):null}function de(n,e,t=process.env){let r=Number(t[n]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):e}function Ee(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function pe(n,e){return Ee(de(n,e),n)}function G(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}var Ie=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function zn(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var k=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}};function Te(n,e,t,r="timeout",o=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${r})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=r,o&&(i.subgraphTransportError=o),i}function Jn(n,e=process.env,t=process.uptime()){let r=Number.isFinite(n)?Number(n):null,o=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,s=Number.isFinite(o)&&o>0?o-i:null;if(r===null&&s===null)return null;let a=r===null?s:s===null?r:Math.min(r,s);return Math.max(1,a)}function qn(n,e){let t=new AbortController,r=!1,o=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(o=setTimeout(()=>{r=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof o.unref=="function"&&o.unref()),{signal:t.signal,timedOut:()=>r,dispose(){o&&(clearTimeout(o),o=null),n&&n.removeEventListener("abort",i)}}}var Ct=new Hn,Ut=Promise.resolve();async function Yn(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(t.length===0)return e();let r=Ct.getStore()===!0,o=null;if(!r){let s=Ut;Ut=new Promise(a=>{o=a}),await s}let i=new Map;try{for(let[s,a]of t)i.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=a;return v.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await Ct.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;o&&o()}}function Zn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!t||!r||!o)throw new k("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:o}}async function Kn({apiBase:n,authToken:e,body:t}){let r=pe("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal})}catch(s){throw new k(G(s)?"begin-timeout":"network",G(s)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${s.message}`)}let i=null;try{i=await o.json()}catch(s){if(G(s))throw new k("begin-timeout",`begin body read TIMED OUT ${r.label}`)}if(!o.ok){if(o.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(o.status===429){let s=i?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=s,a}if(o.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new k("begin-status",`begin returned ${o.status}`)}return i?.data||i}async function Q({apiBase:n,authToken:e,payload:t}){let r=pe("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal});o.ok||v.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){v.warn(`[in-process subgraph] finalize ${G(o)?`TIMED OUT ${r.label}`:`failed: ${o.message}`}`)}}async function Vn(n,e){let t=Y(e,".ready"),r=Y(e,"graph.mjs");if(ee(t)&&ee(r))return;Fn(e,{recursive:!0});let o=Y(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),l=s(o,"wx");a(l),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(ee(t)&&ee(r))return;await new Promise(a=>setTimeout(a,100))}throw new k("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let E=Math.ceil(1e4/1e3),d=Math.ceil(de("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=Bt("curl",["-fsSL","--connect-timeout",String(E),"--max-time",String(d),n],{stdio:["ignore","pipe","inherit"]}),h=Bt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(h.stdin);let f,w,O=()=>{if(f!==void 0&&w!==void 0){if(f!==0)return u(new Error(`curl exited ${f}`));if(w!==0)return u(new Error(`tar exited ${w}`));l()}};c.on("close",R=>{f=R,O()}),h.on("close",R=>{w=R,O()}),c.on("error",u),h.on("error",u)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(o)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(o)}catch{}throw new k("bundle-extract-failed",s.message)}}async function Xn(n){let e=Y(n,"graph.mjs");if(!ee(e))throw new k("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(Wn(e).href)}catch(o){throw new k("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=t.default||Object.values(t).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new k("entry-class-missing","no buildGraph() class export found");return r}async function Lt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=oe(),r;try{r=Zn()}catch(p){throw p}v.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let o=await Kn({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:E,bundleReady:d,nodeConfigs:c}=o,h=zn();if(s&&s!==h)throw await Q({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new k("runtime-mismatch",`${h} vs ${s}`);if(!d||!a)throw await Q({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new k("no-bundle","workflow bundle not built yet");let f=kt(n);if(!f){let p=Y(Ie,`${E}@${u||"0"}`);try{await Vn(a,p);try{er()}catch{}}catch(S){throw S.fallback&&await Q({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:S.message,code:S.reason}}}),S}try{f=await Xn(p),Pt(n,f,{workflowUuid:E,version:u,runtimeTag:s,cacheDir:p})}catch(S){throw Nt(n,S),await Q({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:S.message,code:S.reason||"IMPORT_FAILED"}}}),S.fallback?S:new k("import-failed",S.message)}}let w=Date.now(),O=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,R=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,g={...e.input||{},...R?{nodeConfigs:c}:{}},b=Jn(e.timeoutMs),I=qn(e.signal,b),$,m;try{$=await Yn(O,async()=>{let S=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph();return Mt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>S.run(e.parentAgent,g,{signal:I.signal}))}),m=$&&typeof $=="object"&&"state"in $?$.state:$}catch(p){let S=I.timedOut();throw await Q({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:S?"timeout":"failed",error:S?{message:`aborted at the declared ${Math.round(b/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-w}}),S?Te(n,i,b):p}finally{I.dispose()}if($&&typeof $=="object"&&$.stoppedExternally){let p=I.timedOut();if(await Q({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:p?"timeout":"canceled",finalState:m,durationMs:Date.now()-w}}),p)throw Te(n,i,b);let S=new Error(`Sub-graph '${n}' canceled by parent abort`);throw S.code="SUBGRAPH_CANCELED",S.subgraphJobId=i,S}return await Q({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:m,durationMs:Date.now()-w}}),{finalState:m,executionId:i}}function Qn(n){let e=0,t=[n];for(;t.length;){let r=t.pop(),o;try{o=Dt(r)}catch{continue}if(o.isDirectory()){let i;try{i=jt(r)}catch{continue}for(let s of i)t.push(Y(r,s))}else e+=o.size}return e}function er({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!ee(Ie))return{evicted:0,freedBytes:0};let e=jt(Ie),t=[],r=0;for(let a of e){let l=Y(Ie,a),u;try{u=Dt(l)}catch{continue}let E=u.isDirectory()?Qn(l):u.size;r+=E,t.push({name:a,full:l,size:E,mtimeMs:u.mtimeMs})}if(r<=n)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let o=Math.floor(n*.7),i=0,s=0;for(let a of t){if(r-i<=o)break;if(!ee(Y(a.full,".lock")))try{Gn(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(l){v.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return s>0&&v.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:r-i}}catch(e){return v.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var nr=2e3,rr=600*1e3,or=new Set(["completed","failed","canceled","cancelled","timeout"]);var Gt=()=>pe("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function sr(n){let e=de("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return Ee(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function Wt(){let n=process.env.PROGRESS_API_URL;if(!n)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return n.replace(/\/executions\/?$/,"")}function Ht(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function zt(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function Jt(){return process.env.EXECUTION_ID||null}function Ft(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],n):n}async function Ke(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=oe();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(e.timeoutMs)?e.timeoutMs:rr;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async&&!e.participantBindingId)try{v.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:m}=await Lt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:o}),p=Ft(m,e.output);return v.info(`[sub-graph] '${n}' completed in-process`),p}catch(m){if(m instanceof k||m?.fallback)v.info(`[sub-graph] in-process fallback for '${n}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let i=Wt(),s=Ht(),a=zt(),l=Jt(),u=e.participantBindingId?"participant":n,E=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(u)}/trigger`,d={input:e.input||{},...l?{parentExecutionId:l}:{},...e.conversationId?{conversationId:e.conversationId}:{},...typeof e.idempotencyKey=="string"&&e.idempotencyKey?{idempotencyKey:e.idempotencyKey.slice(0,200)}:{},...e.participantBindingId?{participantBindingId:e.participantBindingId}:{},...e.protocolId?{protocolId:e.protocolId}:{}};v.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let c=Gt(),h;try{h=await fetch(E,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(d),signal:c.signal})}catch(m){if(!G(m))throw m;let p=new Error(`Sub-graph '${n}' trigger TIMED OUT ${c.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw p.code="SUBGRAPH_TRIGGER_TIMEOUT",p.subgraph=n,p.timedOut=!0,p.cause=m,p}if(!h.ok){let m=null,p="";try{m=await h.json(),p=m?.error||m?.message||JSON.stringify(m)}catch{p=await h.text().catch(()=>"")}if(h.status===429){let y=m?.quotaInfo||{},M=new Error(`Sub-graph '${n}' blocked by execution quota (${y.used??"?"}/${y.limit??"?"} on plan ${y.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=n,M.quotaInfo=y,M}if(h.status===400){let y=new Error(`Sub-graph '${n}' rejected input: ${p}`);throw y.code="SUBGRAPH_INVALID_INPUT",y.status=400,y.subgraph=n,y.validationErrors=m?.validationErrors||null,y.missing=m?.missing||null,y}let S=new Error(`Sub-graph '${n}' trigger rejected (${h.status}): ${p}`);throw S.code="SUBGRAPH_TRIGGER_FAILED",S.status=h.status,S.subgraph=n,S}let f;try{f=await h.json()}catch(m){if(!G(m))throw m;let p=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${c.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw p.code="SUBGRAPH_TRIGGER_TIMEOUT",p.subgraph=n,p.timedOut=!0,p.cause=m,p}let w=f?.data?.jobId||f?.jobId;if(!w)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(f).slice(0,200)}`);if(e.async)return v.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${w} (not waiting)`),{jobId:w,status:"accepted",workflow:n};let O=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:nr,R=`${i}/executions/${encodeURIComponent(w)}`,g=Date.now()+o,b="accepted",I=0,$=null;for(;Date.now()<g;){await new Promise(M=>setTimeout(M,O)),I+=1;let m=sr(g),p;try{p=await fetch(R,{headers:{Authorization:`Bearer ${a}`},signal:m.signal})}catch(M){$=G(M)?`poll TIMED OUT ${m.label}`:M?.message||String(M),v.warn(`[sub-graph] status poll for ${w} could not reach the API (${$}), will retry`);continue}if(!p.ok){if(p.status>=500){v.warn(`[sub-graph] status poll for ${w} returned ${p.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${w}: ${p.status}`)}let S;try{S=await p.json()}catch(M){$=G(M)?`poll body read TIMED OUT ${m.label}`:M?.message||String(M),v.warn(`[sub-graph] status poll for ${w} returned an unreadable body (${$}), will retry`);continue}let y=S?.data||S?.execution||S;if(b=y?.status||b,or.has(b)){if(b!=="completed"){let T=new Error(`Sub-graph '${n}' (${w}) ended in status '${b}'`);throw T.subgraphJobId=w,T.subgraphStatus=b,T}let M=y?.finalState||y?.state||{},W=Ft(M,e.output);return v.info(`[sub-graph] '${n}' (${w}) completed after ${I} polls`),W}}try{let m=Ee(500,"SUBGRAPH_CANCEL_TIMEOUT_MS"),p=await fetch(`${R}/cancel`,{method:"POST",headers:{Authorization:`Bearer ${a}`},signal:m.signal});!p.ok&&p.status!==400&&p.status!==404&&v.warn(`[sub-graph] best-effort cancel for ${w} returned ${p.status}`)}catch(m){v.warn(`[sub-graph] best-effort cancel for ${w} failed: ${m?.message||String(m)}`)}throw Te(n,w,o,b,$)}async function qt(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchParticipant: bindingId (string) is required");if(!e.protocolId||typeof e.protocolId!="string")throw new Error("dispatchParticipant: protocolId (string) is required");return Ke("participant",{...e,async:e.async!==!1,participantBindingId:n})}async function Yt(n){if(!n||typeof n!="string")throw new Error("listParticipants: protocolId (string) is required");let e=Wt(),t=Ht(),r=zt(),o=Jt();if(!o){let u=new Error("Collaboration requires a running parent execution");throw u.code="PARENT_EXECUTION_REQUIRED",u}let i=`${e}/projects/${encodeURIComponent(t)}/workflows/participant/trigger`,s=Gt(),a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({participantOperation:"list",parentExecutionId:o,protocolId:n}),signal:s.signal})}catch(u){let E=new Error(`Participant roster lookup failed: ${u?.message||String(u)}`);throw E.code=G(u)?"PARTICIPANT_ROSTER_TIMEOUT":"PARTICIPANT_ROSTER_UNAVAILABLE",E.cause=u,E}let l=null;try{l=await a.json()}catch{}if(!a.ok){let u=new Error(l?.error||`Participant roster lookup rejected (${a.status})`);throw u.code=l?.code||"PARTICIPANT_ROSTER_REJECTED",u.status=a.status,u}return Array.isArray(l?.participants)?l.participants:[]}var ir=8*6e4,ar=10*6e4,cr=2*6e4;function lr(n=process.env,e=process.uptime()){let t=Number(n?.MAX_WORKFLOW_DURATION_MS);return!Number.isFinite(t)||t<=0?null:Math.max(0,t-Math.ceil(Number(e||0)*1e3))}function Zt(n,e,t=Number.MAX_SAFE_INTEGER){let r=Number(n);return Number.isFinite(r)&&r>0?Math.min(Math.floor(r),t):e}function fe(n,e,t={}){return{requested:!0,required:n===!0,observed:!1,status:n===!0?"incomplete":"skipped",reason:e,contributions:[],disagreements:[],...t}}function ur(n,e,t){return{participant:n.displayName||n.id,participantId:n.id,vendor:n.vendor||null,phase:e,revision:0,contribution:t}}function Kt(n,e,t){return n.find(r=>Array.isArray(r.roles)&&r.roles.includes(e))||t}var dr=["claims","assumptions","risks","objections","decisions","evidenceGaps","recommendations","artifactRefs"];function pr(n,e,t){let r=n;if(typeof r=="string")try{r=JSON.parse(r)}catch{r=null}if(!(r&&typeof r=="object"&&!Array.isArray(r)&&r.phase===e&&r.role===t&&r.contextRevision===0&&typeof r.summary=="string"&&dr.every(i=>Array.isArray(r[i])))){let i=new Error(`Participant returned invalid ${e} protocol output`);throw i.code="PARTICIPANT_OUTPUT_INVALID",i}return r}async function Vt(n={},e={}){let t=String(n.protocolId||"discuss.v1"),r=String(n.objective||"").trim(),o=String(n.context||""),i=n.required===!0,s=Zt(n.timeoutMs,ir,ar),a=Zt(n.reserveMs,cr,15*6e4),l=(e.remainingWorkflowTimeMs||lr)();if(!r)return fe(i,"objective_missing",{protocolId:t});if(l!=null&&l<s+a)return fe(i,"insufficient_execution_time",{protocolId:t,remainingMs:l,requiredMs:s+a});let u=e.listParticipants||Yt,E=e.dispatchParticipant||qt,d;try{d=await u(t)}catch(T){return fe(i,T?.code||"participant_roster_unavailable",{protocolId:t,detail:T?.message||String(T)})}let c=d.filter(T=>T?.available===!1),h=d.filter(T=>T&&T.available!==!1&&T.id);if(h.length===0)return fe(i,"no_available_participants",{protocolId:t,unavailable:c});let f=Date.now(),w=f+s,O=[],R=[],g=async(T,j,Z,he=[])=>{let se=w-Date.now();if(se<1e3){let q=new Error("Collaboration node exhausted its authored timeout");throw q.code="COLLABORATION_TIMEOUT",q}let A=Number(T?.limits?.maxExecutionMinutes)*6e4,_=Number.isFinite(A)&&A>0?Math.min(se,A):se,B,U=null;for(let q=0;q<2;q+=1){let ie=q===1?"Your previous attempt did not satisfy the JSON protocol. Return exactly one valid JSON object with every required array field and no Markdown, preface, trailing commas, or comments.":"",Oe=await E(T.id,{async:!1,protocolId:t,timeoutMs:Math.min(_,Math.max(1e3,w-Date.now())),output:"contribute",input:{objective:r,protocolId:t,phase:j,role:Z,contextRevision:0,sharedContext:o,priorContributions:he,...n.instruction||ie?{instruction:[n.instruction,ie].filter(Boolean).join(`
35
+ `).slice(0,4e3)}:{}}});try{B=pr(Oe,j,Z),U=null;break}catch(ge){U=ge}}if(U)throw U;let J=ur(T,j,B);return O.push(J),J},b=Kt(h,"draft",h[0]),I;try{I=await g(b,"draft","drafter")}catch(T){R.push({participantId:b.id,phase:"draft",code:T?.code||"PARTICIPANT_FAILED",detail:T?.message||String(T)});let j=fe(i,"draft_failed",{protocolId:t,unavailable:c,failures:R,durationMs:Date.now()-f});return i&&(j.status="incomplete"),j}let $=h.filter(T=>T.id!==b.id);$.length===0&&($=[b]);let m=await Promise.allSettled($.map(T=>g(T,"critique","critic",[I]))),p=[];m.forEach((T,j)=>{T.status==="fulfilled"?p.push(T.value):R.push({participantId:$[j].id,phase:"critique",code:T.reason?.code||"PARTICIPANT_FAILED",detail:T.reason?.message||String(T.reason)})});let S=Kt(h,"synthesize",b),y=null;try{y=await g(S,"synthesize","synthesizer",[I,...p])}catch(T){R.push({participantId:S.id,phase:"synthesize",code:T?.code||"PARTICIPANT_FAILED",detail:T?.message||String(T)})}let M=p.length>0&&y!=null,W=(y?.contribution?.decisions||[]).filter(T=>T?.status==="unresolved");return{requested:!0,required:i,observed:M,status:M?"completed":"incomplete",reason:M?null:"required_phase_incomplete",protocolId:t,contributions:O,synthesis:y?.contribution||null,disagreements:W,failures:R,unavailable:c,durationMs:Date.now()-f}}import{existsSync as Xt,readFileSync as fr}from"node:fs";import{join as Ve,dirname as Qt}from"node:path";var ve=class{static async loadContext(e,t,r={}){let o={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Qt(Ve(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let E=l.replace(/\.[^.]+$/,"").toLowerCase();o[E]=u}}}let s=r.discovery||{};for(let[a,l]of Object.entries(s))try{let u=Ve(t,l);Xt(u)&&(o[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return o}static async findAndMergeContextFiles(e,t,r){let o=[],i=t;for(;i.startsWith(r);){let s=Ve(i,e);if(Xt(s))try{o.unshift(await this.loadFile(s))}catch(l){console.warn(`[workflow] could not load ${e} from ${s}: ${l.message}`)}let a=Qt(i);if(a===i)break;i=a}return o.length===0?null:o.every(s=>typeof s=="string")?o.join(`
35
36
 
36
37
  ---
37
38
 
38
- `):o.every(s=>typeof s=="object")?Object.assign({},...o):o[o.length-1]}static async loadFile(e){let t=er(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),o=await import(r(e).href);return o.default||o}return t}};import{mkdirSync as Ht,existsSync as We,writeFileSync as Lt,unlinkSync as tr}from"node:fs";import{join as K,resolve as Wt}from"node:path";import{config as nr}from"dotenv";import{zodToJsonSchema as Ft}from"zod-to-json-schema";import{z as _e}from"zod";import rr from"handlebars";function or({traceFrom:n,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:o}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${n} pid=${process.pid} ppid=${s} sessionId=${e} source=${r} mkdir=${o?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let E=(new Error("session trace").stack||"").split(`
39
+ `):o.every(s=>typeof s=="object")?Object.assign({},...o):o[o.length-1]}static async loadFile(e){let t=fr(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),o=await import(r(e).href);return o.default||o}return t}};import{mkdirSync as rn,existsSync as Xe,writeFileSync as en,unlinkSync as hr}from"node:fs";import{join as te,resolve as on}from"node:path";import{config as gr}from"dotenv";import{zodToJsonSchema as tn}from"zod-to-json-schema";import{z as $e}from"zod";import mr from"handlebars";function yr({traceFrom:n,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:o}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${n} pid=${process.pid} ppid=${s} sessionId=${e} source=${r} mkdir=${o?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let E=(new Error("session trace").stack||"").split(`
39
40
  `).slice(2,14).join(`
40
41
  `);console.log(`[zibby:session] stack (${n}):
41
- ${E}`)}}function sr(){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 ir(){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 Wt(String(e).trim())}catch{return String(e).trim()}}function ar(){sr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function cr({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function lr(n={}){let e=ut.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,o=n.paths?.sessionPrefix;return o?`${o}_${r}`:r}function ur({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let o=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let d=Wt(String(process.env.ZIBBY_SESSION_PATH));d&&(o=d,s="ZIBBY_SESSION_PATH")}catch{}let a;if(o)a=String(o).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,s="ZIBBY_SESSION_ID";else{let u=e.sessionId!=null?String(e.sessionId).trim():"";u&&u!=="last"?(a=u,s="config.sessionId"):(a=lr(e),s="generated")}i=i??Date.now();let E=e.paths?.output||he;o=K(n,E,ct,a)}let l=!We(o);return l&&Ht(o,{recursive:!0}),(l||s!=="initialState.sessionPath")&&or({traceFrom:r,sessionId:a,sessionPath:o,idSource:s,mkdirFresh:l}),cr({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var Gt=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof G)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async d=>{let E=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,u;return typeof s.input=="function"?u=s.input(E):s.input&&typeof s.input=="object"?u=s.input:u={},Ut(s.workflow,{input:u,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(E):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:E?._signal,parentAgent:d?.agent})}},l=new G(a);return l.name=e,this.nodes.set(e,l),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let o=!(t instanceof G)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof G?t:new G(o?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){let r=this.edges.get(e);return r===void 0?this.edges.set(e,t):typeof r=="string"?r!==t&&this.edges.set(e,[r,t]):Array.isArray(r)?r.includes(t)||r.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){let o=this.edges.get(e);return o!==void 0&&!o.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(o)?o.join(", "):o}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,r=i=>{t.set(i,1);for(let s of this._simpleTargets(i)){if(!s||s==="END")continue;let a=t.get(s)||0;a===1?e.add(`${i}->${s}`):a===0&&r(s)}t.set(i,2)};this.entryPoint&&r(this.entryPoint);let o=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||o.set(s,(o.get(s)||0)+1);return{backEdges:e,joinDegree:o}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,o,i){let s=r;for(let a=e.length-1;a>=0;a--){let l=e[a],d=s;s=()=>l(t,d,o,i)}return s()}serialize(){let e=[],t={};for(let[u,c]of this.nodes){let _=this.nodeTypeMap.get(u)||(c?.config?._isRouter===!0?"decision":u);e.push({id:u,type:_,data:{nodeType:_,label:u}});let p={};c._isCustomCode&&typeof c.execute=="function"&&(p.customCode=c.execute.toString());let A=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;A&&(p.description=A);let v=this.nodePrompts.get(u);if(v)p.prompt=v;else if(typeof c.prompt=="function")try{let f=c.prompt({});typeof f=="string"&&f.trim()&&(p.prompt=f,p.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(p.executeCode=c.customExecute.toString());let O=c?.config?.dispatchesWorkflow;if(typeof O=="string"&&O.trim())p.dispatchesWorkflow=O.trim();else if(Array.isArray(O)){let f=[...new Set(O.filter(g=>typeof g=="string").map(g=>g.trim()).filter(Boolean))];f.length&&(p.dispatchesWorkflow=f)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(p.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let f=null;if(typeof _e?.toJSONSchema=="function")try{f=_e.toJSONSchema(c.outputSchema)}catch{}if(!f)try{f=Ft(c.outputSchema,{target:"openApi3"})}catch{}p.outputSchema=f?{jsonSchema:f,variables:this._flattenJsonSchemaToVariables(f)}:{schema:c.outputSchema}}else p.outputSchema={schema:c.outputSchema};let h=(this.resolvedToolsMap||{})[u];h?.toolIds&&(p.tools=h.toolIds);let T=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;T&&T.length>0&&(p.skills=[...T]);let w=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;w&&w.length>0&&(p.plugins=w.map(f=>f&&typeof f=="object"?{...f}:f));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(p.stores=y.map(f=>f&&typeof f=="object"?{...f}:f));let m=Array.isArray(c?.config?.uses)?c.config.uses:typeof c?.config?.uses=="string"?[c.config.uses]:Array.isArray(c?.uses)?c.uses:typeof c?.uses=="string"?[c.uses]:null;if(m&&m.length>0){let f=new Set,g=[];for(let $ of m){let N=typeof $=="string"?$.trim():"";!N||f.has(N)||(f.add(N),g.push(N))}g.length>0&&(p.uses=g)}Object.keys(p).length>0&&(t[u]=p)}let r=[];for(let[u,c]of this.edges)if(typeof c=="string")r.push({source:u,target:c});else if(Array.isArray(c))for(let _ of c)r.push({source:u,target:_});else if(c.conditional){let _=this.conditionalCodeMap.get(u)||c.routes.toString(),p=this._inferConditionalTargets(c.routes,c.labels),A=c.labels||{},v=this.nodes.get(u),O=v?.config?._isRouter===!0||this.nodeTypeMap.get(u)==="decision"||!v,h=u;if(!O){let T=`${u}__branch`;e.push({id:T,type:"decision",data:{nodeType:"decision",label:T}}),r.push({source:u,target:T}),h=T}for(let T of p){let w={source:h,target:T,data:{conditionalCode:_}};A[T]&&(w.label=A[T]),r.push(w)}}let o=u=>{if(!u)return null;if(typeof _e?.toJSONSchema=="function")try{return _e.toJSONSchema(u)}catch{}try{return Ft(u,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let i=0;for(let u of r)if(u.target==="END"){i+=1;let c=`END__${i}`;u.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let u of this.nodes.keys())if(!this.edges.has(u)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:u,target:c})}let s=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=o(a||this.stateSchema),d=o(this.inputSchema),E=o(this.contextSchema);return{nodes:s,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:d,contextSchema:E}}_topoOrderNodes(e,t){let r=new Map(e.map((u,c)=>[u.id,c])),o=new Map(e.map(u=>[u.id,u])),i=new Map(e.map(u=>[u.id,0])),s=new Map(e.map(u=>[u.id,[]]));for(let u of t)s.has(u.source)&&i.has(u.target)&&(s.get(u.source).push(u.target),i.set(u.target,i.get(u.target)+1));let a=new Set,l=new Set(r.keys()),d=[...l].filter(u=>i.get(u)===0),E=[];for(;E.length<e.length;){let u;if(d.length>0){if(d.sort((c,_)=>r.get(c)-r.get(_)),u=d.shift(),a.has(u))continue}else u=[...l].sort((c,_)=>r.get(c)-r.get(_))[0];a.add(u),l.delete(u),E.push(o.get(u));for(let c of s.get(u)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return E}_inferConditionalTargets(e,t){let r=e.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(r))!==null;){let d=s[2]!==void 0?s[2]:s[3];d!==void 0&&d!==""&&o.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let l=new Set;for(let d of o)a.has(d)&&l.add(d);if(l.size===0){let d=/return\s+['"]([^'"]+)['"]/g,E;for(;(E=d.exec(r))!==null;)l.add(E[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let o=e.$ref.replace("#/definitions/","");r=e.definitions[o]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],o=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(o)){let l=t?`${t}.${s}`:s;r.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${l}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[o,i]of Object.entries(t))if(!(o==="success"||o==="raw"||o==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${o}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(d=>d?.passed===!0).length,l=i.some(d=>d?.passed!==void 0);r.push(l?`${o}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${o}: ${s} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(b){let S=new Error(`agent.normalizeInput() rejected the trigger input: ${b?.message||b}`);throw S.cause=b,S.code=b?.code||"NORMALIZE_INPUT_FAILED",S}let o=new AbortController;r.signal&&(r.signal.aborted?o.abort():r.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();nr({path:K(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let b=K(s,".zibby.config.js");We(b)&&(a=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let b=a?.agent;b?.provider?l=b.provider:b?.gemini?l="gemini":b?.claude?l="claude":b?.cursor?l="cursor":b?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},E=this._runtimeSchema();if(E){let b=E.safeParse(t);if(!b.success){let S=b.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),S.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${S.join(", ")}`)}P.step("State validated against schema")}let u=ir(),c=t.sessionPath||u;c||ar();let{sessionPath:_,sessionTimestamp:p,sessionId:A}=ur({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});P.step(`Session ${A}`);let v=await Se.loadContext(t.specPath||"",s,d);Object.keys(v).length>0&&P.step(`Context loaded: ${Object.keys(v).join(", ")}`);let O=t.outputPath;!O&&t.specPath&&(e?.calculateOutputPath?O=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new de({...t,config:a,agentType:l,outputPath:O,sessionPath:_,sessionTimestamp:p,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),T=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:w}=await Promise.resolve().then(()=>(Pe(),mt)),y=a.skills&&typeof a.skills=="object"?a.skills:{},m=Object.values(y).filter(b=>b&&typeof b=="object"&&typeof b.id=="string"),f=b=>{for(let S of m)if(S.id===b)return S;return w(b)},g=new Set;for(let[,b]of this.nodes)for(let S of b.config?.skills||[])g.add(S);for(let b of g){let S=f(b);if(typeof S?.middleware=="function")try{let C=await S.middleware();typeof C=="function"&&T.set(b,C)}catch{}}let{backEdges:$,joinDegree:N}=this._analyzeFlow(),W=new Map,ee=[],we=(b,S,C)=>{if(!b||b==="END")return;let L=N.get(b)||0;if(C&&L>1&&!$.has(`${S}->${b}`)){let te=(W.get(b)||0)+1;if(te<L){W.set(b,te);return}W.set(b,0)}ee.includes(b)||ee.push(b)};this.entryPoint&&ee.push(this.entryPoint);let ce=[],Je=a?.recursionLimit??100,Jt=0;try{for(;ee.length>0;){let S=ee.pop();if(!S||S==="END")continue;if(++Jt>Je)throw new Error(`Workflow exceeded recursion limit (${Je}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let C=K(_,lt);if(We(C)){try{tr(C)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
42
- \u{1F6D1} External stop requested \u2014 ending workflow.`),P.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:ce,stoppedExternally:!0};let L=this.nodes.get(S);if(!L)throw new Error(`Node '${S}' not found in graph`);let te=JSON.stringify({sessionPath:_,sessionTimestamp:p,currentNode:S,createdAt:new Date().toISOString(),config:h.get("config")}),zt=K(_,X);Lt(zt,te,"utf-8");let ze=h.get("config")?.paths?.output||he,Yt=K(s,ze,X);Ht(K(s,ze),{recursive:!0});try{Lt(Yt,te,"utf-8")}catch{}let Ye=t.onPipelineProgress;if(typeof Ye=="function")try{Ye({cwd:s,sessionPath:_,sessionId:A,outputBase:h.get("config")?.paths?.output||he,currentNode:S})}catch{}let Zt=(this.resolvedToolsMap||{})[S]||null;h.set("_currentNodeTools",Zt);let qt=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",qt[S]||{}),P.nodeStart(S);let Ze=Date.now(),le=this.nodePrompts.get(S);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(Ue(),Ce));this._invokeAgent=k.invokeAgent}let Kt=this._invokeAgent,be={},Vt=L.config?.skills||[];for(let k of Vt){let B=f(k);if(typeof B?.invokeAgentOptions=="function")try{let x=B.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:S});x&&typeof x=="object"&&(be={...be,...x})}catch(x){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${x.message}`)}}let qe=async(k,B,x={})=>{let U=Kt(k,B,{...be,...x,signal:o.signal});return U.catch(()=>{}),o.signal.aborted?U:Promise.race([U,new Promise((V,F)=>{let D=()=>{setTimeout(()=>{let Xe=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);Xe.name="AbortError",F(Xe)},i)};o.signal.addEventListener("abort",D,{once:!0})})])},Xt=async(k={},B={})=>{let x=B.prompt||"";if(le){let U=this._compiledPrompts.get(S);U||(U=rr.compile(le,{noEscape:!0}),this._compiledPrompts.set(S,U));try{x=U(k)}catch(V){throw console.error(`\u274C Template rendering failed for node '${S}':`,V.message),new Error(`Template rendering failed: ${V.message}`,{cause:V})}}else if(!x)throw new Error(`No prompt template configured for node '${S}' and no prompt provided in options`);return qe(x,{state:h.getAll(),images:B.images||[]},{model:B.model||h.get("model"),workspace:h.get("workspace"),schema:B.schema,...B,signal:o.signal,nodeName:S})},Ke=h.getAll(),Qt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of Qt)Object.prototype.hasOwnProperty.call(Ke,k)&&console.warn(`[workflow] node "${S}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ve={...Ke,state:h,invokeAgent:Xt,_coreInvokeAgent:qe,agent:e,nodeId:S,promptTemplate:le,getPromptTemplate:()=>le};try{let k=(L.config?.skills||[]).map(D=>T.get(D)).filter(Boolean),B=[...this.middleware,...k],x;x=await At(e,o.signal,async()=>B.length>0?this._composeMiddleware(B,S,async()=>L.execute(Ve,h),h.getAll(),h):L.execute(Ve,h));let U=Date.now()-Ze;if(ce.push({node:S,success:x.success,duration:U,timestamp:new Date().toISOString()}),!x.success){if(o.signal.aborted)return P.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:ce,stoppedExternally:!0};h.append("errors",{node:S,error:x.error});let D=Number.isInteger(x.attempts)&&x.attempts>0?x.attempts:(L.config?.retries||0)+1;throw P.nodeFailed(S,x.error,{duration:U}),new Error(`Node '${S}' failed after ${D} attempt(s): ${x.error}`)}h.update({[S]:x.output});let V=this._summarizeNodeOutput(S,x.output);P.nodeComplete(S,{duration:U,details:V});let F=this.edges.get(S);if(F)if(F.conditional){let D=F.routes(h.getAll());P.route(S,D),we(D,S,!1)}else if(Array.isArray(F))for(let D=F.length-1;D>=0;D--)we(F[D],S,!0);else we(F,S,!0)}catch(k){throw P.isInsideNode&&P.nodeFailed(S,k.message,{duration:Date.now()-Ze}),h.set("failed",!0),h.set("failedAt",S),k}}P.graphComplete();let b={success:!0,state:h.getAll(),executionLog:ce};return e&&typeof e.onComplete=="function"&&await e.onComplete(b),b}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(b){console.warn(`[workflow] agent.cleanup() failed: ${b.message}`)}}}};export{Gt as WorkflowGraph,ar as clearInheritedSessionEnvForFreshRun,lr as generateWorkflowSessionId,ir as readPinnedSessionPathFromEnv,ur as resolveWorkflowSession,sr as shouldTrustInheritedSessionEnv,cr as syncProcessEnvToSession};
42
+ ${E}`)}}function Sr(){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 _r(){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 on(String(e).trim())}catch{return String(e).trim()}}function wr(){Sr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function br({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Er(n={}){let e=gt.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,o=n.paths?.sessionPrefix;return o?`${o}_${r}`:r}function Ir({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let o=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let u=on(String(process.env.ZIBBY_SESSION_PATH));u&&(o=u,s="ZIBBY_SESSION_PATH")}catch{}let a;if(o)a=String(o).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,s="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,s="config.sessionId"):(a=Er(e),s="generated")}i=i??Date.now();let E=e.paths?.output||be;o=te(n,E,ft,a)}let l=!Xe(o);return l&&rn(o,{recursive:!0}),(l||s!=="initialState.sessionPath")&&yr({traceFrom:r,sessionId:a,sessionPath:o,idSource:s,mkdirFresh:l}),br({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var nn=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof H)&&t&&typeof t=="object"&&t.collaboration){let s=typeof t.collaboration=="object"?t.collaboration:{},a={name:e,_isCustomCode:!0,collaboration:{protocolId:s.protocolId||"discuss.v1",required:s.required===!0,timeoutMs:s.timeoutMs,reserveMs:s.reserveMs},description:t.description,retries:t.retries,onComplete:t.onComplete,execute:async u=>{let E=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d=(h,f="")=>typeof h=="function"?h(E):h??f,c=await Vt({protocolId:s.protocolId,required:s.required,timeoutMs:s.timeoutMs,reserveMs:s.reserveMs,objective:d(s.objective),context:d(s.context),instruction:d(s.instruction)});if(s.required===!0&&c.status!=="completed"){let h=new Error(`Required collaboration did not complete: ${c.reason||c.status}`);throw h.code="COLLABORATION_REQUIRED_INCOMPLETE",h.collaborationResult=c,h}return c}},l=new H(a);return l.name=e,this.nodes.set(e,l),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}if(!(t instanceof H)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async u=>{let E=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof s.input=="function"?d=s.input(E):s.input&&typeof s.input=="object"?d=s.input:d={},Ke(s.workflow,{input:d,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(E):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:E?._signal,parentAgent:u?.agent})}},l=new H(a);return l.name=e,this.nodes.set(e,l),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let o=!(t instanceof H)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof H?t:new H(o?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){let r=this.edges.get(e);return r===void 0?this.edges.set(e,t):typeof r=="string"?r!==t&&this.edges.set(e,[r,t]):Array.isArray(r)?r.includes(t)||r.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){let o=this.edges.get(e);return o!==void 0&&!o.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(o)?o.join(", "):o}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,r=i=>{t.set(i,1);for(let s of this._simpleTargets(i)){if(!s||s==="END")continue;let a=t.get(s)||0;a===1?e.add(`${i}->${s}`):a===0&&r(s)}t.set(i,2)};this.entryPoint&&r(this.entryPoint);let o=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||o.set(s,(o.get(s)||0)+1);return{backEdges:e,joinDegree:o}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,o,i){let s=r;for(let a=e.length-1;a>=0;a--){let l=e[a],u=s;s=()=>l(t,u,o,i)}return s()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let h=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:h,data:{nodeType:h,label:d}});let f={};c._isCustomCode&&typeof c.execute=="function"&&(f.customCode=c.execute.toString());let w=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;w&&(f.description=w);let O=c?.config?.collaboration;O&&typeof O=="object"&&(f.collaboration={protocolId:O.protocolId||"discuss.v1",required:O.required===!0,...Number.isFinite(O.timeoutMs)?{timeoutMs:O.timeoutMs}:{},...Number.isFinite(O.reserveMs)?{reserveMs:O.reserveMs}:{}});let R=c?.config?.collaborationAsync;R&&typeof R=="object"&&(f.collaborationAsync={protocolId:R.protocolId||"discuss.v1"});let g=this.nodePrompts.get(d);if(g)f.prompt=g;else if(typeof c.prompt=="function")try{let y=c.prompt({});typeof y=="string"&&y.trim()&&(f.prompt=y,f.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(f.executeCode=c.customExecute.toString());let b=c?.config?.dispatchesWorkflow;if(typeof b=="string"&&b.trim())f.dispatchesWorkflow=b.trim();else if(Array.isArray(b)){let y=[...new Set(b.filter(M=>typeof M=="string").map(M=>M.trim()).filter(Boolean))];y.length&&(f.dispatchesWorkflow=y)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(f.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let y=null;if(typeof $e?.toJSONSchema=="function")try{y=$e.toJSONSchema(c.outputSchema)}catch{}if(!y)try{y=tn(c.outputSchema,{target:"openApi3"})}catch{}f.outputSchema=y?{jsonSchema:y,variables:this._flattenJsonSchemaToVariables(y)}:{schema:c.outputSchema}}else f.outputSchema={schema:c.outputSchema};let I=(this.resolvedToolsMap||{})[d];I?.toolIds&&(f.tools=I.toolIds);let $=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;$&&$.length>0&&(f.skills=[...$]);let m=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;m&&m.length>0&&(f.plugins=m.map(y=>y&&typeof y=="object"?{...y}:y));let p=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;p&&p.length>0&&(f.stores=p.map(y=>y&&typeof y=="object"?{...y}:y));let S=Array.isArray(c?.config?.uses)?c.config.uses:typeof c?.config?.uses=="string"?[c.config.uses]:Array.isArray(c?.uses)?c.uses:typeof c?.uses=="string"?[c.uses]:null;if(S&&S.length>0){let y=new Set,M=[];for(let W of S){let T=typeof W=="string"?W.trim():"";!T||y.has(T)||(y.add(T),M.push(T))}M.length>0&&(f.uses=M)}Object.keys(f).length>0&&(t[d]=f)}let r=[];for(let[d,c]of this.edges)if(typeof c=="string")r.push({source:d,target:c});else if(Array.isArray(c))for(let h of c)r.push({source:d,target:h});else if(c.conditional){let h=this.conditionalCodeMap.get(d)||c.routes.toString(),f=this._inferConditionalTargets(c.routes,c.labels),w=c.labels||{},O=this.nodes.get(d),R=O?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!O,g=d;if(!R){let b=`${d}__branch`;e.push({id:b,type:"decision",data:{nodeType:"decision",label:b}}),r.push({source:d,target:b}),g=b}for(let b of f){let I={source:g,target:b,data:{conditionalCode:h}};w[b]&&(I.label=w[b]),r.push(I)}}let o=d=>{if(!d)return null;if(typeof $e?.toJSONSchema=="function")try{return $e.toJSONSchema(d)}catch{}try{return tn(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of r)if(d.target==="END"){i+=1;let c=`END__${i}`;d.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:d,target:c})}let s=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=o(a||this.stateSchema),u=o(this.inputSchema),E=o(this.contextSchema);return{nodes:s,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:E}}_topoOrderNodes(e,t){let r=new Map(e.map((d,c)=>[d.id,c])),o=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),s=new Map(e.map(d=>[d.id,[]]));for(let d of t)s.has(d.source)&&i.has(d.target)&&(s.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(r.keys()),u=[...l].filter(d=>i.get(d)===0),E=[];for(;E.length<e.length;){let d;if(u.length>0){if(u.sort((c,h)=>r.get(c)-r.get(h)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,h)=>r.get(c)-r.get(h))[0];a.add(d),l.delete(d),E.push(o.get(d));for(let c of s.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return E}_inferConditionalTargets(e,t){let r=e.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(r))!==null;){let u=s[2]!==void 0?s[2]:s[3];u!==void 0&&u!==""&&o.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of o)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,E;for(;(E=u.exec(r))!==null;)l.add(E[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let o=e.$ref.replace("#/definitions/","");r=e.definitions[o]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],o=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(o)){let l=t?`${t}.${s}`:s;r.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${l}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[o,i]of Object.entries(t))if(!(o==="success"||o==="raw"||o==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${o}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);r.push(l?`${o}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${o}: ${s} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(A){let _=new Error(`agent.normalizeInput() rejected the trigger input: ${A?.message||A}`);throw _.cause=A,_.code=A?.code||"NORMALIZE_INPUT_FAILED",_}let o=new AbortController;r.signal&&(r.signal.aborted?o.abort():r.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();gr({path:te(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let A=te(s,".zibby.config.js");Xe(A)&&(a=(await import(A)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let A=a?.agent;A?.provider?l=A.provider:A?.gemini?l="gemini":A?.claude?l="claude":A?.cursor?l="cursor":A?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},E=this._runtimeSchema();if(E){let A=E.safeParse(t);if(!A.success){let _=A.error.issues.map(B=>`${B.path.join(".")}: ${B.message}`);throw console.error("\u274C Initial state validation failed:"),_.forEach(B=>console.error(` - ${B}`)),new Error(`State validation failed: ${_.join(", ")}`)}C.step("State validated against schema")}let d=_r(),c=t.sessionPath||d;c||wr();let{sessionPath:h,sessionTimestamp:f,sessionId:w}=Ir({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});C.step(`Session ${w}`);let O=await ve.loadContext(t.specPath||"",s,u);Object.keys(O).length>0&&C.step(`Context loaded: ${Object.keys(O).join(", ")}`);let R=t.outputPath;!R&&t.specPath&&(e?.calculateOutputPath?R=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let g=new Se({...t,config:a,agentType:l,outputPath:R,sessionPath:h,sessionTimestamp:f,context:O,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),b=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:I}=await Promise.resolve().then(()=>(Fe(),bt)),$=a.skills&&typeof a.skills=="object"?a.skills:{},m=Object.values($).filter(A=>A&&typeof A=="object"&&typeof A.id=="string"),p=A=>{for(let _ of m)if(_.id===A)return _;return I(A)},S=new Set;for(let[,A]of this.nodes)for(let _ of A.config?.skills||[])S.add(_);for(let A of S){let _=p(A);if(typeof _?.middleware=="function")try{let B=await _.middleware();typeof B=="function"&&b.set(A,B)}catch{}}let{backEdges:y,joinDegree:M}=this._analyzeFlow(),W=new Map,T=[],j=(A,_,B)=>{if(!A||A==="END")return;let U=M.get(A)||0;if(B&&U>1&&!y.has(`${_}->${A}`)){let J=(W.get(A)||0)+1;if(J<U){W.set(A,J);return}W.set(A,0)}T.includes(A)||T.push(A)};this.entryPoint&&T.push(this.entryPoint);let Z=[],he=a?.recursionLimit??100,se=0;try{for(;T.length>0;){let _=T.pop();if(!_||_==="END")continue;if(++se>he)throw new Error(`Workflow exceeded recursion limit (${he}) \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 B=te(h,ht);if(Xe(B)){try{hr(B)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
43
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),C.step("Workflow stopped externally"),{success:!0,state:g.getAll(),executionLog:Z,stoppedExternally:!0};let U=this.nodes.get(_);if(!U)throw new Error(`Node '${_}' not found in graph`);let J=JSON.stringify({sessionPath:h,sessionTimestamp:f,currentNode:_,createdAt:new Date().toISOString(),config:g.get("config")}),q=te(h,re);en(q,J,"utf-8");let ie=g.get("config")?.paths?.output||be,Oe=te(s,ie,re);rn(te(s,ie),{recursive:!0});try{en(Oe,J,"utf-8")}catch{}let ge=t.onPipelineProgress;if(typeof ge=="function")try{ge({cwd:s,sessionPath:h,sessionId:w,outputBase:g.get("config")?.paths?.output||be,currentNode:_})}catch{}let sn=(this.resolvedToolsMap||{})[_]||null;g.set("_currentNodeTools",sn);let an=g.get("nodeConfigs")||{};g.set("_currentNodeConfig",an[_]||{}),C.nodeStart(_);let Qe=Date.now(),me=this.nodePrompts.get(_);if(!this._invokeAgent){let P=await Promise.resolve().then(()=>(ze(),He));this._invokeAgent=P.invokeAgent}let cn=this._invokeAgent,Me={},ln=U.config?.skills||[];for(let P of ln){let D=p(P);if(typeof D?.invokeAgentOptions=="function")try{let x=D.invokeAgentOptions(g.getAll(),{agentType:g.get("agentType"),nodeName:_});x&&typeof x=="object"&&(Me={...Me,...x})}catch(x){console.warn(`[graph] skill '${P}' invokeAgentOptions threw: ${x.message}`)}}let et=async(P,D,x={})=>{let L=cn(P,D,{...Me,...x,signal:o.signal});return L.catch(()=>{}),o.signal.aborted?L:Promise.race([L,new Promise((ne,z)=>{let F=()=>{setTimeout(()=>{let rt=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);rt.name="AbortError",z(rt)},i)};o.signal.addEventListener("abort",F,{once:!0})})])},un=async(P={},D={})=>{let x=D.prompt||"";if(me){let L=this._compiledPrompts.get(_);L||(L=mr.compile(me,{noEscape:!0}),this._compiledPrompts.set(_,L));try{x=L(P)}catch(ne){throw console.error(`\u274C Template rendering failed for node '${_}':`,ne.message),new Error(`Template rendering failed: ${ne.message}`,{cause:ne})}}else if(!x)throw new Error(`No prompt template configured for node '${_}' and no prompt provided in options`);return et(x,{state:g.getAll(),images:D.images||[]},{model:D.model||g.get("model"),workspace:g.get("workspace"),schema:D.schema,...D,signal:o.signal,nodeName:_})},tt=g.getAll(),dn=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let P of dn)Object.prototype.hasOwnProperty.call(tt,P)&&console.warn(`[workflow] node "${_}": state key "${P}" is shadowed by the engine context prop; read it via context.state.get('${P}')`);let nt={...tt,state:g,invokeAgent:un,_coreInvokeAgent:et,agent:e,nodeId:_,promptTemplate:me,getPromptTemplate:()=>me};try{let P=(U.config?.skills||[]).map(F=>b.get(F)).filter(Boolean),D=[...this.middleware,...P],x;x=await Rt(e,o.signal,async()=>D.length>0?this._composeMiddleware(D,_,async()=>U.execute(nt,g),g.getAll(),g):U.execute(nt,g));let L=Date.now()-Qe;if(Z.push({node:_,success:x.success,duration:L,timestamp:new Date().toISOString()}),!x.success){if(o.signal.aborted)return C.step("Workflow stopped externally"),{success:!0,state:g.getAll(),executionLog:Z,stoppedExternally:!0};g.append("errors",{node:_,error:x.error});let F=Number.isInteger(x.attempts)&&x.attempts>0?x.attempts:(U.config?.retries||0)+1;throw C.nodeFailed(_,x.error,{duration:L}),new Error(`Node '${_}' failed after ${F} attempt(s): ${x.error}`)}g.update({[_]:x.output});let ne=this._summarizeNodeOutput(_,x.output);C.nodeComplete(_,{duration:L,details:ne});let z=this.edges.get(_);if(z)if(z.conditional){let F=z.routes(g.getAll());C.route(_,F),j(F,_,!1)}else if(Array.isArray(z))for(let F=z.length-1;F>=0;F--)j(z[F],_,!0);else j(z,_,!0)}catch(P){throw C.isInsideNode&&C.nodeFailed(_,P.message,{duration:Date.now()-Qe}),g.set("failed",!0),g.set("failedAt",_),P}}C.graphComplete();let A={success:!0,state:g.getAll(),executionLog:Z};return e&&typeof e.onComplete=="function"&&await e.onComplete(A),A}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(A){console.warn(`[workflow] agent.cleanup() failed: ${A.message}`)}}}};export{nn as WorkflowGraph,wr as clearInheritedSessionEnvForFreshRun,Er as generateWorkflowSessionId,_r as readPinnedSessionPathFromEnv,Ir as resolveWorkflowSession,Sr as shouldTrustInheritedSessionEnv,br as syncProcessEnvToSession};
package/dist/index.d.ts CHANGED
@@ -25,7 +25,8 @@
25
25
  * const result = await graph.run(null, { agentType: 'my-agent', cwd: process.cwd() });
26
26
  */
27
27
  export { WorkflowGraph, WorkflowGraph as Graph } from './graph.js';
28
- export { dispatchSubgraph } from './sub-graph-executor.js';
28
+ export { dispatchSubgraph, dispatchParticipant, listParticipants } from './sub-graph-executor.js';
29
+ export { runCollaboration, remainingWorkflowTimeMs } from './collaboration.js';
29
30
  export { generateWorkflowSessionId, resolveWorkflowSession, shouldTrustInheritedSessionEnv, readPinnedSessionPathFromEnv, clearInheritedSessionEnvForFreshRun, syncProcessEnvToSession, } from './graph.js';
30
31
  export { Node } from './node.js';
31
32
  export { classifyFailure, isTransientFailure, formatProviderError, providerErrorKindOf, providerErrorStatusOf, createAttemptBudget, transientRetryBudget, transientBackoffMs, transientBackoffBaseMs, PROVIDER_ERROR_KIND_CLASS, TRANSIENT_MESSAGE_PATTERNS, DEFAULT_TRANSIENT_RETRIES, MAX_TRANSIENT_RETRIES, DEFAULT_TRANSIENT_BACKOFF_MS, MAX_TRANSIENT_BACKOFF_MS, } from './failure-class.js';