@zibby/agent-workflow 2.0.4 → 2.0.5

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