@zibby/agent-workflow 2.0.3 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/graph.js CHANGED
@@ -1,42 +1,42 @@
1
- var Lt=Object.defineProperty;var ie=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Fe=(r,e)=>{for(var t in e)Lt(r,t,{get:e[t],enumerable:!0})};var Ge,Ut,le,$,Q=ie(()=>{Ge=()=>{},Ut={debug:Ge,info:Ge,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},le={impl:Ut},$={debug:(...r)=>le.impl.debug?.(...r),info:(...r)=>le.impl.info?.(...r),warn:(...r)=>le.impl.warn?.(...r),error:(...r)=>le.impl.error?.(...r)}});var et=ie(()=>{});var tt={};Fe(tt,{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(U.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).`)}}U.set(s,Object.freeze({...r})),t===void 0?te.delete(s):te.set(s,t)}function $e(r){return U.get(r)||null}function Jt(r){return U.has(r)}function zt(r){return te.get(r)||null}function Yt(){return new Map(U)}function Zt(){return Array.from(U.keys())}function qt(){U.clear(),te.clear()}var Ie,Ee,U,te,ve=ie(()=>{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);U=globalThis[Ie],te=globalThis[Ee]});var Te={};Fe(Te,{getAgentStrategy:()=>st,invokeAgent:()=>Xt,listStrategies:()=>Vt,registerStrategy:()=>Kt,resolveInvocationExtras:()=>rt,resolveInvocationModel:()=>nt});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 nt({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,w=(typeof n=="string"?n.trim():"")||null;return i||a||u||d||e.model||w||null}function rt({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 st(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=st(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,w=nt({config:i,options:t,strategyName:o.name,envModel:process.env.MODEL,nodeConfigModel:d}),c={...t,model:w,...rt({options:t,stateView:n,context:e}),config:i},l=r,m=c.skills||[];if(m.length>0&&!t.skipPromptFragments){let T=t.connectedIntegrations;if(!T){let p=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof p=="string"&&p.trim()!==""){T={};for(let b of p.split(",").map(I=>I.trim()).filter(Boolean))T[b]=!0}}let v=p=>{let b=p&&p.requiresIntegration;return!b||!T?!0:(Array.isArray(b)?b:[b]).some(E=>T[E]===!0)},f=o.name==="assistant",h=p=>p?.inProcessOnly!==!0||f,_=m.map(p=>{let b=$e(p);if(!v(b)||!h(b))return null;let I=b?.promptFragment;return typeof I=="function"?I():I}).filter(Boolean);_.length>0&&(l+=`
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
- ${_.join(`
3
+ ${T.join(`
4
4
 
5
- `)}`)}let S=n._currentNodeConfig?.stores;if(Array.isArray(S)&&S.length>0&&typeof S[0]=="object"){let T=S.length<=8,v=S.map(f=>{let h=f?.id??f?.storeId??"",_=(f?.name??"").toString().trim()||h,p=f?.type?` \xB7 ${f.type}`:"",b=(f?.description||"").toString().replace(/\s+/g," ").trim(),I=`- ${_} \xB7 ${b||"(no description)"}${p} (id: ${h})`;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&&(I+=`
6
- fields: ${E.join(", ")}`)}return I});l+=`
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&&(l+=`
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: ${l.length} chars`),o.invoke(l,c)}var Ae,F,ke=ie(()=>{et();Q();ve();Ae=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ae]||(globalThis[Ae]=[]);F=globalThis[Ae]});var Wt=new Set(["__proto__","constructor","prototype"]);function Se(r){if(Wt.has(r))throw new Error(`Invalid state key: "${r}"`)}var ae=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){Se(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let n of t)Se(n);this._history.push({...this._state});for(let n of t)this._state[n]=e[n]}append(e,t){Se(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 ce=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 ot,existsSync as it,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"),He=x.gray("\u2514"),we=x.green("\u25C6"),Je=x.hex("#c084fc")("\u25C6"),ze=x.hex("#2dd4bf")("\u25C6"),_e=x.red("\u25C6"),Ye=`${ee} `,Ze=2;function qe(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function Ke(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+=Ye,e.col=Ze,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
- ${Ye}`,e.col=Ze))}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=Ke(this._origStdoutWrite,e),process.stderr.write=Ke(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(Je,e):process.stdout.write.bind(process.stdout)(`${ee} ${Je} ${e}
30
- `)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(ze,t):process.stdout.write.bind(process.stdout)(`${ee} ${ze} ${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(` ${qe(n)}`):"";this._rawWrite(`${He} ${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(` ${qe(s)}`):"";this._rawWrite(`${_e} ${x.red(t)}`),this._rawWrite(`${He} ${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 ue=".zibby/output",Ve="sessions",Z=".session-info.json",Xe=".zibby-stop";var Fn=Object.freeze(["codebase-memory","code-scan","artifact"]),Qe=["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 ce(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=c=>t&&typeof t.get=="function"?t.get(c):e?.[c];if(typeof this.customExecute=="function"){$.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(e);return typeof c=="object"&&c!==null&&c.success===!1?{success:!1,error:c.error||"Node execution failed",raw:c.raw||null}:this.isZodSchema?($.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(c),raw:null}):{success:!0,output:c,raw:null}}catch(c){return $.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&$.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}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 c=xe(d,Z);if(it(c)){let m=JSON.parse(ot(c,"utf-8"));m.currentNode=this.name,Oe(c,JSON.stringify(m,null,2),"utf-8")}let l=xe(d,"..",Z);if(it(l))try{let m=JSON.parse(ot(l,"utf-8"));m.currentNode=this.name,Oe(l,JSON.stringify(m,null,2),"utf-8")}catch{}}}catch(c){$.debug(`[workflow] could not update session info: ${c.message}`)}let w=null;for(let c=0;c<=this.retries;c++)try{$.debug(`[workflow] node '${this.name}' attempt ${c}`);let l=n().config||{},m=l.agents||{},S=this.config.agent??m[this.name]??null,A={state:n()};S&&(A.preferredAgent=S);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:l,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),h,_;if(typeof f=="string"?(h=f,_=null):f.structured?(h=f.raw||JSON.stringify(f.structured,null,2),_=f.structured):(h=f.raw||JSON.stringify(f,null,2),_=f.extracted||null),d)try{let p=xe(d,this.name,"raw_stream_output.txt");Qt(en(p),{recursive:!0}),Oe(p,typeof h=="string"?h:JSON.stringify(h),"utf-8")}catch(p){$.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&_){$.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(_,null,2)}`);let p=_;if(typeof this.onComplete=="function")try{p=await this.onComplete(n(),_)}catch(b){$.warn(`[workflow] onComplete hook failed: ${b.message}`)}return{success:!0,output:p,raw:h}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:h}),raw:h}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(h);return $.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),P.step("Output parsed"),{success:!0,output:p,raw:h}}return{success:!0,output:h,raw:h}}catch(l){w=l,c<this.retries&&$.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:w.message,raw:null}}};Q();Q();import{mkdirSync as rn,existsSync as J,statSync as mt,readdirSync as yt,rmSync as sn}from"node:fs";import{spawn as ft}from"node:child_process";import{join as W}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 at(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 ct(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,lt=new Map;function ut(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"),lt.set(r,{...t,cachedAt:Date.now()})}function dt(r,e){Ne.set(r,"failed"),lt.set(r,{error:e?.message||String(e),failedAt:Date.now()}),Pe.delete(r)}function pt(r){return Ne.get(r)==="ready"?Pe.get(r):null}var de=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 pe(r,e,t,n="timeout"){let s=new Error(`Sub-graph '${r}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${n})`);return s.code="SUBGRAPH_TIMEOUT",s.subgraphJobId=e,s.subgraphStatus=n,s}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 ht=new an,gt=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=ht.getStore()===!0,s=null;if(!n){let i=gt;gt=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 ht.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=W(e,".ready"),n=W(e,"graph.mjs");if(J(t)&&J(n))return;rn(e,{recursive:!0});let s=W(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 w=ft("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),c=ft("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});w.stdout.pipe(c.stdin);let l,m,S=()=>{if(l!==void 0&&m!==void 0){if(l!==0)return d(new Error(`curl exited ${l}`));if(m!==0)return d(new Error(`tar exited ${m}`));u()}};w.on("close",A=>{l=A,S()}),c.on("close",A=>{m=A,S()}),w.on("error",d),c.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=W(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 St(r,e={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=q(),n;try{n=pn()}catch(I){throw I}$.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:w,bundleReady:c,nodeConfigs:l}=s,m=cn();if(i&&i!==m)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,discard:!0}}),new N("runtime-mismatch",`${m} vs ${i}`);if(!c||!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 S=pt(r);if(!S){let I=W(de,`${w}@${d||"0"}`);try{await hn(a,I);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{S=await gn(I),ut(r,S,{workflowUuid:w,version:d,runtimeTag:i,cacheDir:I})}catch(E){throw dt(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=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,f={...e.input||{},...v?{nodeConfigs:l}:{}},h=ln(e.timeoutMs),_=un(e.signal,h),p,b;try{p=await dn(T,async()=>{let E=await(typeof S=="function"&&S.prototype?.buildGraph?new S:S).buildGraph();return at({executionId:o,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>E.run(e.parentAgent,f,{signal:_.signal}))}),b=p&&typeof p=="object"&&"state"in p?p.state:p}catch(I){let E=_.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(h/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:I.message,code:I.code||"CHILD_THREW",stack:I.stack},durationMs:Date.now()-A}}),E?pe(r,o,h):I}finally{_.dispose()}if(p&&typeof p=="object"&&p.stoppedExternally){let I=_.timedOut();if(await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,status:I?"timeout":"canceled",finalState:b,durationMs:Date.now()-A}}),I)throw pe(r,o,h);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:b,durationMs:Date.now()-A}}),{finalState:b,executionId:o}}function mn(r){let e=0,t=[r];for(;t.length;){let n=t.pop(),s;try{s=mt(n)}catch{continue}if(s.isDirectory()){let o;try{o=yt(n)}catch{continue}for(let i of o)t.push(W(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(de))return{evicted:0,freedBytes:0};let e=yt(de),t=[],n=0;for(let a of e){let u=W(de,a),d;try{d=mt(u)}catch{continue}let w=d.isDirectory()?mn(u):d.size;n+=w,t.push({name:a,full:u,size:w,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(W(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 wt(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 _t(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:h}=await St(r,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:s}),_=wt(h,e.output);return $.info(`[sub-graph] '${r}' completed in-process`),_}catch(h){if(h instanceof N||h?.fallback)$.info(`[sub-graph] in-process fallback for '${r}': ${h.reason||"unknown"} \u2014 using HTTP`);else throw h}let o=bn(),i=In(),a=En(),u=$n(),d=`${o}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(r)}/trigger`,w={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 c=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(w)});if(!c.ok){let h=null,_="";try{h=await c.json(),_=h?.error||h?.message||JSON.stringify(h)}catch{_=await c.text().catch(()=>"")}if(c.status===429){let b=h?.quotaInfo||{},I=new Error(`Sub-graph '${r}' blocked by execution quota (${b.used??"?"}/${b.limit??"?"} on plan ${b.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw I.code="SUBGRAPH_QUOTA_EXCEEDED",I.status=429,I.subgraph=r,I.quotaInfo=b,I}if(c.status===400){let b=new Error(`Sub-graph '${r}' rejected input: ${_}`);throw b.code="SUBGRAPH_INVALID_INPUT",b.status=400,b.subgraph=r,b.validationErrors=h?.validationErrors||null,b.missing=h?.missing||null,b}let p=new Error(`Sub-graph '${r}' trigger rejected (${c.status}): ${_}`);throw p.code="SUBGRAPH_TRIGGER_FAILED",p.status=c.status,p.subgraph=r,p}let l=await c.json(),m=l?.data?.jobId||l?.jobId;if(!m)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return $.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${m} (not waiting)`),{jobId:m,status:"accepted",workflow:r};let S=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Sn,A=`${o}/executions/${encodeURIComponent(m)}`,T=Date.now()+s,v="accepted",f=0;for(;Date.now()<T;){await new Promise(b=>setTimeout(b,S)),f+=1;let h=await fetch(A,{headers:{Authorization:`Bearer ${a}`}});if(!h.ok){if(h.status>=500){$.warn(`[sub-graph] status poll for ${m} returned ${h.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${m}: ${h.status}`)}let _=await h.json(),p=_?.data||_?.execution||_;if(v=p?.status||v,_n.has(v)){if(v!=="completed"){let E=new Error(`Sub-graph '${r}' (${m}) ended in status '${v}'`);throw E.subgraphJobId=m,E.subgraphStatus=v,E}let b=p?.finalState||p?.state||{},I=wt(b,e.output);return $.info(`[sub-graph] '${r}' (${m}) completed after ${f} polls`),I}}throw pe(r,m,s,v)}import{existsSync as bt,readFileSync as vn}from"node:fs";import{join as Re,dirname as It}from"node:path";var fe=class{static async loadContext(e,t,n={}){let s={},o=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=It(Re(t,e));for(let u of o){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let w=u.replace(/\.[^.]+$/,"").toLowerCase();s[w]=d}}}let i=n.discovery||{};for(let[a,u]of Object.entries(i))try{let d=Re(t,u);bt(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(bt(i))try{s.unshift(await this.loadFile(i))}catch(u){console.warn(`[workflow] could not load ${e} from ${i}: ${u.message}`)}let a=It(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 At,existsSync as Be,writeFileSync as Et,unlinkSync as An}from"node:fs";import{join as z,resolve as Tt}from"node:path";import{config as Tn}from"dotenv";import{zodToJsonSchema as $t}from"zod-to-json-schema";import{z as he}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 w=(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
- ${w}`)}}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 Tt(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=Qe.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=Tt(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 c=e.sessionId!=null?String(e.sessionId).trim():"";c&&c!=="last"?(a=c,i="config.sessionId"):(a=Bn(e),i="generated")}o=o??Date.now();let w=e.paths?.output||ue;s=z(r,w,Ve,a)}let u=!Be(s);return u&&At(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 vt=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 w=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,c;return typeof i.input=="function"?c=i.input(w):i.input&&typeof i.input=="object"?c=i.input:c={},_t(i.workflow,{input:c,async:i.async===!0,conversationId:typeof i.conversationId=="function"?i.conversationId(w):i.conversationId,output:i.output,timeoutMs:i.timeoutMs,pollIntervalMs:i.pollIntervalMs,signal:w?._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[c,l]of this.nodes){let m=this.nodeTypeMap.get(c)||(l?.config?._isRouter===!0?"decision":c);e.push({id:c,type:m,data:{nodeType:m,label:c}});let S={};l._isCustomCode&&typeof l.execute=="function"&&(S.customCode=l.execute.toString());let A=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;A&&(S.description=A);let T=this.nodePrompts.get(c);if(T)S.prompt=T;else if(typeof l.prompt=="function")try{let p=l.prompt({});typeof p=="string"&&p.trim()&&(S.prompt=p,S.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(S.executeCode=l.customExecute.toString()),typeof l?.config?.dispatchesWorkflow=="string"&&l.config.dispatchesWorkflow.trim()&&(S.dispatchesWorkflow=l.config.dispatchesWorkflow.trim()),typeof l?.config?.agent=="string"&&l.config.agent.trim()&&(S.agent=l.config.agent.trim()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let p=null;if(typeof he?.toJSONSchema=="function")try{p=he.toJSONSchema(l.outputSchema)}catch{}if(!p)try{p=$t(l.outputSchema,{target:"openApi3"})}catch{}S.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:l.outputSchema}}else S.outputSchema={schema:l.outputSchema};let v=(this.resolvedToolsMap||{})[c];v?.toolIds&&(S.tools=v.toolIds);let f=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;f&&f.length>0&&(S.skills=[...f]);let h=Array.isArray(l?.config?.plugins)?l.config.plugins:Array.isArray(l?.plugins)?l.plugins:null;h&&h.length>0&&(S.plugins=h.map(p=>p&&typeof p=="object"?{...p}:p));let _=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;_&&_.length>0&&(S.stores=_.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(S).length>0&&(t[c]=S)}let n=[];for(let[c,l]of this.edges)if(typeof l=="string")n.push({source:c,target:l});else if(Array.isArray(l))for(let m of l)n.push({source:c,target:m});else if(l.conditional){let m=this.conditionalCodeMap.get(c)||l.routes.toString(),S=this._inferConditionalTargets(l.routes,l.labels),A=l.labels||{},T=this.nodes.get(c),v=T?.config?._isRouter===!0||this.nodeTypeMap.get(c)==="decision"||!T,f=c;if(!v){let h=`${c}__branch`;e.push({id:h,type:"decision",data:{nodeType:"decision",label:h}}),n.push({source:c,target:h}),f=h}for(let h of S){let _={source:f,target:h,data:{conditionalCode:m}};A[h]&&(_.label=A[h]),n.push(_)}}let s=c=>{if(!c)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(c)}catch{}try{return $t(c,{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 c of n)if(c.target==="END"){o+=1;let l=`END__${o}`;c.target=l,e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}})}for(let c of this.nodes.keys())if(!this.edges.has(c)){o+=1;let l=`END__${o}`;e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:c,target:l})}let i=this._topoOrderNodes(e,n),a=this._runtimeSchema(),u=s(a||this.stateSchema),d=s(this.inputSchema),w=s(this.contextSchema);return{nodes:i,edges:n,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:w}}_topoOrderNodes(e,t){let n=new Map(e.map((c,l)=>[c.id,l])),s=new Map(e.map(c=>[c.id,c])),o=new Map(e.map(c=>[c.id,0])),i=new Map(e.map(c=>[c.id,[]]));for(let c of t)i.has(c.source)&&o.has(c.target)&&(i.get(c.source).push(c.target),o.set(c.target,o.get(c.target)+1));let a=new Set,u=new Set(n.keys()),d=[...u].filter(c=>o.get(c)===0),w=[];for(;w.length<e.length;){let c;if(d.length>0){if(d.sort((l,m)=>n.get(l)-n.get(m)),c=d.shift(),a.has(c))continue}else c=[...u].sort((l,m)=>n.get(l)-n.get(m))[0];a.add(c),u.delete(c),w.push(s.get(c));for(let l of i.get(c)||[])o.set(l,o.get(l)-1),o.get(l)<=0&&!a.has(l)&&d.push(l)}return w}_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,w;for(;(w=d.exec(n))!==null;)u.add(w[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(y){let g=new Error(`agent.normalizeInput() rejected the trigger input: ${y?.message||y}`);throw g.cause=y,g.code=y?.code||"NORMALIZE_INPUT_FAILED",g}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 y=z(i,".zibby.config.js");Be(y)&&(a=(await import(y)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let y=a?.agent;y?.provider?u=y.provider:y?.gemini?u="gemini":y?.claude?u="claude":y?.cursor?u="cursor":y?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},w=this._runtimeSchema();if(w){let y=w.safeParse(t);if(!y.success){let g=y.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),g.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${g.join(", ")}`)}P.step("State validated against schema")}let c=Pn(),l=t.sessionPath||c;l||Nn();let{sessionPath:m,sessionTimestamp:S,sessionId:A}=Cn({cwd:i,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:t.sessionTimestamp}});P.step(`Session ${A}`);let T=await fe.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 ae({...t,config:a,agentType:u,outputPath:v,sessionPath:m,sessionTimestamp:S,context:T,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),h=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:_}=await Promise.resolve().then(()=>(ve(),tt)),p=a.skills&&typeof a.skills=="object"?a.skills:{},b=Object.values(p).filter(y=>y&&typeof y=="object"&&typeof y.id=="string"),I=y=>{for(let g of b)if(g.id===y)return g;return _(y)},E=new Set;for(let[,y]of this.nodes)for(let g of y.config?.skills||[])E.add(g);for(let y of E){let g=I(y);if(typeof g?.middleware=="function")try{let C=await g.middleware();typeof C=="function"&&h.set(y,C)}catch{}}let{backEdges:kt,joinDegree:Ot}=this._analyzeFlow(),ge=new Map,K=[],me=(y,g,C)=>{if(!y||y==="END")return;let j=Ot.get(y)||0;if(C&&j>1&&!kt.has(`${g}->${y}`)){let V=(ge.get(y)||0)+1;if(V<j){ge.set(y,V);return}ge.set(y,0)}K.includes(y)||K.push(y)};this.entryPoint&&K.push(this.entryPoint);let re=[],Ce=a?.recursionLimit??100,xt=0;try{for(;K.length>0;){let g=K.pop();if(!g||g==="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 C=z(m,Xe);if(Be(C)){try{An(C)}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(g);if(!j)throw new Error(`Node '${g}' not found in graph`);let V=JSON.stringify({sessionPath:m,sessionTimestamp:S,currentNode:g,createdAt:new Date().toISOString(),config:f.get("config")}),Pt=z(m,Z);Et(Pt,V,"utf-8");let Me=f.get("config")?.paths?.output||ue,Nt=z(i,Me,Z);At(z(i,Me),{recursive:!0});try{Et(Nt,V,"utf-8")}catch{}let je=t.onPipelineProgress;if(typeof je=="function")try{je({cwd:i,sessionPath:m,sessionId:A,outputBase:f.get("config")?.paths?.output||ue,currentNode:g})}catch{}let Rt=(this.resolvedToolsMap||{})[g]||null;f.set("_currentNodeTools",Rt);let Bt=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Bt[g]||{}),P.nodeStart(g);let De=Date.now(),se=this.nodePrompts.get(g);if(!this._invokeAgent){let O=await Promise.resolve().then(()=>(ke(),Te));this._invokeAgent=O.invokeAgent}let Ct=this._invokeAgent,ye={},Mt=j.config?.skills||[];for(let O of Mt){let R=I(O);if(typeof R?.invokeAgentOptions=="function")try{let k=R.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:g});k&&typeof k=="object"&&(ye={...ye,...k})}catch(k){console.warn(`[graph] skill '${O}' invokeAgentOptions threw: ${k.message}`)}}let Le=async(O,R,k={})=>{let M=Ct(O,R,{...ye,...k,signal:s.signal});return M.catch(()=>{}),s.signal.aborted?M:Promise.race([M,new Promise((Y,D)=>{let B=()=>{setTimeout(()=>{let X=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${o}ms`);X.name="AbortError",D(X)},o)};s.signal.addEventListener("abort",B,{once:!0})})])},jt=async(O={},R={})=>{let k=R.prompt||"";if(se){let M=this._compiledPrompts.get(g);M||(M=kn.compile(se,{noEscape:!0}),this._compiledPrompts.set(g,M));try{k=M(O)}catch(Y){throw console.error(`\u274C Template rendering failed for node '${g}':`,Y.message),new Error(`Template rendering failed: ${Y.message}`,{cause:Y})}}else if(!k)throw new Error(`No prompt template configured for node '${g}' 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:g})},We=f.getAll(),Dt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let O of Dt)Object.prototype.hasOwnProperty.call(We,O)&&console.warn(`[workflow] node "${g}": state key "${O}" is shadowed by the engine context prop; read it via context.state.get('${O}')`);let Ue={...We,state:f,invokeAgent:jt,_coreInvokeAgent:Le,agent:e,nodeId:g,promptTemplate:se,getPromptTemplate:()=>se};try{let O=(j.config?.skills||[]).map(B=>h.get(B)).filter(Boolean),R=[...this.middleware,...O],k;k=await ct(e,s.signal,async()=>R.length>0?this._composeMiddleware(R,g,async()=>j.execute(Ue,f),f.getAll(),f):j.execute(Ue,f));let M=Date.now()-De;if(re.push({node:g,success:k.success,duration:M,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:g,error:k.error});let B=j.config?.retries||0,X=`${g}_retries`,oe=f.getAll()[X]||0;if(oe<B){P.stepInfo(`Retrying (attempt ${oe+1}/${B})`),f.update({[X]:oe+1,[`${g}_raw`]:k.raw});continue}throw P.nodeFailed(g,k.error,{duration:M}),new Error(`Node '${g}' failed after ${oe} attempts: ${k.error}`)}f.update({[g]:k.output});let Y=this._summarizeNodeOutput(g,k.output);P.nodeComplete(g,{duration:M,details:Y});let D=this.edges.get(g);if(D)if(D.conditional){let B=D.routes(f.getAll());P.route(g,B),me(B,g,!1)}else if(Array.isArray(D))for(let B=D.length-1;B>=0;B--)me(D[B],g,!0);else me(D,g,!0)}catch(O){throw P.isInsideNode&&P.nodeFailed(g,O.message,{duration:Date.now()-De}),f.set("failed",!0),f.set("failedAt",g),O}}P.graphComplete();let y={success:!0,state:f.getAll(),executionLog:re};return e&&typeof e.onComplete=="function"&&await e.onComplete(y),y}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(y){console.warn(`[workflow] agent.cleanup() failed: ${y.message}`)}}}};export{vt 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};
@@ -61,7 +61,7 @@ export declare class SubgraphFallback extends Error {
61
61
  * board-runner lane does) behaves differently depending on a routing decision
62
62
  * it never made. Two places that must agree ⇒ one constructor.
63
63
  */
64
- export declare function subgraphTimeoutError(workflowName: any, jobId: any, timeoutMs: any, lastStatus?: string): any;
64
+ export declare function subgraphTimeoutError(workflowName: any, jobId: any, timeoutMs: any, lastStatus?: string, lastTransportError?: string | null): any;
65
65
  /**
66
66
  * How long an IN-PROCESS child may run, in ms — or `null` for "no deadline".
67
67
  *
@@ -1 +1 @@
1
- import{mkdirSync as Z,existsSync as b,statSync as F,readdirSync as R,rmSync as Q}from"node:fs";import{spawn as N}from"node:child_process";import{join as w}from"node:path";import{pathToFileURL as ee}from"node:url";import{AsyncLocalStorage as te}from"node:async_hooks";var P=()=>{},V={debug:P,info:P,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},B={impl:V};var m={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 Y}from"node:async_hooks";var k=new Y;function $(){let e=k.getStore();return e||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function M(e,r){let n=k.getStore()||$(),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 k.run(t,r)}var O=new Map,C=new Map,U=new Map;function D(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");O.set(e,r),C.set(e,"ready"),U.set(e,{...n,cachedAt:Date.now()})}function j(e,r){C.set(e,"failed"),U.set(e,{error:r?.message||String(r),failedAt:Date.now()}),O.delete(e)}function L(e){return C.get(e)==="ready"?O.get(e):null}var x=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function ne(){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 z(e,r,n,t="timeout"){let o=new Error(`Sub-graph '${e}' (${r}) timed out after ${Math.round(n/1e3)}s (last status: ${t})`);return o.code="SUBGRAPH_TIMEOUT",o.subgraphJobId=r,o.subgraphStatus=t,o}function re(e,r=process.env,n=process.uptime()){let t=Number.isFinite(e)?Number(e):null,o=Number(r&&r.MAX_WORKFLOW_DURATION_MS),s=Number.isFinite(n)&&n>0?n*1e3:0,a=Number.isFinite(o)&&o>0?o-s: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 oe(e,r){let n=new AbortController,t=!1,o=null,s=()=>{n.abort(e?.reason)};return e&&(e.aborted?s():e.addEventListener("abort",s,{once:!0})),r!=null&&!n.signal.aborted&&(o=setTimeout(()=>{t=!0,n.abort(new Error("sub-graph deadline exceeded"))},r),typeof o.unref=="function"&&o.unref()),{signal:n.signal,timedOut:()=>t,dispose(){o&&(clearTimeout(o),o=null),e&&e.removeEventListener("abort",s)}}}var G=new te,H=Promise.resolve();async function se(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=G.getStore()===!0,o=null;if(!t){let a=H;H=new Promise(i=>{o=i}),await a}let s=new Map;try{for(let[a,i]of n)s.set(a,Object.prototype.hasOwnProperty.call(process.env,a)?process.env[a]:void 0),process.env[a]=i;return m.debug(`[in-process subgraph] scoped ${n.length} child env var(s)${t?" (nested)":""}`),await G.run(!0,r)}finally{for(let[a,i]of s)i===void 0?delete process.env[a]:process.env[a]=i;o&&o()}}function ae(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),r=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),n=e||r,t=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!n||!t||!o)throw new l("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:n,projectId:t,authToken:o}}async function ie({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(s){throw new l("network",`begin fetch failed: ${s.message}`)}let o=null;try{o=await t.json()}catch{}if(!t.ok){if(t.status===404){let s=new Error(`Sub-graph child '${n.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(t.status===429){let s=o?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=s,a}if(t.status===400&&o?.validationErrors){let s=new Error(`Sub-graph rejected input: ${o?.error||o?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=o.validationErrors,s.missing=o.missing,s}throw new l("begin-status",`begin returned ${t.status}`)}return o?.data||o}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||m.warn(`[in-process subgraph] finalize returned ${t.status} for ${n.childExecutionId}`)}catch(t){m.warn(`[in-process subgraph] finalize failed: ${t.message}`)}}async function ce(e,r){let n=w(r,".ready"),t=w(r,"graph.mjs");if(b(n)&&b(t))return;Z(r,{recursive:!0});let o=w(r,".lock"),s=!1;try{let{openSync:a,closeSync:i}=await import("node:fs"),d=a(o,"wx");i(d),s=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!s){let a=Date.now()+3e4;for(;Date.now()<a;){if(b(n)&&b(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"]}),T=N("tar",["-xzf","-","-C",r],{stdio:["pipe","inherit","inherit"]});g.stdout.pipe(T.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()}),T.on("close",v=>{I=v,h()}),g.on("error",p),T.on("error",p)});let{writeFileSync:a,unlinkSync:i}=await import("node:fs");a(n,"");try{i(o)}catch{}}catch(a){try{let{unlinkSync:i}=await import("node:fs");i(o)}catch{}throw new l("bundle-extract-failed",a.message)}}async function ue(e){let r=w(e,"graph.mjs");if(!b(r))throw new l("entry-missing",`graph.mjs missing under ${e}`);let n;try{n=await import(ee(r).href)}catch(o){throw new l("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let t=n.default||Object.values(n).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!t)throw new l("entry-class-missing","no buildGraph() class export found");return t}async function ve(e,r={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let n=$(),t;try{t=ae()}catch(u){throw u}m.debug(`[in-process subgraph] begin '${e}' parent=${n.executionId||"<root>"}`);let o=await ie({apiBase:t.apiBase,authToken:t.authToken,body:{parentExecutionId:n.executionId,childWorkflowType:e,input:r.input||{},...r.conversationId?{conversationId:r.conversationId}:{}}}),{childExecutionId:s,runtimeTag:a,bundlePresignedUrl:i,sourcesPresignedUrl:d,workflowVersion:p,workflowUuid:g,bundleReady:T,nodeConfigs:f}=o,I=ne();if(a&&a!==I)throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:s,discard:!0}}),new l("runtime-mismatch",`${I} vs ${a}`);if(!T||!i)throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:s,discard:!0}}),new l("no-bundle","workflow bundle not built yet");let h=L(e);if(!h){let u=w(x,`${g}@${p||"0"}`);try{await ce(i,u);try{le()}catch{}}catch(c){throw c.fallback&&await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:s,status:"failed",error:{message:c.message,code:c.reason}}}),c}try{h=await ue(u),D(e,h,{workflowUuid:g,version:p,runtimeTag:a,cacheDir:u})}catch(c){throw j(e,c),await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:s,status:"failed",error:{message:c.message,code:c.reason||"IMPORT_FAILED"}}}),c.fallback?c:new l("import-failed",c.message)}}let v=Date.now(),q=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,W=f&&typeof f=="object"&&!Array.isArray(f)&&Object.keys(f).length>0,X={...r.input||{},...W?{nodeConfigs:f}:{}},S=re(r.timeoutMs),_=oe(r.signal,S),y,A;try{y=await se(q,async()=>{let c=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph();return M({executionId:s,parentExecutionId:n.executionId,conversationId:r.conversationId!==void 0?r.conversationId:n.conversationId,dispatchMode:"inprocess"},()=>c.run(r.parentAgent,X,{signal:_.signal}))}),A=y&&typeof y=="object"&&"state"in y?y.state:y}catch(u){let c=_.timedOut();throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:s,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?z(e,s,S):u}finally{_.dispose()}if(y&&typeof y=="object"&&y.stoppedExternally){let u=_.timedOut();if(await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:s,status:u?"timeout":"canceled",finalState:A,durationMs:Date.now()-v}}),u)throw z(e,s,S);let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=s,c}return await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:s,status:"completed",finalState:A,durationMs:Date.now()-v}}),{finalState:A,executionId:s}}function Ee(){try{if(!b(x))return{bytes:0,entries:0};let e=R(x),r=0;for(let n of e)try{r+=J(w(x,n))}catch{}return{bytes:r,entries:e.length}}catch{return{bytes:0,entries:0}}}function J(e){let r=0,n=[e];for(;n.length;){let t=n.pop(),o;try{o=F(t)}catch{continue}if(o.isDirectory()){let s;try{s=R(t)}catch{continue}for(let a of s)n.push(w(t,a))}else r+=o.size}return r}function le({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!b(x))return{evicted:0,freedBytes:0};let r=R(x),n=[],t=0;for(let i of r){let d=w(x,i),p;try{p=F(d)}catch{continue}let g=p.isDirectory()?J(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 o=Math.floor(e*.7),s=0,a=0;for(let i of n){if(t-s<=o)break;if(!b(w(i.full,".lock")))try{Q(i.full,{recursive:!0,force:!0}),s+=i.size,a+=1}catch(d){m.debug(`[sub-graph cache] evict skip ${i.name}: ${d.message}`)}}return a>0&&m.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:s,totalBytes:t-s}}catch(r){return m.debug(`[sub-graph cache] evict failed: ${r.message}`),{evicted:0,freedBytes:0}}}export{l as SubgraphFallback,le as evictCacheIfOver,Ee as getCacheStats,re as resolveChildTimeoutMs,ve as runInProcessSubgraph,z as subgraphTimeoutError,oe 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};