@zibby/agent-workflow 0.6.2 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
- var Yt=Object.defineProperty;var ve=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var de=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var qe=(n,e)=>{for(var t in e)Yt(n,t,{get:e[t],enumerable:!0})};var Ke,qt,he,E,F=de(()=>{Ke=()=>{},qt={debug:Ke,info:Ke,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},he={impl:qt},E={debug:(...n)=>he.impl.debug?.(...n),info:(...n)=>he.impl.info?.(...n),warn:(...n)=>he.impl.warn?.(...n),error:(...n)=>he.impl.error?.(...n)}});var at=de(()=>{});var ct={};qe(ct,{clearSkills:()=>on,getAllSkills:()=>tn,getSkill:()=>re,getSkillSource:()=>en,hasSkill:()=>Qt,listSkillIds:()=>nn,registerSkill:()=>Xt});function Xt(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:o=!1}=e,r=n.id;if(G.has(r)&&!o){let i=oe.get(r);if(!(i===t)){let a=i||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${r}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}G.set(r,Object.freeze({...n})),t===void 0?oe.delete(r):oe.set(r,t)}function re(n){return G.get(n)||null}function Qt(n){return G.has(n)}function en(n){return oe.get(n)||null}function tn(){return new Map(G)}function nn(){return Array.from(G.keys())}function on(){G.clear(),oe.clear()}var Oe,Pe,G,oe,me=de(()=>{Oe=Symbol.for("@zibby/agent-workflow.skills"),Pe=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Oe]||(globalThis[Oe]=new Map);globalThis[Pe]||(globalThis[Pe]=new Map);G=globalThis[Oe],oe=globalThis[Pe]});var se={};qe(se,{getAgentStrategy:()=>ut,invokeAgent:()=>an,listStrategies:()=>sn,registerStrategy:()=>rn,resolveInvocationModel:()=>lt});function rn(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=H.findIndex(t=>t.getName()===n.getName());e>=0?H[e]=n:H.push(n)}function sn(){return H.map(n=>n.getName())}function lt({config:n={},options:e={},strategyName:t,envModel:o}={}){let r=n.models||{},i=e.nodeName&&r[e.nodeName]||null,s=r.default||null,a=n.agent?.[t]?.model||null,u=(typeof o=="string"?o.trim():"")||null;return i||s||a||e.model||u||null}function ut(n={}){let{state:e={},preferredAgent:t=null}=n,o=t||e.agentType||process.env.AGENT_TYPE;if(!o){let i=H.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}E.debug(`[workflow] agent selection: requested=${o}`);let r=H.find(i=>i.getName()===o);if(!r){let i=H.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${i}`)}if(!r.canHandle(n))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return E.debug(`[workflow] using agent: ${r.getName()}`),r}async function an(n,e={},t={}){let o=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},r={...e,state:o},i=ut(r),s=o.config||t.config||{},a=lt({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL}),u={...t,model:a,workspace:o.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],extraMcpServers:t.extraMcpServers||o.extraMcpServers||e.extraMcpServers||[],plugins:t.plugins||e.plugins||[],config:s},d=n,h=u.skills||[];if(h.length>0&&!t.skipPromptFragments){let g=t.connectedIntegrations;if(!g){let $=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof $=="string"&&$.trim()!==""){g={};for(let b of $.split(",").map(f=>f.trim()).filter(Boolean))g[b]=!0}}let m=$=>{let b=$&&$.requiresIntegration;return!b||!g?!0:(Array.isArray(b)?b:[b]).some(y=>g[y]===!0)},S=h.map($=>{let b=re($);if(!m(b))return null;let f=b?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);S.length>0&&(d+=`
1
+ var Yt=Object.defineProperty;var ve=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var de=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var qe=(n,e)=>{for(var t in e)Yt(n,t,{get:e[t],enumerable:!0})};var Ke,qt,he,E,F=de(()=>{Ke=()=>{},qt={debug:Ke,info:Ke,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},he={impl:qt},E={debug:(...n)=>he.impl.debug?.(...n),info:(...n)=>he.impl.info?.(...n),warn:(...n)=>he.impl.warn?.(...n),error:(...n)=>he.impl.error?.(...n)}});var at=de(()=>{});var ct={};qe(ct,{clearSkills:()=>on,getAllSkills:()=>tn,getSkill:()=>re,getSkillSource:()=>en,hasSkill:()=>Qt,listSkillIds:()=>nn,registerSkill:()=>Xt});function Xt(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:o=!1}=e,r=n.id;if(G.has(r)&&!o){let i=oe.get(r);if(!(i===t)){let a=i||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${r}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}G.set(r,Object.freeze({...n})),t===void 0?oe.delete(r):oe.set(r,t)}function re(n){return G.get(n)||null}function Qt(n){return G.has(n)}function en(n){return oe.get(n)||null}function tn(){return new Map(G)}function nn(){return Array.from(G.keys())}function on(){G.clear(),oe.clear()}var Oe,Ne,G,oe,me=de(()=>{Oe=Symbol.for("@zibby/agent-workflow.skills"),Ne=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Oe]||(globalThis[Oe]=new Map);globalThis[Ne]||(globalThis[Ne]=new Map);G=globalThis[Oe],oe=globalThis[Ne]});var se={};qe(se,{getAgentStrategy:()=>ut,invokeAgent:()=>an,listStrategies:()=>sn,registerStrategy:()=>rn,resolveInvocationModel:()=>lt});function rn(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=H.findIndex(t=>t.getName()===n.getName());e>=0?H[e]=n:H.push(n)}function sn(){return H.map(n=>n.getName())}function lt({config:n={},options:e={},strategyName:t,envModel:o}={}){let r=n.models||{},i=e.nodeName&&r[e.nodeName]||null,s=r.default||null,a=n.agent?.[t]?.model||null,u=(typeof o=="string"?o.trim():"")||null;return i||s||a||e.model||u||null}function ut(n={}){let{state:e={},preferredAgent:t=null}=n,o=t||e.agentType||process.env.AGENT_TYPE;if(!o){let i=H.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}E.debug(`[workflow] agent selection: requested=${o}`);let r=H.find(i=>i.getName()===o);if(!r){let i=H.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${i}`)}if(!r.canHandle(n))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return E.debug(`[workflow] using agent: ${r.getName()}`),r}async function an(n,e={},t={}){let o=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},r={...e,state:o},i=ut(r),s=o.config||t.config||{},a=lt({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL}),u={...t,model:a,workspace:o.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],extraMcpServers:t.extraMcpServers||o.extraMcpServers||e.extraMcpServers||[],plugins:t.plugins||e.plugins||[],config:s},d=n,h=u.skills||[];if(h.length>0&&!t.skipPromptFragments){let g=t.connectedIntegrations;if(!g){let $=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof $=="string"&&$.trim()!==""){g={};for(let I of $.split(",").map(f=>f.trim()).filter(Boolean))g[I]=!0}}let m=$=>{let I=$&&$.requiresIntegration;return!I||!g?!0:(Array.isArray(I)?I:[I]).some(S=>g[S]===!0)},w=h.map($=>{let I=re($);if(!m(I))return null;let f=I?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);w.length>0&&(d+=`
2
2
 
3
- ${S.join(`
3
+ ${w.join(`
4
4
 
5
- `)}`)}let l=o._currentNodeConfig?.stores;if(Array.isArray(l)&&l.length>0&&typeof l[0]=="object"){let g=l.length<=8,m=l.map(S=>{let $=S?.id??S?.storeId??"",b=(S?.name??"").toString().trim()||$,f=S?.type?` \xB7 ${S.type}`:"",y=(S?.description||"").toString().replace(/\s+/g," ").trim(),_=`- ${b} \xB7 ${y||"(no description)"}${f} (id: ${$})`;if(g&&S?.schema&&typeof S.schema=="object"){let p=S.schema.properties&&typeof S.schema.properties=="object"?Object.keys(S.schema.properties):Object.keys(S.schema);p.length&&(_+=`
5
+ `)}`)}let l=o._currentNodeConfig?.stores;if(Array.isArray(l)&&l.length>0&&typeof l[0]=="object"){let g=l.length<=8,m=l.map(w=>{let $=w?.id??w?.storeId??"",I=(w?.name??"").toString().trim()||$,f=w?.type?` \xB7 ${w.type}`:"",S=(w?.description||"").toString().replace(/\s+/g," ").trim(),_=`- ${I} \xB7 ${S||"(no description)"}${f} (id: ${$})`;if(g&&w?.schema&&typeof w.schema=="object"){let p=w.schema.properties&&typeof w.schema.properties=="object"?Object.keys(w.schema.properties):Object.keys(w.schema);p.length&&(_+=`
6
6
  fields: ${p.join(", ")}`)}return _});d+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
@@ -14,7 +14,7 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
14
14
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
15
15
 
16
16
  ${c}
17
- `),E.debug(`[workflow] prompt length: ${d.length} chars`),i.invoke(d,u)}var Ne,H,ie=de(()=>{at();F();me();Ne=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ne]||(globalThis[Ne]=[]);H=globalThis[Ne]});var Zt=new Set(["__proto__","constructor","prototype"]);function Ae(n){if(Zt.has(n))throw new Error(`Invalid state key: "${n}"`)}var pe=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){Ae(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)Ae(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){Ae(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import J from"handlebars";var fe=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let o=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(r=>r[0]);for(let r of o)try{return this.validate(JSON.parse(r))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,r]of Object.entries(this.schema)){if(r.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&r.type){let i=typeof e[o];i!==r.type&&t.push(`Field '${o}' expected ${r.type}, got ${i}`)}if(r.validate&&o in e){let i=r.validate(e[o]);i&&t.push(`Field '${o}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
17
+ `),E.debug(`[workflow] prompt length: ${d.length} chars`),i.invoke(d,u)}var Pe,H,ie=de(()=>{at();F();me();Pe=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Pe]||(globalThis[Pe]=[]);H=globalThis[Pe]});var Zt=new Set(["__proto__","constructor","prototype"]);function Ae(n){if(Zt.has(n))throw new Error(`Invalid state key: "${n}"`)}var pe=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){Ae(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)Ae(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){Ae(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import J from"handlebars";var fe=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let o=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(r=>r[0]);for(let r of o)try{return this.validate(JSON.parse(r))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,r]of Object.entries(this.schema)){if(r.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&r.type){let i=typeof e[o];i!==r.type&&t.push(`Field '${o}' expected ${r.type}, got ${i}`)}if(r.validate&&o in e){let i=r.validate(e[o]);i&&t.push(`Field '${o}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
18
18
  ${t.join(`
19
19
  `)}`);return e}};F();import{writeFileSync as Ce,readFileSync as dt,existsSync as pt,mkdirSync as cn}from"node:fs";import{join as Re,dirname as ln}from"node:path";import x from"chalk";var Kt="__WORKFLOW_GRAPH_LOG__",ne=x.gray("\u2502"),Vt=x.gray("\u250C"),Ve=x.gray("\u2514"),Te=x.green("\u25C6"),Xe=x.hex("#c084fc")("\u25C6"),Qe=x.hex("#2dd4bf")("\u25C6"),ke=x.red("\u25C6"),et=`${ne} `,tt=2;function nt(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function ot(n,e){return(t,o,r)=>{if(typeof t!="string")return n(t,o,r);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let u=t[a];e.lineStart&&(s+=et,e.col=tt,e.lineStart=!1),u===`
20
20
  `?(s+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,s+=u):e.inEsc?(s+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,s+=u,e.col>=i&&(s+=`
@@ -31,15 +31,15 @@ ${et}`,e.col=tt))}return n(s,o,r)}}var xe=class{constructor(){this._currentNode=
31
31
  `)}stepFail(e){this._origStdoutWrite?this._writeDot(ke,x.red(e)):process.stdout.write.bind(process.stdout)(`${ne} ${ke} ${x.red(e)}
32
32
  `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Vt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:r}=t;if(r)for(let s of r)this._rawWrite(`${Te} ${s}`);let i=o?x.dim(` ${nt(o)}`):"";this._rawWrite(`${Ve} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:r}=o,i=r?x.dim(` ${nt(r)}`):"";this._rawWrite(`${ke} ${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(){}},O=new xe;var ge=".zibby/output",rt="sessions",K=".session-info.json",st=".zibby-stop";var Qn=Object.freeze(["codebase-memory","code-scan","artifact"]),it=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];J.helpers.inc||J.registerHelper("inc",n=>Number(n)+1);J.helpers.json||J.registerHelper("json",n=>JSON.stringify(n,null,2));J.helpers.eq||J.registerHelper("eq",(n,e)=>n===e);var W=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new fe(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return E.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let o=()=>t&&typeof t.getAll=="function"?t.getAll():e,r=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){E.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(E.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){return E.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&E.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=J.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(o())):i=this.prompt;let s=r("_skillHints");s&&(i=`${s}
33
33
 
34
- ${i}`);let a=o(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Re(d,K);if(pt(l)){let g=JSON.parse(dt(l,"utf-8"));g.currentNode=this.name,Ce(l,JSON.stringify(g,null,2),"utf-8")}let c=Re(d,"..",K);if(pt(c))try{let g=JSON.parse(dt(c,"utf-8"));g.currentNode=this.name,Ce(c,JSON.stringify(g,null,2),"utf-8")}catch{}}}catch(l){E.debug(`[workflow] could not update session info: ${l.message}`)}let h=null;for(let l=0;l<=this.retries;l++)try{E.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=o().config||{},g=c.agents||{},m=this.config.agent??g[this.name]??null,S={state:o()};m&&(S.preferredAgent=m);let $={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},b=e?._coreInvokeAgent;b||(b=(await Promise.resolve().then(()=>(ie(),se))).invokeAgent);let f=await b(i,S,$),y,_;if(typeof f=="string"?(y=f,_=null):f.structured?(y=f.raw||JSON.stringify(f.structured,null,2),_=f.structured):(y=f.raw||JSON.stringify(f,null,2),_=f.extracted||null),d)try{let p=Re(d,this.name,"raw_stream_output.txt");cn(ln(p),{recursive:!0}),Ce(p,typeof y=="string"?y:JSON.stringify(y),"utf-8")}catch(p){E.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&_){E.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(_,null,2)}`);let p=_;if(typeof this.onComplete=="function")try{p=await this.onComplete(o(),_)}catch(v){E.warn(`[workflow] onComplete hook failed: ${v.message}`)}return{success:!0,output:p,raw:y}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:y}),raw:y}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(y);return E.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),O.step("Output parsed"),{success:!0,output:p,raw:y}}return{success:!0,output:y,raw:y}}catch(c){h=c,l<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};F();F();import{mkdirSync as pn,existsSync as Y,statSync as It,readdirSync as Et,rmSync as fn}from"node:fs";import{spawn as wt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as hn}from"node:url";import{AsyncLocalStorage as gn}from"node:async_hooks";import{AsyncLocalStorage as un}from"node:async_hooks";var ae=new un;function V(){let n=ae.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 ft(n,e){let t=ae.getStore()||V(),o=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return ae.run(o,e)}function ht(n,e,t){let o=ae.getStore()||V(),r=Object.freeze({...o,agent:n??o.agent??null,signal:e??o.signal??null});return ae.run(r,t)}var Be=new Map,Me=new Map,gt=new Map;function mt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Be.set(n,e),Me.set(n,"ready"),gt.set(n,{...t,cachedAt:Date.now()})}function yt(n,e){Me.set(n,"failed"),gt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Be.delete(n)}function St(n){return Me.get(n)==="ready"?Be.get(n):null}var ye=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function mn(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var P=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}},_t=new gn,bt=Promise.resolve();async function yn(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(t.length===0)return e();let o=_t.getStore()===!0,r=null;if(!o){let s=bt;bt=new Promise(a=>{r=a}),await s}let i=new Map;try{for(let[s,a]of t)i.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=a;return E.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await _t.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;r&&r()}}function Sn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,o=process.env.PROJECT_ID,r=process.env.PROJECT_API_TOKEN;if(!t||!o||!r)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:r}}async function wn({apiBase:n,authToken:e,body:t}){let o;try{o=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(i){throw new P("network",`begin fetch failed: ${i.message}`)}let r=null;try{r=await o.json()}catch{}if(!o.ok){if(o.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(o.status===429){let i=r?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=i,s}if(o.status===400&&r?.validationErrors){let i=new Error(`Sub-graph rejected input: ${r?.error||r?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=r.validationErrors,i.missing=r.missing,i}throw new P("begin-status",`begin returned ${o.status}`)}return r?.data||r}async function z({apiBase:n,authToken:e,payload:t}){try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});o.ok||E.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){E.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function _n(n,e){let t=U(e,".ready"),o=U(e,"graph.mjs");if(Y(t)&&Y(o))return;pn(e,{recursive:!0});let r=U(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),u=s(r,"wx");a(u),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(Y(t)&&Y(o))return;await new Promise(a=>setTimeout(a,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let h=wt("curl",["-fsSL",n],{stdio:["ignore","pipe","inherit"]}),l=wt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(l.stdin);let c,g,m=()=>{if(c!==void 0&&g!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(g!==0)return d(new Error(`tar exited ${g}`));u()}};h.on("close",S=>{c=S,m()}),l.on("close",S=>{g=S,m()}),h.on("error",d),l.on("error",d)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(r)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(r)}catch{}throw new P("bundle-extract-failed",s.message)}}async function bn(n){let e=U(n,"graph.mjs");if(!Y(e))throw new P("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(hn(e).href)}catch(r){throw new P("import-failed",`${r?.code||r?.name||"unknown"}: ${r.message}`)}let o=t.default||Object.values(t).find(r=>typeof r=="function"&&r.prototype?.buildGraph);if(!o)throw new P("entry-class-missing","no buildGraph() class export found");return o}async function $t(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=V(),o;try{o=Sn()}catch(p){throw p}E.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let r=await wn({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:h,bundleReady:l,nodeConfigs:c}=r,g=mn();if(s&&s!==g)throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new P("runtime-mismatch",`${g} vs ${s}`);if(!l||!a)throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new P("no-bundle","workflow bundle not built yet");let m=St(n);if(!m){let p=U(ye,`${h}@${d||"0"}`);try{await _n(a,p);try{En()}catch{}}catch(v){throw v.fallback&&await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:v.message,code:v.reason}}}),v}try{m=await bn(p),mt(n,m,{workflowUuid:h,version:d,runtimeTag:s,cacheDir:p})}catch(v){throw yt(n,v),await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:v.message,code:v.reason||"IMPORT_FAILED"}}}),v.fallback?v:new P("import-failed",v.message)}}let S=Date.now(),$=r.env&&typeof r.env=="object"&&!Array.isArray(r.env)?r.env:null,b=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...b?{nodeConfigs:c}:{}},y,_;try{y=await yn($,async()=>{let v=await(typeof m=="function"&&m.prototype?.buildGraph?new m:m).buildGraph();return ft({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>v.run(e.parentAgent,f,{signal:e.signal}))}),_=y&&typeof y=="object"&&"state"in y?y.state:y}catch(p){throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-S}}),p}if(y&&typeof y=="object"&&y.stoppedExternally){await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"canceled",finalState:_,durationMs:Date.now()-S}});let p=new Error(`Sub-graph '${n}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"completed",finalState:_,durationMs:Date.now()-S}}),{finalState:_,executionId:i}}function In(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),r;try{r=It(o)}catch{continue}if(r.isDirectory()){let i;try{i=Et(o)}catch{continue}for(let s of i)t.push(U(o,s))}else e+=r.size}return e}function En({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(ye))return{evicted:0,freedBytes:0};let e=Et(ye),t=[],o=0;for(let a of e){let u=U(ye,a),d;try{d=It(u)}catch{continue}let h=d.isDirectory()?In(u):d.size;o+=h,t.push({name:a,full:u,size:h,mtimeMs:d.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let r=Math.floor(n*.7),i=0,s=0;for(let a of t){if(o-i<=r)break;if(!Y(U(a.full,".lock")))try{fn(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(u){E.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return s>0&&E.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:o-i}}catch(e){return E.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var $n=2e3,vn=600*1e3,An=new Set(["completed","failed","canceled","timeout"]);function Tn(){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 kn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function xn(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function On(){return process.env.EXECUTION_ID||null}function vt(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,o)=>t==null?t:t[o],n):n}async function At(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=V();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=o)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{E.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:_}=await $t(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=vt(_,e.output);return E.info(`[sub-graph] '${n}' completed in-process`),p}catch(_){if(_ instanceof P||_?.fallback)E.info(`[sub-graph] in-process fallback for '${n}': ${_.reason||"unknown"} \u2014 using HTTP`);else throw _}let r=Tn(),i=kn(),s=xn(),a=On(),u=`${r}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(n)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};E.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let h=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(d)});if(!h.ok){let _=null,p="";try{_=await h.json(),p=_?.error||_?.message||JSON.stringify(_)}catch{p=await h.text().catch(()=>"")}if(h.status===429){let T=_?.quotaInfo||{},M=new Error(`Sub-graph '${n}' blocked by execution quota (${T.used??"?"}/${T.limit??"?"} on plan ${T.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=n,M.quotaInfo=T,M}if(h.status===400){let T=new Error(`Sub-graph '${n}' rejected input: ${p}`);throw T.code="SUBGRAPH_INVALID_INPUT",T.status=400,T.subgraph=n,T.validationErrors=_?.validationErrors||null,T.missing=_?.missing||null,T}let v=new Error(`Sub-graph '${n}' trigger rejected (${h.status}): ${p}`);throw v.code="SUBGRAPH_TRIGGER_FAILED",v.status=h.status,v.subgraph=n,v}let l=await h.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return E.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:n};let g=Number.isFinite(e.timeoutMs)?e.timeoutMs:vn,m=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:$n,S=`${r}/executions/${encodeURIComponent(c)}`,$=Date.now()+g,b="accepted",f=0;for(;Date.now()<$;){await new Promise(T=>setTimeout(T,m)),f+=1;let _=await fetch(S,{headers:{Authorization:`Bearer ${s}`}});if(!_.ok){if(_.status>=500){E.warn(`[sub-graph] status poll for ${c} returned ${_.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${_.status}`)}let p=await _.json(),v=p?.data||p?.execution||p;if(b=v?.status||b,An.has(b)){if(b!=="completed"){let X=new Error(`Sub-graph '${n}' (${c}) ended in status '${b}'`);throw X.subgraphJobId=c,X.subgraphStatus=b,X}let T=v?.finalState||v?.state||{},M=vt(T,e.output);return E.info(`[sub-graph] '${n}' (${c}) completed after ${f} polls`),M}}let y=new Error(`Sub-graph '${n}' (${c}) timed out after ${Math.round(g/1e3)}s (last status: ${b})`);throw y.subgraphJobId=c,y.subgraphStatus=b,y}import{existsSync as Tt,readFileSync as Pn}from"node:fs";import{join as je,dirname as kt}from"node:path";var Se=class{static async loadContext(e,t,o={}){let r={},i=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=kt(je(t,e));for(let u of i){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let h=u.replace(/\.[^.]+$/,"").toLowerCase();r[h]=d}}}let s=o.discovery||{};for(let[a,u]of Object.entries(s))try{let d=je(t,u);Tt(d)&&(r[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return r}static async findAndMergeContextFiles(e,t,o){let r=[],i=t;for(;i.startsWith(o);){let s=je(i,e);if(Tt(s))try{r.unshift(await this.loadFile(s))}catch(u){console.warn(`[workflow] could not load ${e} from ${s}: ${u.message}`)}let a=kt(i);if(a===i)break;i=a}return r.length===0?null:r.every(s=>typeof s=="string")?r.join(`
34
+ ${i}`);let a=o(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Re(d,K);if(pt(l)){let g=JSON.parse(dt(l,"utf-8"));g.currentNode=this.name,Ce(l,JSON.stringify(g,null,2),"utf-8")}let c=Re(d,"..",K);if(pt(c))try{let g=JSON.parse(dt(c,"utf-8"));g.currentNode=this.name,Ce(c,JSON.stringify(g,null,2),"utf-8")}catch{}}}catch(l){E.debug(`[workflow] could not update session info: ${l.message}`)}let h=null;for(let l=0;l<=this.retries;l++)try{E.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=o().config||{},g=c.agents||{},m=this.config.agent??g[this.name]??null,w={state:o()};m&&(w.preferredAgent=m);let $={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},I=e?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(ie(),se))).invokeAgent);let f=await I(i,w,$),S,_;if(typeof f=="string"?(S=f,_=null):f.structured?(S=f.raw||JSON.stringify(f.structured,null,2),_=f.structured):(S=f.raw||JSON.stringify(f,null,2),_=f.extracted||null),d)try{let p=Re(d,this.name,"raw_stream_output.txt");cn(ln(p),{recursive:!0}),Ce(p,typeof S=="string"?S:JSON.stringify(S),"utf-8")}catch(p){E.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&_){E.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(_,null,2)}`);let p=_;if(typeof this.onComplete=="function")try{p=await this.onComplete(o(),_)}catch(v){E.warn(`[workflow] onComplete hook failed: ${v.message}`)}return{success:!0,output:p,raw:S}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:S}),raw:S}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(S);return E.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),O.step("Output parsed"),{success:!0,output:p,raw:S}}return{success:!0,output:S,raw:S}}catch(c){h=c,l<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};F();F();import{mkdirSync as pn,existsSync as Y,statSync as It,readdirSync as Et,rmSync as fn}from"node:fs";import{spawn as wt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as hn}from"node:url";import{AsyncLocalStorage as gn}from"node:async_hooks";import{AsyncLocalStorage as un}from"node:async_hooks";var ae=new un;function V(){let n=ae.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 ft(n,e){let t=ae.getStore()||V(),o=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return ae.run(o,e)}function ht(n,e,t){let o=ae.getStore()||V(),r=Object.freeze({...o,agent:n??o.agent??null,signal:e??o.signal??null});return ae.run(r,t)}var Be=new Map,Me=new Map,gt=new Map;function mt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Be.set(n,e),Me.set(n,"ready"),gt.set(n,{...t,cachedAt:Date.now()})}function yt(n,e){Me.set(n,"failed"),gt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Be.delete(n)}function St(n){return Me.get(n)==="ready"?Be.get(n):null}var ye=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function mn(){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"}},_t=new gn,bt=Promise.resolve();async function yn(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(t.length===0)return e();let o=_t.getStore()===!0,r=null;if(!o){let s=bt;bt=new Promise(a=>{r=a}),await s}let i=new Map;try{for(let[s,a]of t)i.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=a;return E.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await _t.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;r&&r()}}function Sn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,o=process.env.PROJECT_ID,r=process.env.PROJECT_API_TOKEN;if(!t||!o||!r)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:r}}async function wn({apiBase:n,authToken:e,body:t}){let o;try{o=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(i){throw new N("network",`begin fetch failed: ${i.message}`)}let r=null;try{r=await o.json()}catch{}if(!o.ok){if(o.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(o.status===429){let i=r?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=i,s}if(o.status===400&&r?.validationErrors){let i=new Error(`Sub-graph rejected input: ${r?.error||r?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=r.validationErrors,i.missing=r.missing,i}throw new N("begin-status",`begin returned ${o.status}`)}return r?.data||r}async function z({apiBase:n,authToken:e,payload:t}){try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});o.ok||E.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){E.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function _n(n,e){let t=U(e,".ready"),o=U(e,"graph.mjs");if(Y(t)&&Y(o))return;pn(e,{recursive:!0});let r=U(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),u=s(r,"wx");a(u),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(Y(t)&&Y(o))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let h=wt("curl",["-fsSL",n],{stdio:["ignore","pipe","inherit"]}),l=wt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(l.stdin);let c,g,m=()=>{if(c!==void 0&&g!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(g!==0)return d(new Error(`tar exited ${g}`));u()}};h.on("close",w=>{c=w,m()}),l.on("close",w=>{g=w,m()}),h.on("error",d),l.on("error",d)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(r)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(r)}catch{}throw new N("bundle-extract-failed",s.message)}}async function bn(n){let e=U(n,"graph.mjs");if(!Y(e))throw new N("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(hn(e).href)}catch(r){throw new N("import-failed",`${r?.code||r?.name||"unknown"}: ${r.message}`)}let o=t.default||Object.values(t).find(r=>typeof r=="function"&&r.prototype?.buildGraph);if(!o)throw new N("entry-class-missing","no buildGraph() class export found");return o}async function $t(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=V(),o;try{o=Sn()}catch(p){throw p}E.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let r=await wn({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:h,bundleReady:l,nodeConfigs:c}=r,g=mn();if(s&&s!==g)throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new N("runtime-mismatch",`${g} vs ${s}`);if(!l||!a)throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new N("no-bundle","workflow bundle not built yet");let m=St(n);if(!m){let p=U(ye,`${h}@${d||"0"}`);try{await _n(a,p);try{En()}catch{}}catch(v){throw v.fallback&&await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:v.message,code:v.reason}}}),v}try{m=await bn(p),mt(n,m,{workflowUuid:h,version:d,runtimeTag:s,cacheDir:p})}catch(v){throw yt(n,v),await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:v.message,code:v.reason||"IMPORT_FAILED"}}}),v.fallback?v:new N("import-failed",v.message)}}let w=Date.now(),$=r.env&&typeof r.env=="object"&&!Array.isArray(r.env)?r.env:null,I=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...I?{nodeConfigs:c}:{}},S,_;try{S=await yn($,async()=>{let v=await(typeof m=="function"&&m.prototype?.buildGraph?new m:m).buildGraph();return ft({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>v.run(e.parentAgent,f,{signal:e.signal}))}),_=S&&typeof S=="object"&&"state"in S?S.state:S}catch(p){throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-w}}),p}if(S&&typeof S=="object"&&S.stoppedExternally){await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"canceled",finalState:_,durationMs:Date.now()-w}});let p=new Error(`Sub-graph '${n}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"completed",finalState:_,durationMs:Date.now()-w}}),{finalState:_,executionId:i}}function In(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),r;try{r=It(o)}catch{continue}if(r.isDirectory()){let i;try{i=Et(o)}catch{continue}for(let s of i)t.push(U(o,s))}else e+=r.size}return e}function En({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(ye))return{evicted:0,freedBytes:0};let e=Et(ye),t=[],o=0;for(let a of e){let u=U(ye,a),d;try{d=It(u)}catch{continue}let h=d.isDirectory()?In(u):d.size;o+=h,t.push({name:a,full:u,size:h,mtimeMs:d.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let r=Math.floor(n*.7),i=0,s=0;for(let a of t){if(o-i<=r)break;if(!Y(U(a.full,".lock")))try{fn(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(u){E.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return s>0&&E.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:o-i}}catch(e){return E.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var $n=2e3,vn=600*1e3,An=new Set(["completed","failed","canceled","timeout"]);function Tn(){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 kn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function xn(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function On(){return process.env.EXECUTION_ID||null}function vt(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,o)=>t==null?t:t[o],n):n}async function At(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=V();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=o)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{E.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:_}=await $t(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=vt(_,e.output);return E.info(`[sub-graph] '${n}' completed in-process`),p}catch(_){if(_ instanceof N||_?.fallback)E.info(`[sub-graph] in-process fallback for '${n}': ${_.reason||"unknown"} \u2014 using HTTP`);else throw _}let r=Tn(),i=kn(),s=xn(),a=On(),u=`${r}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(n)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};E.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let h=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(d)});if(!h.ok){let _=null,p="";try{_=await h.json(),p=_?.error||_?.message||JSON.stringify(_)}catch{p=await h.text().catch(()=>"")}if(h.status===429){let T=_?.quotaInfo||{},M=new Error(`Sub-graph '${n}' blocked by execution quota (${T.used??"?"}/${T.limit??"?"} on plan ${T.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=n,M.quotaInfo=T,M}if(h.status===400){let T=new Error(`Sub-graph '${n}' rejected input: ${p}`);throw T.code="SUBGRAPH_INVALID_INPUT",T.status=400,T.subgraph=n,T.validationErrors=_?.validationErrors||null,T.missing=_?.missing||null,T}let v=new Error(`Sub-graph '${n}' trigger rejected (${h.status}): ${p}`);throw v.code="SUBGRAPH_TRIGGER_FAILED",v.status=h.status,v.subgraph=n,v}let l=await h.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return E.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:n};let g=Number.isFinite(e.timeoutMs)?e.timeoutMs:vn,m=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:$n,w=`${r}/executions/${encodeURIComponent(c)}`,$=Date.now()+g,I="accepted",f=0;for(;Date.now()<$;){await new Promise(T=>setTimeout(T,m)),f+=1;let _=await fetch(w,{headers:{Authorization:`Bearer ${s}`}});if(!_.ok){if(_.status>=500){E.warn(`[sub-graph] status poll for ${c} returned ${_.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${_.status}`)}let p=await _.json(),v=p?.data||p?.execution||p;if(I=v?.status||I,An.has(I)){if(I!=="completed"){let X=new Error(`Sub-graph '${n}' (${c}) ended in status '${I}'`);throw X.subgraphJobId=c,X.subgraphStatus=I,X}let T=v?.finalState||v?.state||{},M=vt(T,e.output);return E.info(`[sub-graph] '${n}' (${c}) completed after ${f} polls`),M}}let S=new Error(`Sub-graph '${n}' (${c}) timed out after ${Math.round(g/1e3)}s (last status: ${I})`);throw S.subgraphJobId=c,S.subgraphStatus=I,S}import{existsSync as Tt,readFileSync as Nn}from"node:fs";import{join as je,dirname as kt}from"node:path";var Se=class{static async loadContext(e,t,o={}){let r={},i=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=kt(je(t,e));for(let u of i){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let h=u.replace(/\.[^.]+$/,"").toLowerCase();r[h]=d}}}let s=o.discovery||{};for(let[a,u]of Object.entries(s))try{let d=je(t,u);Tt(d)&&(r[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return r}static async findAndMergeContextFiles(e,t,o){let r=[],i=t;for(;i.startsWith(o);){let s=je(i,e);if(Tt(s))try{r.unshift(await this.loadFile(s))}catch(u){console.warn(`[workflow] could not load ${e} from ${s}: ${u.message}`)}let a=kt(i);if(a===i)break;i=a}return r.length===0?null:r.every(s=>typeof s=="string")?r.join(`
35
35
 
36
36
  ---
37
37
 
38
- `):r.every(s=>typeof s=="object")?Object.assign({},...r):r[r.length-1]}static async loadFile(e){let t=Pn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),r=await import(o(e).href);return r.default||r}return t}};import{mkdirSync as Pt,existsSync as De,writeFileSync as xt,unlinkSync as Nn}from"node:fs";import{join as Z,resolve as Nt}from"node:path";import{config as Cn}from"dotenv";import{zodToJsonSchema as Ot}from"zod-to-json-schema";import{z as we}from"zod";import Rn from"handlebars";function Bn({traceFrom:n,sessionId:e,sessionPath:t,idSource:o,mkdirFresh:r}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${n} pid=${process.pid} ppid=${s} sessionId=${e} source=${o} mkdir=${r?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let h=(new Error("session trace").stack||"").split(`
38
+ `):r.every(s=>typeof s=="object")?Object.assign({},...r):r[r.length-1]}static async loadFile(e){let t=Nn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),r=await import(o(e).href);return r.default||r}return t}};import{mkdirSync as Nt,existsSync as De,writeFileSync as xt,unlinkSync as Pn}from"node:fs";import{join as Z,resolve as Pt}from"node:path";import{config as Cn}from"dotenv";import{zodToJsonSchema as Ot}from"zod-to-json-schema";import{z as we}from"zod";import Rn from"handlebars";function Bn({traceFrom:n,sessionId:e,sessionPath:t,idSource:o,mkdirFresh:r}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${n} pid=${process.pid} ppid=${s} sessionId=${e} source=${o} mkdir=${r?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let h=(new Error("session trace").stack||"").split(`
39
39
  `).slice(2,14).join(`
40
40
  `);console.log(`[zibby:session] stack (${n}):
41
- ${h}`)}}function Mn(){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 jn(){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 Dn(){Mn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Ln({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 Wn(n={}){let e=it.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,r=n.paths?.sessionPrefix;return r?`${r}_${o}`:o}function Un({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let r=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!r&&process.env.ZIBBY_SESSION_PATH)try{let d=Nt(String(process.env.ZIBBY_SESSION_PATH));d&&(r=d,s="ZIBBY_SESSION_PATH")}catch{}let a;if(r)a=String(r).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,s="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,s="config.sessionId"):(a=Wn(e),s="generated")}i=i??Date.now();let h=e.paths?.output||ge;r=Z(n,h,rt,a)}let u=!De(r);return u&&Pt(r,{recursive:!0}),(u||s!=="initialState.sessionPath")&&Bn({traceFrom:o,sessionId:a,sessionPath:r,idSource:s,mkdirFresh:u}),Ln({sessionPath:r,sessionId:a}),{sessionPath:r,sessionId:a,sessionTimestamp:i}}var _e=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,o={}){if(!(t instanceof W)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async d=>{let h=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof s.input=="function"?l=s.input(h):s.input&&typeof s.input=="object"?l=s.input:l={},At(s.workflow,{input:l,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(h):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:h?._signal,parentAgent:d?.agent})}},u=new W(a);return u.name=e,this.nodes.set(e,u),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let r=!(t instanceof W)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof W?t:new W(r?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),o.prompt?this.nodePrompts.set(e,o.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addEdge(e,t){let o=this.edges.get(e);return o===void 0?this.edges.set(e,t):typeof o=="string"?o!==t&&this.edges.set(e,[o,t]):Array.isArray(o)?o.includes(t)||o.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:o}={}){let r=this.edges.get(e);return r!==void 0&&!r.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(r)?r.join(", "):r}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:o}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,o=i=>{t.set(i,1);for(let s of this._simpleTargets(i)){if(!s||s==="END")continue;let a=t.get(s)||0;a===1?e.add(`${i}->${s}`):a===0&&o(s)}t.set(i,2)};this.entryPoint&&o(this.entryPoint);let r=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||r.set(s,(r.get(s)||0)+1);return{backEdges:e,joinDegree:r}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,r,i){let s=o;for(let a=e.length-1;a>=0;a--){let u=e[a],d=s;s=()=>u(t,d,r,i)}return s()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let g=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:g,data:{nodeType:g,label:l}});let m={};c._isCustomCode&&typeof c.execute=="function"&&(m.customCode=c.execute.toString());let S=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;S&&(m.description=S);let $=this.nodePrompts.get(l);if($)m.prompt=$;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(m.prompt=p,m.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(m.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(m.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof we?.toJSONSchema=="function")try{p=we.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Ot(c.outputSchema,{target:"openApi3"})}catch{}m.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else m.outputSchema={schema:c.outputSchema};let b=(this.resolvedToolsMap||{})[l];b?.toolIds&&(m.tools=b.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(m.skills=[...f]);let y=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;y&&y.length>0&&(m.plugins=y.map(p=>p&&typeof p=="object"?{...p}:p));let _=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;_&&_.length>0&&(m.stores=_.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(m).length>0&&(t[l]=m)}let o=[];for(let[l,c]of this.edges)if(typeof c=="string")o.push({source:l,target:c});else if(Array.isArray(c))for(let g of c)o.push({source:l,target:g});else if(c.conditional){let g=this.conditionalCodeMap.get(l)||c.routes.toString(),m=this._inferConditionalTargets(c.routes,c.labels),S=c.labels||{},$=this.nodes.get(l),b=$?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!$,f=l;if(!b){let y=`${l}__branch`;e.push({id:y,type:"decision",data:{nodeType:"decision",label:y}}),o.push({source:l,target:y}),f=y}for(let y of m){let _={source:f,target:y,data:{conditionalCode:g}};S[y]&&(_.label=S[y]),o.push(_)}}let r=l=>{if(!l)return null;if(typeof we?.toJSONSchema=="function")try{return we.toJSONSchema(l)}catch{}try{return Ot(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let i=0;for(let l of o)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"}}),o.push({source:l,target:c})}let s=this._topoOrderNodes(e,o),a=this._runtimeSchema(),u=r(a||this.stateSchema),d=r(this.inputSchema),h=r(this.contextSchema);return{nodes:s,edges:o,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:h}}_topoOrderNodes(e,t){let o=new Map(e.map((l,c)=>[l.id,c])),r=new Map(e.map(l=>[l.id,l])),i=new Map(e.map(l=>[l.id,0])),s=new Map(e.map(l=>[l.id,[]]));for(let l of t)s.has(l.source)&&i.has(l.target)&&(s.get(l.source).push(l.target),i.set(l.target,i.get(l.target)+1));let a=new Set,u=new Set(o.keys()),d=[...u].filter(l=>i.get(l)===0),h=[];for(;h.length<e.length;){let l;if(d.length>0){if(d.sort((c,g)=>o.get(c)-o.get(g)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,g)=>o.get(c)-o.get(g))[0];a.add(l),u.delete(l),h.push(r.get(l));for(let c of s.get(l)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return h}_inferConditionalTargets(e,t){let o=e.toString(),r=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(o))!==null;){let d=s[2]!==void 0?s[2]:s[3];d!==void 0&&d!==""&&r.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let u=new Set;for(let d of r)a.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=d.exec(o))!==null;)u.add(h[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let r=e.$ref.replace("#/definitions/","");o=e.definitions[r]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],r=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(r)){let u=t?`${t}.${s}`:s;o.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${u}[]`))}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[r,i]of Object.entries(t))if(!(r==="success"||r==="raw"||r==="nextNode")){if(typeof i=="string"&&i.length<=80)o.push(`${r}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(d=>d?.passed===!0).length,u=i.some(d=>d?.passed!==void 0);o.push(u?`${r}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${r}: ${s} items`)}if(o.length>=4)break}return o}async run(e,t={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t)&&(t=e.normalizeInput(t)??t);let r=new AbortController;o.signal&&(o.signal.aborted?r.abort():o.signal.addEventListener("abort",()=>r.abort(),{once:!0}));let i=o.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();Cn({path:Z(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let I=Z(s,".zibby.config.js");De(I)&&(a=(await import(I)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let I=a?.agent;I?.provider?u=I.provider:I?.gemini?u="gemini":I?.claude?u="claude":I?.cursor?u="cursor":I?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},h=this._runtimeSchema();if(h){let I=h.safeParse(t);if(!I.success){let w=I.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),w.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${w.join(", ")}`)}O.step("State validated against schema")}let l=jn(),c=t.sessionPath||l;c||Dn();let{sessionPath:g,sessionTimestamp:m,sessionId:S}=Un({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${S}`);let $=await Se.loadContext(t.specPath||"",s,d);Object.keys($).length>0&&O.step(`Context loaded: ${Object.keys($).join(", ")}`);let b=t.outputPath;!b&&t.specPath&&(e?.calculateOutputPath?b=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new pe({...t,config:a,agentType:u,outputPath:b,sessionPath:g,sessionTimestamp:m,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:r.signal}),y=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:_}=await Promise.resolve().then(()=>(me(),ct)),p=a.skills&&typeof a.skills=="object"?a.skills:{},v=Object.values(p).filter(I=>I&&typeof I=="object"&&typeof I.id=="string"),T=I=>{for(let w of v)if(w.id===I)return w;return _(I)},M=new Set;for(let[,I]of this.nodes)for(let w of I.config?.skills||[])M.add(w);for(let I of M){let w=T(I);if(typeof w?.middleware=="function")try{let R=await w.middleware();typeof R=="function"&&y.set(I,R)}catch{}}let{backEdges:X,joinDegree:jt}=this._analyzeFlow(),Ie=new Map,Q=[],Ee=(I,w,R)=>{if(!I||I==="END")return;let D=jt.get(I)||0;if(R&&D>1&&!X.has(`${w}->${I}`)){let ee=(Ie.get(I)||0)+1;if(ee<D){Ie.set(I,ee);return}Ie.set(I,0)}Q.includes(I)||Q.push(I)};this.entryPoint&&Q.push(this.entryPoint);let ce=[],Fe=a?.recursionLimit??100,Dt=0;try{for(;Q.length>0;){let w=Q.pop();if(!w||w==="END")continue;if(++Dt>Fe)throw new Error(`Workflow exceeded recursion limit (${Fe}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let R=Z(g,st);if(De(R)){try{Nn(R)}catch{}r.abort()}if(r.signal.aborted)return console.warn(`
42
- \u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ce,stoppedExternally:!0};let D=this.nodes.get(w);if(!D)throw new Error(`Node '${w}' not found in graph`);let ee=JSON.stringify({sessionPath:g,sessionTimestamp:m,currentNode:w,createdAt:new Date().toISOString(),config:f.get("config")}),Lt=Z(g,K);xt(Lt,ee,"utf-8");let Ge=f.get("config")?.paths?.output||ge,Wt=Z(s,Ge,K);Pt(Z(s,Ge),{recursive:!0});try{xt(Wt,ee,"utf-8")}catch{}let He=t.onPipelineProgress;if(typeof He=="function")try{He({cwd:s,sessionPath:g,sessionId:S,outputBase:f.get("config")?.paths?.output||ge,currentNode:w})}catch{}let Ut=(this.resolvedToolsMap||{})[w]||null;f.set("_currentNodeTools",Ut);let Ft=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Ft[w]||{}),O.nodeStart(w);let Je=Date.now(),le=this.nodePrompts.get(w);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(ie(),se));this._invokeAgent=k.invokeAgent}let Gt=this._invokeAgent,$e={},Ht=D.config?.skills||[];for(let k of Ht){let N=T(k);if(typeof N?.invokeAgentOptions=="function")try{let A=N.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:w});A&&typeof A=="object"&&($e={...$e,...A})}catch(A){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${A.message}`)}}let ze=async(k,N,A={})=>{let B=Gt(k,N,{...$e,...A,signal:r.signal});return B.catch(()=>{}),r.signal.aborted?B:Promise.race([B,new Promise((q,L)=>{let C=()=>{setTimeout(()=>{let te=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);te.name="AbortError",L(te)},i)};r.signal.addEventListener("abort",C,{once:!0})})])},Jt=async(k={},N={})=>{let A=N.prompt||"";if(le){let B=this._compiledPrompts.get(w);B||(B=Rn.compile(le,{noEscape:!0}),this._compiledPrompts.set(w,B));try{A=B(k)}catch(q){throw console.error(`\u274C Template rendering failed for node '${w}':`,q.message),new Error(`Template rendering failed: ${q.message}`,{cause:q})}}else if(!A)throw new Error(`No prompt template configured for node '${w}' and no prompt provided in options`);return ze(A,{state:f.getAll(),images:N.images||[]},{model:N.model||f.get("model"),workspace:f.get("workspace"),schema:N.schema,...N,signal:r.signal})},Ye=f.getAll(),zt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of zt)Object.prototype.hasOwnProperty.call(Ye,k)&&console.warn(`[workflow] node "${w}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ze={...Ye,state:f,invokeAgent:Jt,_coreInvokeAgent:ze,agent:e,nodeId:w,promptTemplate:le,getPromptTemplate:()=>le};try{let k=(D.config?.skills||[]).map(C=>y.get(C)).filter(Boolean),N=[...this.middleware,...k],A;A=await ht(e,r.signal,async()=>N.length>0?this._composeMiddleware(N,w,async()=>D.execute(Ze,f),f.getAll(),f):D.execute(Ze,f));let B=Date.now()-Je;if(ce.push({node:w,success:A.success,duration:B,timestamp:new Date().toISOString()}),!A.success){if(r.signal.aborted)return O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ce,stoppedExternally:!0};f.append("errors",{node:w,error:A.error});let C=D.config?.retries||0,te=`${w}_retries`,ue=f.getAll()[te]||0;if(ue<C){O.stepInfo(`Retrying (attempt ${ue+1}/${C})`),f.update({[te]:ue+1,[`${w}_raw`]:A.raw});continue}throw O.nodeFailed(w,A.error,{duration:B}),new Error(`Node '${w}' failed after ${ue} attempts: ${A.error}`)}f.update({[w]:A.output});let q=this._summarizeNodeOutput(w,A.output);O.nodeComplete(w,{duration:B,details:q});let L=this.edges.get(w);if(L)if(L.conditional){let C=L.routes(f.getAll());O.route(w,C),Ee(C,w,!1)}else if(Array.isArray(L))for(let C=L.length-1;C>=0;C--)Ee(L[C],w,!0);else Ee(L,w,!0)}catch(k){throw O.isInsideNode&&O.nodeFailed(w,k.message,{duration:Date.now()-Je}),f.set("failed",!0),f.set("failedAt",w),k}}O.graphComplete();let I={success:!0,state:f.getAll(),executionLog:ce};return e&&typeof e.onComplete=="function"&&await e.onComplete(I),I}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(I){console.warn(`[workflow] agent.cleanup() failed: ${I.message}`)}}}};var Le=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Le]||(globalThis[Le]=new Map);var We=globalThis[Le];function Fn(n,e){We.set(n,e)}function Ct(n){return We.get(n)}function Ue(n){return We.has(n)}Fn("ai_agent",{name:"ai_agent",factory:!0,create:(n,e={})=>({name:n,_isCustomCode:!0,execute:async t=>{let o=t?._coreInvokeAgent;o||(o=(await Promise.resolve().then(()=>(ie(),se))).invokeAgent);let r=e.extraPromptInstructions||"Execute the task based on the current state.",i=Gn(r,t),s=await o(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:s,nodeId:n},raw:typeof s=="string"?s:s.raw}}})});function Gn(n,e){let t=/@([\w.]+)/g,o=new Set,r;for(;(r=t.exec(n))!==null;)o.add(r[1]);if(o.size===0)return n;let i=[],s=new Set;for(let a of o){let u=a.split(".")[0];if(s.has(u))continue;let d=a.split(".").reduce((c,g)=>c?.[g],e);if(d===void 0)continue;let h=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),l=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${l}
41
+ ${h}`)}}function Mn(){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 jn(){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 Pt(String(e).trim())}catch{return String(e).trim()}}function Dn(){Mn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Ln({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 Wn(n={}){let e=it.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,r=n.paths?.sessionPrefix;return r?`${r}_${o}`:o}function Un({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let r=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!r&&process.env.ZIBBY_SESSION_PATH)try{let d=Pt(String(process.env.ZIBBY_SESSION_PATH));d&&(r=d,s="ZIBBY_SESSION_PATH")}catch{}let a;if(r)a=String(r).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,s="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,s="config.sessionId"):(a=Wn(e),s="generated")}i=i??Date.now();let h=e.paths?.output||ge;r=Z(n,h,rt,a)}let u=!De(r);return u&&Nt(r,{recursive:!0}),(u||s!=="initialState.sessionPath")&&Bn({traceFrom:o,sessionId:a,sessionPath:r,idSource:s,mkdirFresh:u}),Ln({sessionPath:r,sessionId:a}),{sessionPath:r,sessionId:a,sessionTimestamp:i}}var _e=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,o={}){if(!(t instanceof W)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async d=>{let h=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof s.input=="function"?l=s.input(h):s.input&&typeof s.input=="object"?l=s.input:l={},At(s.workflow,{input:l,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(h):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:h?._signal,parentAgent:d?.agent})}},u=new W(a);return u.name=e,this.nodes.set(e,u),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let r=!(t instanceof W)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof W?t:new W(r?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),o.prompt?this.nodePrompts.set(e,o.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addEdge(e,t){let o=this.edges.get(e);return o===void 0?this.edges.set(e,t):typeof o=="string"?o!==t&&this.edges.set(e,[o,t]):Array.isArray(o)?o.includes(t)||o.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:o}={}){let r=this.edges.get(e);return r!==void 0&&!r.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(r)?r.join(", "):r}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:o}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,o=i=>{t.set(i,1);for(let s of this._simpleTargets(i)){if(!s||s==="END")continue;let a=t.get(s)||0;a===1?e.add(`${i}->${s}`):a===0&&o(s)}t.set(i,2)};this.entryPoint&&o(this.entryPoint);let r=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||r.set(s,(r.get(s)||0)+1);return{backEdges:e,joinDegree:r}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,r,i){let s=o;for(let a=e.length-1;a>=0;a--){let u=e[a],d=s;s=()=>u(t,d,r,i)}return s()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let g=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:g,data:{nodeType:g,label:l}});let m={};c._isCustomCode&&typeof c.execute=="function"&&(m.customCode=c.execute.toString());let w=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;w&&(m.description=w);let $=this.nodePrompts.get(l);if($)m.prompt=$;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(m.prompt=p,m.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(m.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(m.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof we?.toJSONSchema=="function")try{p=we.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Ot(c.outputSchema,{target:"openApi3"})}catch{}m.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else m.outputSchema={schema:c.outputSchema};let I=(this.resolvedToolsMap||{})[l];I?.toolIds&&(m.tools=I.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(m.skills=[...f]);let S=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;S&&S.length>0&&(m.plugins=S.map(p=>p&&typeof p=="object"?{...p}:p));let _=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;_&&_.length>0&&(m.stores=_.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(m).length>0&&(t[l]=m)}let o=[];for(let[l,c]of this.edges)if(typeof c=="string")o.push({source:l,target:c});else if(Array.isArray(c))for(let g of c)o.push({source:l,target:g});else if(c.conditional){let g=this.conditionalCodeMap.get(l)||c.routes.toString(),m=this._inferConditionalTargets(c.routes,c.labels),w=c.labels||{},$=this.nodes.get(l),I=$?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!$,f=l;if(!I){let S=`${l}__branch`;e.push({id:S,type:"decision",data:{nodeType:"decision",label:S}}),o.push({source:l,target:S}),f=S}for(let S of m){let _={source:f,target:S,data:{conditionalCode:g}};w[S]&&(_.label=w[S]),o.push(_)}}let r=l=>{if(!l)return null;if(typeof we?.toJSONSchema=="function")try{return we.toJSONSchema(l)}catch{}try{return Ot(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let i=0;for(let l of o)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"}}),o.push({source:l,target:c})}let s=this._topoOrderNodes(e,o),a=this._runtimeSchema(),u=r(a||this.stateSchema),d=r(this.inputSchema),h=r(this.contextSchema);return{nodes:s,edges:o,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:h}}_topoOrderNodes(e,t){let o=new Map(e.map((l,c)=>[l.id,c])),r=new Map(e.map(l=>[l.id,l])),i=new Map(e.map(l=>[l.id,0])),s=new Map(e.map(l=>[l.id,[]]));for(let l of t)s.has(l.source)&&i.has(l.target)&&(s.get(l.source).push(l.target),i.set(l.target,i.get(l.target)+1));let a=new Set,u=new Set(o.keys()),d=[...u].filter(l=>i.get(l)===0),h=[];for(;h.length<e.length;){let l;if(d.length>0){if(d.sort((c,g)=>o.get(c)-o.get(g)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,g)=>o.get(c)-o.get(g))[0];a.add(l),u.delete(l),h.push(r.get(l));for(let c of s.get(l)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return h}_inferConditionalTargets(e,t){let o=e.toString(),r=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(o))!==null;){let d=s[2]!==void 0?s[2]:s[3];d!==void 0&&d!==""&&r.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let u=new Set;for(let d of r)a.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=d.exec(o))!==null;)u.add(h[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let r=e.$ref.replace("#/definitions/","");o=e.definitions[r]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],r=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(r)){let u=t?`${t}.${s}`:s;o.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${u}[]`))}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[r,i]of Object.entries(t))if(!(r==="success"||r==="raw"||r==="nextNode")){if(typeof i=="string"&&i.length<=80)o.push(`${r}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(d=>d?.passed===!0).length,u=i.some(d=>d?.passed!==void 0);o.push(u?`${r}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${r}: ${s} items`)}if(o.length>=4)break}return o}async run(e,t={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(b){let y=new Error(`agent.normalizeInput() rejected the trigger input: ${b?.message||b}`);throw y.cause=b,y.code=b?.code||"NORMALIZE_INPUT_FAILED",y}let r=new AbortController;o.signal&&(o.signal.aborted?r.abort():o.signal.addEventListener("abort",()=>r.abort(),{once:!0}));let i=o.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();Cn({path:Z(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let b=Z(s,".zibby.config.js");De(b)&&(a=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let b=a?.agent;b?.provider?u=b.provider:b?.gemini?u="gemini":b?.claude?u="claude":b?.cursor?u="cursor":b?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},h=this._runtimeSchema();if(h){let b=h.safeParse(t);if(!b.success){let y=b.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),y.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${y.join(", ")}`)}O.step("State validated against schema")}let l=jn(),c=t.sessionPath||l;c||Dn();let{sessionPath:g,sessionTimestamp:m,sessionId:w}=Un({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${w}`);let $=await Se.loadContext(t.specPath||"",s,d);Object.keys($).length>0&&O.step(`Context loaded: ${Object.keys($).join(", ")}`);let I=t.outputPath;!I&&t.specPath&&(e?.calculateOutputPath?I=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new pe({...t,config:a,agentType:u,outputPath:I,sessionPath:g,sessionTimestamp:m,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:r.signal}),S=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:_}=await Promise.resolve().then(()=>(me(),ct)),p=a.skills&&typeof a.skills=="object"?a.skills:{},v=Object.values(p).filter(b=>b&&typeof b=="object"&&typeof b.id=="string"),T=b=>{for(let y of v)if(y.id===b)return y;return _(b)},M=new Set;for(let[,b]of this.nodes)for(let y of b.config?.skills||[])M.add(y);for(let b of M){let y=T(b);if(typeof y?.middleware=="function")try{let R=await y.middleware();typeof R=="function"&&S.set(b,R)}catch{}}let{backEdges:X,joinDegree:jt}=this._analyzeFlow(),Ie=new Map,Q=[],Ee=(b,y,R)=>{if(!b||b==="END")return;let D=jt.get(b)||0;if(R&&D>1&&!X.has(`${y}->${b}`)){let ee=(Ie.get(b)||0)+1;if(ee<D){Ie.set(b,ee);return}Ie.set(b,0)}Q.includes(b)||Q.push(b)};this.entryPoint&&Q.push(this.entryPoint);let ce=[],Fe=a?.recursionLimit??100,Dt=0;try{for(;Q.length>0;){let y=Q.pop();if(!y||y==="END")continue;if(++Dt>Fe)throw new Error(`Workflow exceeded recursion limit (${Fe}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let R=Z(g,st);if(De(R)){try{Pn(R)}catch{}r.abort()}if(r.signal.aborted)return console.warn(`
42
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ce,stoppedExternally:!0};let D=this.nodes.get(y);if(!D)throw new Error(`Node '${y}' not found in graph`);let ee=JSON.stringify({sessionPath:g,sessionTimestamp:m,currentNode:y,createdAt:new Date().toISOString(),config:f.get("config")}),Lt=Z(g,K);xt(Lt,ee,"utf-8");let Ge=f.get("config")?.paths?.output||ge,Wt=Z(s,Ge,K);Nt(Z(s,Ge),{recursive:!0});try{xt(Wt,ee,"utf-8")}catch{}let He=t.onPipelineProgress;if(typeof He=="function")try{He({cwd:s,sessionPath:g,sessionId:w,outputBase:f.get("config")?.paths?.output||ge,currentNode:y})}catch{}let Ut=(this.resolvedToolsMap||{})[y]||null;f.set("_currentNodeTools",Ut);let Ft=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Ft[y]||{}),O.nodeStart(y);let Je=Date.now(),le=this.nodePrompts.get(y);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(ie(),se));this._invokeAgent=k.invokeAgent}let Gt=this._invokeAgent,$e={},Ht=D.config?.skills||[];for(let k of Ht){let P=T(k);if(typeof P?.invokeAgentOptions=="function")try{let A=P.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:y});A&&typeof A=="object"&&($e={...$e,...A})}catch(A){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${A.message}`)}}let ze=async(k,P,A={})=>{let B=Gt(k,P,{...$e,...A,signal:r.signal});return B.catch(()=>{}),r.signal.aborted?B:Promise.race([B,new Promise((q,L)=>{let C=()=>{setTimeout(()=>{let te=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);te.name="AbortError",L(te)},i)};r.signal.addEventListener("abort",C,{once:!0})})])},Jt=async(k={},P={})=>{let A=P.prompt||"";if(le){let B=this._compiledPrompts.get(y);B||(B=Rn.compile(le,{noEscape:!0}),this._compiledPrompts.set(y,B));try{A=B(k)}catch(q){throw console.error(`\u274C Template rendering failed for node '${y}':`,q.message),new Error(`Template rendering failed: ${q.message}`,{cause:q})}}else if(!A)throw new Error(`No prompt template configured for node '${y}' and no prompt provided in options`);return ze(A,{state:f.getAll(),images:P.images||[]},{model:P.model||f.get("model"),workspace:f.get("workspace"),schema:P.schema,...P,signal:r.signal})},Ye=f.getAll(),zt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of zt)Object.prototype.hasOwnProperty.call(Ye,k)&&console.warn(`[workflow] node "${y}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ze={...Ye,state:f,invokeAgent:Jt,_coreInvokeAgent:ze,agent:e,nodeId:y,promptTemplate:le,getPromptTemplate:()=>le};try{let k=(D.config?.skills||[]).map(C=>S.get(C)).filter(Boolean),P=[...this.middleware,...k],A;A=await ht(e,r.signal,async()=>P.length>0?this._composeMiddleware(P,y,async()=>D.execute(Ze,f),f.getAll(),f):D.execute(Ze,f));let B=Date.now()-Je;if(ce.push({node:y,success:A.success,duration:B,timestamp:new Date().toISOString()}),!A.success){if(r.signal.aborted)return O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ce,stoppedExternally:!0};f.append("errors",{node:y,error:A.error});let C=D.config?.retries||0,te=`${y}_retries`,ue=f.getAll()[te]||0;if(ue<C){O.stepInfo(`Retrying (attempt ${ue+1}/${C})`),f.update({[te]:ue+1,[`${y}_raw`]:A.raw});continue}throw O.nodeFailed(y,A.error,{duration:B}),new Error(`Node '${y}' failed after ${ue} attempts: ${A.error}`)}f.update({[y]:A.output});let q=this._summarizeNodeOutput(y,A.output);O.nodeComplete(y,{duration:B,details:q});let L=this.edges.get(y);if(L)if(L.conditional){let C=L.routes(f.getAll());O.route(y,C),Ee(C,y,!1)}else if(Array.isArray(L))for(let C=L.length-1;C>=0;C--)Ee(L[C],y,!0);else Ee(L,y,!0)}catch(k){throw O.isInsideNode&&O.nodeFailed(y,k.message,{duration:Date.now()-Je}),f.set("failed",!0),f.set("failedAt",y),k}}O.graphComplete();let b={success:!0,state:f.getAll(),executionLog:ce};return e&&typeof e.onComplete=="function"&&await e.onComplete(b),b}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(b){console.warn(`[workflow] agent.cleanup() failed: ${b.message}`)}}}};var Le=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Le]||(globalThis[Le]=new Map);var We=globalThis[Le];function Fn(n,e){We.set(n,e)}function Ct(n){return We.get(n)}function Ue(n){return We.has(n)}Fn("ai_agent",{name:"ai_agent",factory:!0,create:(n,e={})=>({name:n,_isCustomCode:!0,execute:async t=>{let o=t?._coreInvokeAgent;o||(o=(await Promise.resolve().then(()=>(ie(),se))).invokeAgent);let r=e.extraPromptInstructions||"Execute the task based on the current state.",i=Gn(r,t),s=await o(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:s,nodeId:n},raw:typeof s=="string"?s:s.raw}}})});function Gn(n,e){let t=/@([\w.]+)/g,o=new Set,r;for(;(r=t.exec(n))!==null;)o.add(r[1]);if(o.size===0)return n;let i=[],s=new Set;for(let a of o){let u=a.split(".")[0];if(s.has(u))continue;let d=a.split(".").reduce((c,g)=>c?.[g],e);if(d===void 0)continue;let h=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),l=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${l}
43
43
  ${h}`),a.includes(".")||s.add(u)}return i.length===0?n:`${n}
44
44
 
45
45
  ---
@@ -47,4 +47,4 @@ ${h}`),a.includes(".")||s.add(u)}return i.length===0?n:`${n}
47
47
 
48
48
  ${i.join(`
49
49
 
50
- `)}`}me();F();var Hn={};function Bt(n,e){if(Array.isArray(e))return Rt(e);let t=Hn[n];return!t||t.length===0?null:Rt(t)}function Rt(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},o=[];for(let r of n){let i=re(r);if(!i){E.warn(`[workflow] unknown skill "${r}" \u2014 skipping`);continue}o.push(r);for(let s of i.tools||[])e.push({name:s.name,description:s.description,input_schema:s.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let s=i.resolve();s&&(t[i.serverName]={...s,toolPrefix:r})}else{let s={};for(let a of i.envKeys||[]){let u=process.env[a];u&&(s[a]=u)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:s,toolPrefix:r}}}return o.length===0?null:{toolIds:o,claudeTools:e,mcpServers:t}}F();function er(n,e={}){let{nodes:t,edges:o,nodeConfigs:r={}}=n;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(o))throw new j("Graph edges must be an array");let i=new _e(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let s=new Set,a=new Map,u={};for(let c of t){let g=be(c);a.set(c.id,{...c,resolvedType:g}),g==="decision"&&s.add(c.id)}for(let[c,g]of a){if(s.has(c))continue;let m=g.resolvedType,S=r[c]||{},$=Bt(m,S.tools);$&&(u[c]=$);let b={};S.prompt&&(b.prompt=S.prompt);let f=Ue(m);if(E.debug(`[workflow] compiler: node "${c}" type="${m}" registered=${f}`),S.customCode&&!f)i.addNode(c,Mt(c,S.customCode,S),b),i.setNodeType(c,m);else if(f){let y=Ct(m);y.factory?i.addNode(c,y.create(c,{...S,resolvedTools:$}),b):i.addNode(c,y,b),i.setNodeType(c,m)}else if(S.executeCode)i.addNode(c,Mt(c,S.executeCode,S),b),i.setNodeType(c,m);else throw new j(`Unknown node type "${m}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=u;let d=new Set;for(let c of o)s.has(c.target)||d.add(c.target);let h=t.find(c=>!s.has(c.id)&&!d.has(c.id));if(!h)throw new j("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(h.id);let l=Jn(o,"source");for(let c of o)if(!s.has(c.source))if(s.has(c.target)){let g=c.target,m=l.get(g)||[];if(m.length===0)throw new j(`Decision node "${g}" has no outgoing edges`);let S=zn(g,m,s);i.addConditionalEdges(c.source,S)}else i.addEdge(c.source,c.target);return i}function tr(n){let e=[];if(!n||typeof n!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(n.nodes)||n.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(n.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=n.nodeConfigs||{};for(let a of n.nodes){let u=be(a);if(u==="decision"||Ue(u))continue;let d=t[a.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${u}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let o=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)o.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),o.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let r=new Set(n.nodes.filter(a=>be(a)==="decision").map(a=>a.id)),i=new Set;for(let a of n.edges)r.has(a.target)||i.add(a.target);let s=n.nodes.filter(a=>!r.has(a.id)&&!i.has(a.id));s.length===0?e.push("No entry point found (every node has incoming edges)"):s.length>1&&e.push(`Multiple entry points found: ${s.map(a=>a.id).join(", ")}`);for(let a of r){let u=n.edges.filter(h=>h.source===a);u.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),u.some(h=>h.data?.conditionalCode||h.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function nr(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>be(e)!=="decision").map(e=>e.id)}function be(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function Jn(n,e){let t=new Map;for(let o of n){let r=o[e];t.has(r)||t.set(r,[]),t.get(r).push(o)}return t}function zn(n,e,t){let o=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!o)throw new j(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let r=o.data?.conditionalCode||o.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),s;try{let u=new Function(`return (${r})`)();s=d=>{let h=u(d);return i.has(h)||E.warn(`[workflow] conditional route from "${n}" returned "${h}" which is not in valid targets: ${[...i].join(", ")}`),h}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return s}function Mt(n,e,t={}){let o;try{o=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new j(`Failed to compile customCode for node "${n}": ${s.message}`)}let r=o(async(...s)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(ie(),se));return a(...s)},typeof ve<"u"?ve:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:n,_isCustomCode:!0,outputSchema:i,execute:async s=>{try{let a=await r(s);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var j=class extends Error{constructor(e){super(e),this.name="CompilationError"}};export{j as CompilationError,er as compileGraph,nr as extractSteps,tr as validateGraphConfig};
50
+ `)}`}me();F();var Hn={};function Bt(n,e){if(Array.isArray(e))return Rt(e);let t=Hn[n];return!t||t.length===0?null:Rt(t)}function Rt(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},o=[];for(let r of n){let i=re(r);if(!i){E.warn(`[workflow] unknown skill "${r}" \u2014 skipping`);continue}o.push(r);for(let s of i.tools||[])e.push({name:s.name,description:s.description,input_schema:s.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let s=i.resolve();s&&(t[i.serverName]={...s,toolPrefix:r})}else{let s={};for(let a of i.envKeys||[]){let u=process.env[a];u&&(s[a]=u)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:s,toolPrefix:r}}}return o.length===0?null:{toolIds:o,claudeTools:e,mcpServers:t}}F();function er(n,e={}){let{nodes:t,edges:o,nodeConfigs:r={}}=n;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(o))throw new j("Graph edges must be an array");let i=new _e(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let s=new Set,a=new Map,u={};for(let c of t){let g=be(c);a.set(c.id,{...c,resolvedType:g}),g==="decision"&&s.add(c.id)}for(let[c,g]of a){if(s.has(c))continue;let m=g.resolvedType,w=r[c]||{},$=Bt(m,w.tools);$&&(u[c]=$);let I={};w.prompt&&(I.prompt=w.prompt);let f=Ue(m);if(E.debug(`[workflow] compiler: node "${c}" type="${m}" registered=${f}`),w.customCode&&!f)i.addNode(c,Mt(c,w.customCode,w),I),i.setNodeType(c,m);else if(f){let S=Ct(m);S.factory?i.addNode(c,S.create(c,{...w,resolvedTools:$}),I):i.addNode(c,S,I),i.setNodeType(c,m)}else if(w.executeCode)i.addNode(c,Mt(c,w.executeCode,w),I),i.setNodeType(c,m);else throw new j(`Unknown node type "${m}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=u;let d=new Set;for(let c of o)s.has(c.target)||d.add(c.target);let h=t.find(c=>!s.has(c.id)&&!d.has(c.id));if(!h)throw new j("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(h.id);let l=Jn(o,"source");for(let c of o)if(!s.has(c.source))if(s.has(c.target)){let g=c.target,m=l.get(g)||[];if(m.length===0)throw new j(`Decision node "${g}" has no outgoing edges`);let w=zn(g,m,s);i.addConditionalEdges(c.source,w)}else i.addEdge(c.source,c.target);return i}function tr(n){let e=[];if(!n||typeof n!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(n.nodes)||n.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(n.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=n.nodeConfigs||{};for(let a of n.nodes){let u=be(a);if(u==="decision"||Ue(u))continue;let d=t[a.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${u}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let o=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)o.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),o.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let r=new Set(n.nodes.filter(a=>be(a)==="decision").map(a=>a.id)),i=new Set;for(let a of n.edges)r.has(a.target)||i.add(a.target);let s=n.nodes.filter(a=>!r.has(a.id)&&!i.has(a.id));s.length===0?e.push("No entry point found (every node has incoming edges)"):s.length>1&&e.push(`Multiple entry points found: ${s.map(a=>a.id).join(", ")}`);for(let a of r){let u=n.edges.filter(h=>h.source===a);u.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),u.some(h=>h.data?.conditionalCode||h.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function nr(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>be(e)!=="decision").map(e=>e.id)}function be(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function Jn(n,e){let t=new Map;for(let o of n){let r=o[e];t.has(r)||t.set(r,[]),t.get(r).push(o)}return t}function zn(n,e,t){let o=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!o)throw new j(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let r=o.data?.conditionalCode||o.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),s;try{let u=new Function(`return (${r})`)();s=d=>{let h=u(d);return i.has(h)||E.warn(`[workflow] conditional route from "${n}" returned "${h}" which is not in valid targets: ${[...i].join(", ")}`),h}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return s}function Mt(n,e,t={}){let o;try{o=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new j(`Failed to compile customCode for node "${n}": ${s.message}`)}let r=o(async(...s)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(ie(),se));return a(...s)},typeof ve<"u"?ve:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:n,_isCustomCode:!0,outputSchema:i,execute:async s=>{try{let a=await r(s);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var j=class extends Error{constructor(e){super(e),this.name="CompilationError"}};export{j as CompilationError,er as compileGraph,nr as extractSteps,tr as validateGraphConfig};
package/dist/graph.js CHANGED
@@ -1,12 +1,12 @@
1
- var jt=Object.defineProperty;var ae=(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)jt(r,t,{get:e[t],enumerable:!0})};var Ge,Lt,ue,E,ee=ae(()=>{Ge=()=>{},Lt={debug:Ge,info:Ge,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},ue={impl:Lt},E={debug:(...r)=>ue.impl.debug?.(...r),info:(...r)=>ue.impl.info?.(...r),warn:(...r)=>ue.impl.warn?.(...r),error:(...r)=>ue.impl.error?.(...r)}});var et=ae(()=>{});var tt={};Fe(tt,{clearSkills:()=>Yt,getAllSkills:()=>Jt,getSkill:()=>$e,getSkillSource:()=>Ht,hasSkill:()=>Gt,listSkillIds:()=>zt,registerSkill:()=>Ft});function Ft(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 i=ne.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).`)}}U.set(s,Object.freeze({...r})),t===void 0?ne.delete(s):ne.set(s,t)}function $e(r){return U.get(r)||null}function Gt(r){return U.has(r)}function Ht(r){return ne.get(r)||null}function Jt(){return new Map(U)}function zt(){return Array.from(U.keys())}function Yt(){U.clear(),ne.clear()}var Ie,Ee,U,ne,ve=ae(()=>{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],ne=globalThis[Ee]});var Te={};Fe(Te,{getAgentStrategy:()=>rt,invokeAgent:()=>Vt,listStrategies:()=>qt,registerStrategy:()=>Zt,resolveInvocationModel:()=>nt});function Zt(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 qt(){return F.map(r=>r.getName())}function nt({config:r={},options:e={},strategyName:t,envModel:n}={}){let s=r.models||{},i=e.nodeName&&s[e.nodeName]||null,o=s.default||null,a=r.agent?.[t]?.model||null,u=(typeof n=="string"?n.trim():"")||null;return i||o||a||e.model||u||null}function rt(r={}){let{state:e={},preferredAgent:t=null}=r,n=t||e.agentType||process.env.AGENT_TYPE;if(!n){let i=F.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}E.debug(`[workflow] agent selection: requested=${n}`);let s=F.find(i=>i.getName()===n);if(!s){let i=F.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${i}`)}if(!s.canHandle(r))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return E.debug(`[workflow] using agent: ${s.getName()}`),s}async function Vt(r,e={},t={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:n},i=rt(s),o=n.config||t.config||{},a=nt({config:o,options:t,strategyName:i.name,envModel:process.env.MODEL}),u={...t,model:a,workspace:n.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],extraMcpServers:t.extraMcpServers||n.extraMcpServers||e.extraMcpServers||[],plugins:t.plugins||e.plugins||[],config:o},p=r,m=u.skills||[];if(m.length>0&&!t.skipPromptFragments){let S=t.connectedIntegrations;if(!S){let $=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof $=="string"&&$.trim()!==""){S={};for(let I of $.split(",").map(f=>f.trim()).filter(Boolean))S[I]=!0}}let w=$=>{let I=$&&$.requiresIntegration;return!I||!S?!0:(Array.isArray(I)?I:[I]).some(g=>S[g]===!0)},b=m.map($=>{let I=$e($);if(!w(I))return null;let f=I?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);b.length>0&&(p+=`
1
+ var jt=Object.defineProperty;var ae=(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)jt(r,t,{get:e[t],enumerable:!0})};var Ge,Lt,ue,E,ee=ae(()=>{Ge=()=>{},Lt={debug:Ge,info:Ge,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},ue={impl:Lt},E={debug:(...r)=>ue.impl.debug?.(...r),info:(...r)=>ue.impl.info?.(...r),warn:(...r)=>ue.impl.warn?.(...r),error:(...r)=>ue.impl.error?.(...r)}});var et=ae(()=>{});var tt={};Fe(tt,{clearSkills:()=>Yt,getAllSkills:()=>Jt,getSkill:()=>$e,getSkillSource:()=>Ht,hasSkill:()=>Gt,listSkillIds:()=>zt,registerSkill:()=>Ft});function Ft(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 i=ne.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).`)}}U.set(s,Object.freeze({...r})),t===void 0?ne.delete(s):ne.set(s,t)}function $e(r){return U.get(r)||null}function Gt(r){return U.has(r)}function Ht(r){return ne.get(r)||null}function Jt(){return new Map(U)}function zt(){return Array.from(U.keys())}function Yt(){U.clear(),ne.clear()}var be,Ee,U,ne,ve=ae(()=>{be=Symbol.for("@zibby/agent-workflow.skills"),Ee=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[be]||(globalThis[be]=new Map);globalThis[Ee]||(globalThis[Ee]=new Map);U=globalThis[be],ne=globalThis[Ee]});var Te={};Fe(Te,{getAgentStrategy:()=>rt,invokeAgent:()=>Vt,listStrategies:()=>qt,registerStrategy:()=>Zt,resolveInvocationModel:()=>nt});function Zt(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 qt(){return F.map(r=>r.getName())}function nt({config:r={},options:e={},strategyName:t,envModel:n}={}){let s=r.models||{},i=e.nodeName&&s[e.nodeName]||null,o=s.default||null,a=r.agent?.[t]?.model||null,u=(typeof n=="string"?n.trim():"")||null;return i||o||a||e.model||u||null}function rt(r={}){let{state:e={},preferredAgent:t=null}=r,n=t||e.agentType||process.env.AGENT_TYPE;if(!n){let i=F.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}E.debug(`[workflow] agent selection: requested=${n}`);let s=F.find(i=>i.getName()===n);if(!s){let i=F.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${i}`)}if(!s.canHandle(r))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return E.debug(`[workflow] using agent: ${s.getName()}`),s}async function Vt(r,e={},t={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:n},i=rt(s),o=n.config||t.config||{},a=nt({config:o,options:t,strategyName:i.name,envModel:process.env.MODEL}),u={...t,model:a,workspace:n.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],extraMcpServers:t.extraMcpServers||n.extraMcpServers||e.extraMcpServers||[],plugins:t.plugins||e.plugins||[],config:o},p=r,m=u.skills||[];if(m.length>0&&!t.skipPromptFragments){let w=t.connectedIntegrations;if(!w){let $=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof $=="string"&&$.trim()!==""){w={};for(let b of $.split(",").map(f=>f.trim()).filter(Boolean))w[b]=!0}}let _=$=>{let b=$&&$.requiresIntegration;return!b||!w?!0:(Array.isArray(b)?b:[b]).some(g=>w[g]===!0)},I=m.map($=>{let b=$e($);if(!_(b))return null;let f=b?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);I.length>0&&(p+=`
2
2
 
3
- ${b.join(`
3
+ ${I.join(`
4
4
 
5
- `)}`)}let c=n._currentNodeConfig?.stores;if(Array.isArray(c)&&c.length>0&&typeof c[0]=="object"){let S=c.length<=8,w=c.map(b=>{let $=b?.id??b?.storeId??"",I=(b?.name??"").toString().trim()||$,f=b?.type?` \xB7 ${b.type}`:"",g=(b?.description||"").toString().replace(/\s+/g," ").trim(),y=`- ${I} \xB7 ${g||"(no description)"}${f} (id: ${$})`;if(S&&b?.schema&&typeof b.schema=="object"){let d=b.schema.properties&&typeof b.schema.properties=="object"?Object.keys(b.schema.properties):Object.keys(b.schema);d.length&&(y+=`
5
+ `)}`)}let c=n._currentNodeConfig?.stores;if(Array.isArray(c)&&c.length>0&&typeof c[0]=="object"){let w=c.length<=8,_=c.map(I=>{let $=I?.id??I?.storeId??"",b=(I?.name??"").toString().trim()||$,f=I?.type?` \xB7 ${I.type}`:"",g=(I?.description||"").toString().replace(/\s+/g," ").trim(),y=`- ${b} \xB7 ${g||"(no description)"}${f} (id: ${$})`;if(w&&I?.schema&&typeof I.schema=="object"){let d=I.schema.properties&&typeof I.schema.properties=="object"?Object.keys(I.schema.properties):Object.keys(I.schema);d.length&&(y+=`
6
6
  fields: ${d.join(", ")}`)}return y});p+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
9
- ${w.join(`
9
+ ${_.join(`
10
10
  `)}`}let l=n._currentNodeConfig?.extraPromptInstructions?.trim();return l&&(p+=`
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
@@ -18,7 +18,7 @@ ${l}
18
18
  ${t.join(`
19
19
  `)}`);return e}};ee();import{writeFileSync as xe,readFileSync as st,existsSync as ot,mkdirSync as Kt}from"node:fs";import{join as Oe,dirname as Xt}from"node:path";import x from"chalk";var Wt="__WORKFLOW_GRAPH_LOG__",te=x.gray("\u2502"),Ut=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=`${te} `,Ze=2;function qe(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function Ve(r,e){return(t,n,s)=>{if(typeof t!="string")return r(t,n,s);let i=process.stdout.columns||120,o="";for(let a=0;a<t.length;a++){let u=t[a];e.lineStart&&(o+=Ye,e.col=Ze,e.lineStart=!1),u===`
20
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
- ${Ye}`,e.col=Ze))}return r(o,n,s)}}var be=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=Ve(this._origStdoutWrite,e),process.stderr.write=Ve(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
21
+ ${Ye}`,e.col=Ze))}return r(o,n,s)}}var Ie=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=Ve(this._origStdoutWrite,e),process.stderr.write=Ve(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
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
24
  `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Wt}${JSON.stringify(e)}
@@ -29,14 +29,14 @@ ${Ye}`,e.col=Ze))}return r(o,n,s)}}var be=class{constructor(){this._currentNode=
29
29
  `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Je,e):process.stdout.write.bind(process.stdout)(`${te} ${Je} ${e}
30
30
  `)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(ze,t):process.stdout.write.bind(process.stdout)(`${te} ${ze} ${t}
31
31
  `)}stepFail(e){this._origStdoutWrite?this._writeDot(_e,x.red(e)):process.stdout.write.bind(process.stdout)(`${te} ${_e} ${x.red(e)}
32
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Ut} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:n,details:s}=t;if(s)for(let o of s)this._rawWrite(`${we} ${o}`);let i=n?x.dim(` ${qe(n)}`):"";this._rawWrite(`${He} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,n={}){this._stopIntercepting();let{duration:s}=n,i=s?x.dim(` ${qe(s)}`):"";this._rawWrite(`${_e} ${x.red(t)}`),this._rawWrite(`${He} ${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(){}},O=new be;var pe=".zibby/output",Ke="sessions",Z=".session-info.json",Xe=".zibby-stop";var Dn=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 le(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return E.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let 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"){E.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?(E.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 E.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&E.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=G.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(n())):i=this.prompt;let o=s("_skillHints");o&&(i=`${o}
32
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Ut} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:n,details:s}=t;if(s)for(let o of s)this._rawWrite(`${we} ${o}`);let i=n?x.dim(` ${qe(n)}`):"";this._rawWrite(`${He} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,n={}){this._stopIntercepting();let{duration:s}=n,i=s?x.dim(` ${qe(s)}`):"";this._rawWrite(`${_e} ${x.red(t)}`),this._rawWrite(`${He} ${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(){}},O=new Ie;var pe=".zibby/output",Ke="sessions",Z=".session-info.json",Xe=".zibby-stop";var Dn=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 le(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return E.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let 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"){E.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?(E.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 E.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&E.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=G.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(n())):i=this.prompt;let o=s("_skillHints");o&&(i=`${o}
33
33
 
34
- ${i}`);let a=n(),u=a.cwd||process.cwd(),p=a.sessionPath;try{if(p){let c=Oe(p,Z);if(ot(c)){let S=JSON.parse(st(c,"utf-8"));S.currentNode=this.name,xe(c,JSON.stringify(S,null,2),"utf-8")}let l=Oe(p,"..",Z);if(ot(l))try{let S=JSON.parse(st(l,"utf-8"));S.currentNode=this.name,xe(l,JSON.stringify(S,null,2),"utf-8")}catch{}}}catch(c){E.debug(`[workflow] could not update session info: ${c.message}`)}let m=null;for(let c=0;c<=this.retries;c++)try{E.debug(`[workflow] node '${this.name}' attempt ${c}`);let l=n().config||{},S=l.agents||{},w=this.config.agent??S[this.name]??null,b={state:n()};w&&(b.preferredAgent=w);let $={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:p,config:l,nodeName:this.name,timeout:this.config?.timeout||3e5},I=e?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(ke(),Te))).invokeAgent);let f=await I(i,b,$),g,y;if(typeof f=="string"?(g=f,y=null):f.structured?(g=f.raw||JSON.stringify(f.structured,null,2),y=f.structured):(g=f.raw||JSON.stringify(f,null,2),y=f.extracted||null),p)try{let d=Oe(p,this.name,"raw_stream_output.txt");Kt(Xt(d),{recursive:!0}),xe(d,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(d){E.debug(`[workflow] could not save raw output: ${d.message}`)}if(this.isZodSchema&&y){E.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let d=y;if(typeof this.onComplete=="function")try{d=await this.onComplete(n(),y)}catch(v){E.warn(`[workflow] onComplete hook failed: ${v.message}`)}return{success:!0,output:d,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:g}),raw:g}}catch(d){throw new Error(`onComplete failed: ${d.message}`,{cause:d})}if(this.parser){let d=this.parser.parse(g);return E.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(d,null,2)}`),O.step("Output parsed"),{success:!0,output:d,raw:g}}return{success:!0,output:g,raw:g}}catch(l){m=l,c<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:m.message,raw:null}}};ee();ee();import{mkdirSync as tn,existsSync as J,statSync as gt,readdirSync as mt,rmSync as nn}from"node:fs";import{spawn as dt}from"node:child_process";import{join as W}from"node:path";import{pathToFileURL as rn}from"node:url";import{AsyncLocalStorage as sn}from"node:async_hooks";import{AsyncLocalStorage as Qt}from"node:async_hooks";var re=new Qt;function q(){let r=re.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 it(r,e){let t=re.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 re.run(n,e)}function at(r,e,t){let n=re.getStore()||q(),s=Object.freeze({...n,agent:r??n.agent??null,signal:e??n.signal??null});return re.run(s,t)}var Pe=new Map,Ne=new Map,ct=new Map;function lt(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"),ct.set(r,{...t,cachedAt:Date.now()})}function ut(r,e){Ne.set(r,"failed"),ct.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 on(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var P=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}},ft=new sn,ht=Promise.resolve();async function an(r,e){let t=r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(([o,a])=>typeof o=="string"&&o&&typeof a=="string"):[];if(t.length===0)return e();let n=ft.getStore()===!0,s=null;if(!n){let o=ht;ht=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 E.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await ft.run(!0,e)}finally{for(let[o,a]of i)a===void 0?delete process.env[o]:process.env[o]=a;s&&s()}}function cn(){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 P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:s}}async function ln({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(i){throw new P("network",`begin fetch failed: ${i.message}`)}let s=null;try{s=await n.json()}catch{}if(!n.ok){if(n.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(n.status===429){let i=s?.quotaInfo||{},o=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw o.code="SUBGRAPH_QUOTA_EXCEEDED",o.status=429,o.quotaInfo=i,o}if(n.status===400&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new P("begin-status",`begin returned ${n.status}`)}return s?.data||s}async function 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||E.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){E.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function un(r,e){let t=W(e,".ready"),n=W(e,"graph.mjs");if(J(t)&&J(n))return;tn(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(J(t)&&J(n))return;await new Promise(a=>setTimeout(a,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,p)=>{let m=dt("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),c=dt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});m.stdout.pipe(c.stdin);let l,S,w=()=>{if(l!==void 0&&S!==void 0){if(l!==0)return p(new Error(`curl exited ${l}`));if(S!==0)return p(new Error(`tar exited ${S}`));u()}};m.on("close",b=>{l=b,w()}),c.on("close",b=>{S=b,w()}),m.on("error",p),c.on("error",p)});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 P("bundle-extract-failed",o.message)}}async function pn(r){let e=W(r,"graph.mjs");if(!J(e))throw new P("entry-missing",`graph.mjs missing under ${r}`);let t;try{t=await import(rn(e).href)}catch(s){throw new P("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let n=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!n)throw new P("entry-class-missing","no buildGraph() class export found");return n}async function yt(r,e={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=q(),n;try{n=cn()}catch(d){throw d}E.debug(`[in-process subgraph] begin '${r}' parent=${t.executionId||"<root>"}`);let s=await ln({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:r,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:o,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:p,workflowUuid:m,bundleReady:c,nodeConfigs:l}=s,S=on();if(o&&o!==S)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new P("runtime-mismatch",`${S} vs ${o}`);if(!c||!a)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new P("no-bundle","workflow bundle not built yet");let w=pt(r);if(!w){let d=W(de,`${m}@${p||"0"}`);try{await un(a,d);try{fn()}catch{}}catch(v){throw v.fallback&&await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:v.message,code:v.reason}}}),v}try{w=await pn(d),lt(r,w,{workflowUuid:m,version:p,runtimeTag:o,cacheDir:d})}catch(v){throw ut(r,v),await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:v.message,code:v.reason||"IMPORT_FAILED"}}}),v.fallback?v:new P("import-failed",v.message)}}let b=Date.now(),$=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,I=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,f={...e.input||{},...I?{nodeConfigs:l}:{}},g,y;try{g=await an($,async()=>{let v=await(typeof w=="function"&&w.prototype?.buildGraph?new w:w).buildGraph();return it({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>v.run(e.parentAgent,f,{signal:e.signal}))}),y=g&&typeof g=="object"&&"state"in g?g.state:g}catch(d){throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:d.message,code:d.code||"CHILD_THREW",stack:d.stack},durationMs:Date.now()-b}}),d}if(g&&typeof g=="object"&&g.stoppedExternally){await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",finalState:y,durationMs:Date.now()-b}});let d=new Error(`Sub-graph '${r}' canceled by parent abort`);throw d.code="SUBGRAPH_CANCELED",d.subgraphJobId=i,d}return await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:y,durationMs:Date.now()-b}}),{finalState:y,executionId:i}}function dn(r){let e=0,t=[r];for(;t.length;){let n=t.pop(),s;try{s=gt(n)}catch{continue}if(s.isDirectory()){let i;try{i=mt(n)}catch{continue}for(let o of i)t.push(W(n,o))}else e+=s.size}return e}function fn({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=mt(de),t=[],n=0;for(let a of e){let u=W(de,a),p;try{p=gt(u)}catch{continue}let m=p.isDirectory()?dn(u):p.size;n+=m,t.push({name:a,full:u,size:m,mtimeMs:p.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),i=0,o=0;for(let a of t){if(n-i<=s)break;if(!J(W(a.full,".lock")))try{nn(a.full,{recursive:!0,force:!0}),i+=a.size,o+=1}catch(u){E.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return o>0&&E.info(`[sub-graph cache] evicted ${o} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:o,freedBytes:i,totalBytes:n-i}}catch(e){return E.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var hn=2e3,gn=600*1e3,mn=new Set(["completed","failed","canceled","timeout"]);function yn(){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 Sn(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function wn(){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 St(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 wt(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.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{E.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:y}=await yt(r,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),d=St(y,e.output);return E.info(`[sub-graph] '${r}' completed in-process`),d}catch(y){if(y instanceof P||y?.fallback)E.info(`[sub-graph] in-process fallback for '${r}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let s=yn(),i=Sn(),o=wn(),a=_n(),u=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(r)}/trigger`,p={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};E.info(`[sub-graph] dispatching '${r}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let m=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(p)});if(!m.ok){let y=null,d="";try{y=await m.json(),d=y?.error||y?.message||JSON.stringify(y)}catch{d=await m.text().catch(()=>"")}if(m.status===429){let T=y?.quotaInfo||{},M=new Error(`Sub-graph '${r}' blocked by execution quota (${T.used??"?"}/${T.limit??"?"} on plan ${T.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=r,M.quotaInfo=T,M}if(m.status===400){let T=new Error(`Sub-graph '${r}' rejected input: ${d}`);throw T.code="SUBGRAPH_INVALID_INPUT",T.status=400,T.subgraph=r,T.validationErrors=y?.validationErrors||null,T.missing=y?.missing||null,T}let v=new Error(`Sub-graph '${r}' trigger rejected (${m.status}): ${d}`);throw v.code="SUBGRAPH_TRIGGER_FAILED",v.status=m.status,v.subgraph=r,v}let c=await m.json(),l=c?.data?.jobId||c?.jobId;if(!l)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(e.async)return E.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${l} (not waiting)`),{jobId:l,status:"accepted",workflow:r};let S=Number.isFinite(e.timeoutMs)?e.timeoutMs:gn,w=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:hn,b=`${s}/executions/${encodeURIComponent(l)}`,$=Date.now()+S,I="accepted",f=0;for(;Date.now()<$;){await new Promise(T=>setTimeout(T,w)),f+=1;let y=await fetch(b,{headers:{Authorization:`Bearer ${o}`}});if(!y.ok){if(y.status>=500){E.warn(`[sub-graph] status poll for ${l} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${l}: ${y.status}`)}let d=await y.json(),v=d?.data||d?.execution||d;if(I=v?.status||I,mn.has(I)){if(I!=="completed"){let V=new Error(`Sub-graph '${r}' (${l}) ended in status '${I}'`);throw V.subgraphJobId=l,V.subgraphStatus=I,V}let T=v?.finalState||v?.state||{},M=St(T,e.output);return E.info(`[sub-graph] '${r}' (${l}) completed after ${f} polls`),M}}let g=new Error(`Sub-graph '${r}' (${l}) timed out after ${Math.round(S/1e3)}s (last status: ${I})`);throw g.subgraphJobId=l,g.subgraphStatus=I,g}import{existsSync as _t,readFileSync as bn}from"node:fs";import{join as Re,dirname as bt}from"node:path";var fe=class{static async loadContext(e,t,n={}){let s={},i=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=bt(Re(t,e));for(let u of i){let p=await this.findAndMergeContextFiles(u,a,t);if(p){let m=u.replace(/\.[^.]+$/,"").toLowerCase();s[m]=p}}}let o=n.discovery||{};for(let[a,u]of Object.entries(o))try{let p=Re(t,u);_t(p)&&(s[a]=await this.loadFile(p))}catch(p){console.warn(`[workflow] could not load context '${a}' from '${u}': ${p.message}`)}return s}static async findAndMergeContextFiles(e,t,n){let s=[],i=t;for(;i.startsWith(n);){let o=Re(i,e);if(_t(o))try{s.unshift(await this.loadFile(o))}catch(u){console.warn(`[workflow] could not load ${e} from ${o}: ${u.message}`)}let a=bt(i);if(a===i)break;i=a}return s.length===0?null:s.every(o=>typeof o=="string")?s.join(`
34
+ ${i}`);let a=n(),u=a.cwd||process.cwd(),p=a.sessionPath;try{if(p){let c=Oe(p,Z);if(ot(c)){let w=JSON.parse(st(c,"utf-8"));w.currentNode=this.name,xe(c,JSON.stringify(w,null,2),"utf-8")}let l=Oe(p,"..",Z);if(ot(l))try{let w=JSON.parse(st(l,"utf-8"));w.currentNode=this.name,xe(l,JSON.stringify(w,null,2),"utf-8")}catch{}}}catch(c){E.debug(`[workflow] could not update session info: ${c.message}`)}let m=null;for(let c=0;c<=this.retries;c++)try{E.debug(`[workflow] node '${this.name}' attempt ${c}`);let l=n().config||{},w=l.agents||{},_=this.config.agent??w[this.name]??null,I={state:n()};_&&(I.preferredAgent=_);let $={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:p,config:l,nodeName:this.name,timeout:this.config?.timeout||3e5},b=e?._coreInvokeAgent;b||(b=(await Promise.resolve().then(()=>(ke(),Te))).invokeAgent);let f=await b(i,I,$),g,y;if(typeof f=="string"?(g=f,y=null):f.structured?(g=f.raw||JSON.stringify(f.structured,null,2),y=f.structured):(g=f.raw||JSON.stringify(f,null,2),y=f.extracted||null),p)try{let d=Oe(p,this.name,"raw_stream_output.txt");Kt(Xt(d),{recursive:!0}),xe(d,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(d){E.debug(`[workflow] could not save raw output: ${d.message}`)}if(this.isZodSchema&&y){E.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let d=y;if(typeof this.onComplete=="function")try{d=await this.onComplete(n(),y)}catch(v){E.warn(`[workflow] onComplete hook failed: ${v.message}`)}return{success:!0,output:d,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:g}),raw:g}}catch(d){throw new Error(`onComplete failed: ${d.message}`,{cause:d})}if(this.parser){let d=this.parser.parse(g);return E.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(d,null,2)}`),O.step("Output parsed"),{success:!0,output:d,raw:g}}return{success:!0,output:g,raw:g}}catch(l){m=l,c<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:m.message,raw:null}}};ee();ee();import{mkdirSync as tn,existsSync as J,statSync as gt,readdirSync as mt,rmSync as nn}from"node:fs";import{spawn as dt}from"node:child_process";import{join as W}from"node:path";import{pathToFileURL as rn}from"node:url";import{AsyncLocalStorage as sn}from"node:async_hooks";import{AsyncLocalStorage as Qt}from"node:async_hooks";var re=new Qt;function q(){let r=re.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 it(r,e){let t=re.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 re.run(n,e)}function at(r,e,t){let n=re.getStore()||q(),s=Object.freeze({...n,agent:r??n.agent??null,signal:e??n.signal??null});return re.run(s,t)}var Pe=new Map,Ne=new Map,ct=new Map;function lt(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"),ct.set(r,{...t,cachedAt:Date.now()})}function ut(r,e){Ne.set(r,"failed"),ct.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 on(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var P=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}},ft=new sn,ht=Promise.resolve();async function an(r,e){let t=r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(([o,a])=>typeof o=="string"&&o&&typeof a=="string"):[];if(t.length===0)return e();let n=ft.getStore()===!0,s=null;if(!n){let o=ht;ht=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 E.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await ft.run(!0,e)}finally{for(let[o,a]of i)a===void 0?delete process.env[o]:process.env[o]=a;s&&s()}}function cn(){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 P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:s}}async function ln({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(i){throw new P("network",`begin fetch failed: ${i.message}`)}let s=null;try{s=await n.json()}catch{}if(!n.ok){if(n.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(n.status===429){let i=s?.quotaInfo||{},o=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw o.code="SUBGRAPH_QUOTA_EXCEEDED",o.status=429,o.quotaInfo=i,o}if(n.status===400&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new P("begin-status",`begin returned ${n.status}`)}return s?.data||s}async function 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||E.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){E.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function un(r,e){let t=W(e,".ready"),n=W(e,"graph.mjs");if(J(t)&&J(n))return;tn(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(J(t)&&J(n))return;await new Promise(a=>setTimeout(a,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,p)=>{let m=dt("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),c=dt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});m.stdout.pipe(c.stdin);let l,w,_=()=>{if(l!==void 0&&w!==void 0){if(l!==0)return p(new Error(`curl exited ${l}`));if(w!==0)return p(new Error(`tar exited ${w}`));u()}};m.on("close",I=>{l=I,_()}),c.on("close",I=>{w=I,_()}),m.on("error",p),c.on("error",p)});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 P("bundle-extract-failed",o.message)}}async function pn(r){let e=W(r,"graph.mjs");if(!J(e))throw new P("entry-missing",`graph.mjs missing under ${r}`);let t;try{t=await import(rn(e).href)}catch(s){throw new P("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let n=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!n)throw new P("entry-class-missing","no buildGraph() class export found");return n}async function yt(r,e={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=q(),n;try{n=cn()}catch(d){throw d}E.debug(`[in-process subgraph] begin '${r}' parent=${t.executionId||"<root>"}`);let s=await ln({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:r,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:o,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:p,workflowUuid:m,bundleReady:c,nodeConfigs:l}=s,w=on();if(o&&o!==w)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new P("runtime-mismatch",`${w} vs ${o}`);if(!c||!a)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new P("no-bundle","workflow bundle not built yet");let _=pt(r);if(!_){let d=W(de,`${m}@${p||"0"}`);try{await un(a,d);try{fn()}catch{}}catch(v){throw v.fallback&&await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:v.message,code:v.reason}}}),v}try{_=await pn(d),lt(r,_,{workflowUuid:m,version:p,runtimeTag:o,cacheDir:d})}catch(v){throw ut(r,v),await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:v.message,code:v.reason||"IMPORT_FAILED"}}}),v.fallback?v:new P("import-failed",v.message)}}let I=Date.now(),$=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,b=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,f={...e.input||{},...b?{nodeConfigs:l}:{}},g,y;try{g=await an($,async()=>{let v=await(typeof _=="function"&&_.prototype?.buildGraph?new _:_).buildGraph();return it({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>v.run(e.parentAgent,f,{signal:e.signal}))}),y=g&&typeof g=="object"&&"state"in g?g.state:g}catch(d){throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:d.message,code:d.code||"CHILD_THREW",stack:d.stack},durationMs:Date.now()-I}}),d}if(g&&typeof g=="object"&&g.stoppedExternally){await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",finalState:y,durationMs:Date.now()-I}});let d=new Error(`Sub-graph '${r}' canceled by parent abort`);throw d.code="SUBGRAPH_CANCELED",d.subgraphJobId=i,d}return await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:y,durationMs:Date.now()-I}}),{finalState:y,executionId:i}}function dn(r){let e=0,t=[r];for(;t.length;){let n=t.pop(),s;try{s=gt(n)}catch{continue}if(s.isDirectory()){let i;try{i=mt(n)}catch{continue}for(let o of i)t.push(W(n,o))}else e+=s.size}return e}function fn({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=mt(de),t=[],n=0;for(let a of e){let u=W(de,a),p;try{p=gt(u)}catch{continue}let m=p.isDirectory()?dn(u):p.size;n+=m,t.push({name:a,full:u,size:m,mtimeMs:p.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),i=0,o=0;for(let a of t){if(n-i<=s)break;if(!J(W(a.full,".lock")))try{nn(a.full,{recursive:!0,force:!0}),i+=a.size,o+=1}catch(u){E.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return o>0&&E.info(`[sub-graph cache] evicted ${o} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:o,freedBytes:i,totalBytes:n-i}}catch(e){return E.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var hn=2e3,gn=600*1e3,mn=new Set(["completed","failed","canceled","timeout"]);function yn(){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 Sn(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function wn(){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 St(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 wt(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.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{E.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:y}=await yt(r,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),d=St(y,e.output);return E.info(`[sub-graph] '${r}' completed in-process`),d}catch(y){if(y instanceof P||y?.fallback)E.info(`[sub-graph] in-process fallback for '${r}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let s=yn(),i=Sn(),o=wn(),a=_n(),u=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(r)}/trigger`,p={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};E.info(`[sub-graph] dispatching '${r}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let m=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(p)});if(!m.ok){let y=null,d="";try{y=await m.json(),d=y?.error||y?.message||JSON.stringify(y)}catch{d=await m.text().catch(()=>"")}if(m.status===429){let T=y?.quotaInfo||{},M=new Error(`Sub-graph '${r}' blocked by execution quota (${T.used??"?"}/${T.limit??"?"} on plan ${T.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=r,M.quotaInfo=T,M}if(m.status===400){let T=new Error(`Sub-graph '${r}' rejected input: ${d}`);throw T.code="SUBGRAPH_INVALID_INPUT",T.status=400,T.subgraph=r,T.validationErrors=y?.validationErrors||null,T.missing=y?.missing||null,T}let v=new Error(`Sub-graph '${r}' trigger rejected (${m.status}): ${d}`);throw v.code="SUBGRAPH_TRIGGER_FAILED",v.status=m.status,v.subgraph=r,v}let c=await m.json(),l=c?.data?.jobId||c?.jobId;if(!l)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(e.async)return E.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${l} (not waiting)`),{jobId:l,status:"accepted",workflow:r};let w=Number.isFinite(e.timeoutMs)?e.timeoutMs:gn,_=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:hn,I=`${s}/executions/${encodeURIComponent(l)}`,$=Date.now()+w,b="accepted",f=0;for(;Date.now()<$;){await new Promise(T=>setTimeout(T,_)),f+=1;let y=await fetch(I,{headers:{Authorization:`Bearer ${o}`}});if(!y.ok){if(y.status>=500){E.warn(`[sub-graph] status poll for ${l} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${l}: ${y.status}`)}let d=await y.json(),v=d?.data||d?.execution||d;if(b=v?.status||b,mn.has(b)){if(b!=="completed"){let V=new Error(`Sub-graph '${r}' (${l}) ended in status '${b}'`);throw V.subgraphJobId=l,V.subgraphStatus=b,V}let T=v?.finalState||v?.state||{},M=St(T,e.output);return E.info(`[sub-graph] '${r}' (${l}) completed after ${f} polls`),M}}let g=new Error(`Sub-graph '${r}' (${l}) timed out after ${Math.round(w/1e3)}s (last status: ${b})`);throw g.subgraphJobId=l,g.subgraphStatus=b,g}import{existsSync as _t,readFileSync as In}from"node:fs";import{join as Re,dirname as It}from"node:path";var fe=class{static async loadContext(e,t,n={}){let s={},i=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=It(Re(t,e));for(let u of i){let p=await this.findAndMergeContextFiles(u,a,t);if(p){let m=u.replace(/\.[^.]+$/,"").toLowerCase();s[m]=p}}}let o=n.discovery||{};for(let[a,u]of Object.entries(o))try{let p=Re(t,u);_t(p)&&(s[a]=await this.loadFile(p))}catch(p){console.warn(`[workflow] could not load context '${a}' from '${u}': ${p.message}`)}return s}static async findAndMergeContextFiles(e,t,n){let s=[],i=t;for(;i.startsWith(n);){let o=Re(i,e);if(_t(o))try{s.unshift(await this.loadFile(o))}catch(u){console.warn(`[workflow] could not load ${e} from ${o}: ${u.message}`)}let a=It(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(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:n}=await import("url"),s=await import(n(e).href);return s.default||s}return t}};import{mkdirSync as vt,existsSync as Be,writeFileSync as It,unlinkSync as In}from"node:fs";import{join as z,resolve as At}from"node:path";import{config as En}from"dotenv";import{zodToJsonSchema as Et}from"zod-to-json-schema";import{z as he}from"zod";import $n from"handlebars";function vn({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 o=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${r} pid=${process.pid} ppid=${o} 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 m=(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=In(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 vt,existsSync as Be,writeFileSync as bt,unlinkSync as bn}from"node:fs";import{join as z,resolve as At}from"node:path";import{config as En}from"dotenv";import{zodToJsonSchema as Et}from"zod-to-json-schema";import{z as he}from"zod";import $n from"handlebars";function vn({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 o=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${r} pid=${process.pid} ppid=${o} 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 m=(new Error("session trace").stack||"").split(`
39
39
  `).slice(2,14).join(`
40
40
  `);console.log(`[zibby:session] stack (${r}):
41
- ${m}`)}}function An(){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 Tn(){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 At(String(e).trim())}catch{return String(e).trim()}}function kn(){An()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function xn({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 On(r={}){let e=Qe.map(i=>process.env[i]).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 Pn({cwd:r=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,o="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let p=At(String(process.env.ZIBBY_SESSION_PATH));p&&(s=p,o="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let p=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(p)a=p,o="ZIBBY_SESSION_ID";else{let c=e.sessionId!=null?String(e.sessionId).trim():"";c&&c!=="last"?(a=c,o="config.sessionId"):(a=On(e),o="generated")}i=i??Date.now();let m=e.paths?.output||pe;s=z(r,m,Ke,a)}let u=!Be(s);return u&&vt(s,{recursive:!0}),(u||o!=="initialState.sessionPath")&&vn({traceFrom:n,sessionId:a,sessionPath:s,idSource:o,mkdirFresh:u}),xn({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var $t=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 o=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:o.workflow,retries:o.retries,onComplete:o.onComplete,execute:async p=>{let m=p?.state&&typeof p.state.getAll=="function"?p.state.getAll():p,c;return typeof o.input=="function"?c=o.input(m):o.input&&typeof o.input=="object"?c=o.input:c={},wt(o.workflow,{input:c,async:o.async===!0,conversationId:typeof o.conversationId=="function"?o.conversationId(m):o.conversationId,output:o.output,timeoutMs:o.timeoutMs,pollIntervalMs:o.pollIntervalMs,signal:m?._signal,parentAgent:p?.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,i=t instanceof L?t:new L(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){let n=this.edges.get(e);return n===void 0?this.edges.set(e,t):typeof n=="string"?n!==t&&this.edges.set(e,[n,t]):Array.isArray(n)?n.includes(t)||n.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:n}={}){let s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:n}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,n=i=>{t.set(i,1);for(let o of this._simpleTargets(i)){if(!o||o==="END")continue;let a=t.get(o)||0;a===1?e.add(`${i}->${o}`):a===0&&n(o)}t.set(i,2)};this.entryPoint&&n(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,n,s,i){let o=n;for(let a=e.length-1;a>=0;a--){let u=e[a],p=o;o=()=>u(t,p,s,i)}return o()}serialize(){let e=[],t={};for(let[c,l]of this.nodes){let S=this.nodeTypeMap.get(c)||(l?.config?._isRouter===!0?"decision":c);e.push({id:c,type:S,data:{nodeType:S,label:c}});let w={};l._isCustomCode&&typeof l.execute=="function"&&(w.customCode=l.execute.toString());let b=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;b&&(w.description=b);let $=this.nodePrompts.get(c);if($)w.prompt=$;else if(typeof l.prompt=="function")try{let d=l.prompt({});typeof d=="string"&&d.trim()&&(w.prompt=d,w.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(w.executeCode=l.customExecute.toString()),typeof l?.config?.dispatchesWorkflow=="string"&&l.config.dispatchesWorkflow.trim()&&(w.dispatchesWorkflow=l.config.dispatchesWorkflow.trim()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let d=null;if(typeof he?.toJSONSchema=="function")try{d=he.toJSONSchema(l.outputSchema)}catch{}if(!d)try{d=Et(l.outputSchema,{target:"openApi3"})}catch{}w.outputSchema=d?{jsonSchema:d,variables:this._flattenJsonSchemaToVariables(d)}:{schema:l.outputSchema}}else w.outputSchema={schema:l.outputSchema};let I=(this.resolvedToolsMap||{})[c];I?.toolIds&&(w.tools=I.toolIds);let f=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;f&&f.length>0&&(w.skills=[...f]);let g=Array.isArray(l?.config?.plugins)?l.config.plugins:Array.isArray(l?.plugins)?l.plugins:null;g&&g.length>0&&(w.plugins=g.map(d=>d&&typeof d=="object"?{...d}:d));let y=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;y&&y.length>0&&(w.stores=y.map(d=>d&&typeof d=="object"?{...d}:d)),Object.keys(w).length>0&&(t[c]=w)}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 S of l)n.push({source:c,target:S});else if(l.conditional){let S=this.conditionalCodeMap.get(c)||l.routes.toString(),w=this._inferConditionalTargets(l.routes,l.labels),b=l.labels||{},$=this.nodes.get(c),I=$?.config?._isRouter===!0||this.nodeTypeMap.get(c)==="decision"||!$,f=c;if(!I){let g=`${c}__branch`;e.push({id:g,type:"decision",data:{nodeType:"decision",label:g}}),n.push({source:c,target:g}),f=g}for(let g of w){let y={source:f,target:g,data:{conditionalCode:S}};b[g]&&(y.label=b[g]),n.push(y)}}let s=c=>{if(!c)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(c)}catch{}try{return Et(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 i=0;for(let c of n)if(c.target==="END"){i+=1;let l=`END__${i}`;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)){i+=1;let l=`END__${i}`;e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:c,target:l})}let o=this._topoOrderNodes(e,n),a=this._runtimeSchema(),u=s(a||this.stateSchema),p=s(this.inputSchema),m=s(this.contextSchema);return{nodes:o,edges:n,nodeConfigs:t,stateSchema:u,inputSchema:p,contextSchema:m}}_topoOrderNodes(e,t){let n=new Map(e.map((c,l)=>[c.id,l])),s=new Map(e.map(c=>[c.id,c])),i=new Map(e.map(c=>[c.id,0])),o=new Map(e.map(c=>[c.id,[]]));for(let c of t)o.has(c.source)&&i.has(c.target)&&(o.get(c.source).push(c.target),i.set(c.target,i.get(c.target)+1));let a=new Set,u=new Set(n.keys()),p=[...u].filter(c=>i.get(c)===0),m=[];for(;m.length<e.length;){let c;if(p.length>0){if(p.sort((l,S)=>n.get(l)-n.get(S)),c=p.shift(),a.has(c))continue}else c=[...u].sort((l,S)=>n.get(l)-n.get(S))[0];a.add(c),u.delete(c),m.push(s.get(c));for(let l of o.get(c)||[])i.set(l,i.get(l)-1),i.get(l)<=0&&!a.has(l)&&p.push(l)}return m}_inferConditionalTargets(e,t){let n=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,o;for(;(o=i.exec(n))!==null;){let p=o[2]!==void 0?o[2]:o[3];p!==void 0&&p!==""&&s.add(p)}let a=new Set(["END","START","__end__","__start__"]);for(let p of this.nodes.keys())a.add(p);if(t&&typeof t=="object")for(let p of Object.keys(t))a.add(p);let u=new Set;for(let p of s)a.has(p)&&u.add(p);if(u.size===0){let p=/return\s+['"]([^'"]+)['"]/g,m;for(;(m=p.exec(n))!==null;)u.add(m[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||{},i=e.required||[];for(let[o,a]of Object.entries(s)){let u=t?`${t}.${o}`:o;n.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(o),optional:!i.includes(o)}),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,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${s}: ${i}`);else if(Array.isArray(i)){let o=i.length,a=i.filter(p=>p?.passed===!0).length,u=i.some(p=>p?.passed!==void 0);n.push(u?`${s}: ${a}/${o} passed${o-a?`, ${o-a} failed`:""}`:`${s}: ${o} 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");e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t)&&(t=e.normalizeInput(t)??t);let s=new AbortController;n.signal&&(n.signal.aborted?s.abort():n.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,o=t.cwd||process.cwd();En({path:z(o,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let _=z(o,".zibby.config.js");Be(_)&&(a=(await import(_)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let _=a?.agent;_?.provider?u=_.provider:_?.gemini?u="gemini":_?.claude?u="claude":_?.cursor?u="cursor":_?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let p=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},m=this._runtimeSchema();if(m){let _=m.safeParse(t);if(!_.success){let h=_.error.issues.map(B=>`${B.path.join(".")}: ${B.message}`);throw console.error("\u274C Initial state validation failed:"),h.forEach(B=>console.error(` - ${B}`)),new Error(`State validation failed: ${h.join(", ")}`)}O.step("State validated against schema")}let c=Tn(),l=t.sessionPath||c;l||kn();let{sessionPath:S,sessionTimestamp:w,sessionId:b}=Pn({cwd:o,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${b}`);let $=await fe.loadContext(t.specPath||"",o,p);Object.keys($).length>0&&O.step(`Context loaded: ${Object.keys($).join(", ")}`);let I=t.outputPath;!I&&t.specPath&&(e?.calculateOutputPath?I=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ce({...t,config:a,agentType:u,outputPath:I,sessionPath:S,sessionTimestamp:w,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(ve(),tt)),d=a.skills&&typeof a.skills=="object"?a.skills:{},v=Object.values(d).filter(_=>_&&typeof _=="object"&&typeof _.id=="string"),T=_=>{for(let h of v)if(h.id===_)return h;return y(_)},M=new Set;for(let[,_]of this.nodes)for(let h of _.config?.skills||[])M.add(h);for(let _ of M){let h=T(_);if(typeof h?.middleware=="function")try{let B=await h.middleware();typeof B=="function"&&g.set(_,B)}catch{}}let{backEdges:V,joinDegree:Tt}=this._analyzeFlow(),ge=new Map,K=[],me=(_,h,B)=>{if(!_||_==="END")return;let j=Tt.get(_)||0;if(B&&j>1&&!V.has(`${h}->${_}`)){let X=(ge.get(_)||0)+1;if(X<j){ge.set(_,X);return}ge.set(_,0)}K.includes(_)||K.push(_)};this.entryPoint&&K.push(this.entryPoint);let se=[],Ce=a?.recursionLimit??100,kt=0;try{for(;K.length>0;){let h=K.pop();if(!h||h==="END")continue;if(++kt>Ce)throw new Error(`Workflow exceeded recursion limit (${Ce}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let B=z(S,Xe);if(Be(B)){try{In(B)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
42
- \u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:se,stoppedExternally:!0};let j=this.nodes.get(h);if(!j)throw new Error(`Node '${h}' not found in graph`);let X=JSON.stringify({sessionPath:S,sessionTimestamp:w,currentNode:h,createdAt:new Date().toISOString(),config:f.get("config")}),xt=z(S,Z);It(xt,X,"utf-8");let Me=f.get("config")?.paths?.output||pe,Ot=z(o,Me,Z);vt(z(o,Me),{recursive:!0});try{It(Ot,X,"utf-8")}catch{}let je=t.onPipelineProgress;if(typeof je=="function")try{je({cwd:o,sessionPath:S,sessionId:b,outputBase:f.get("config")?.paths?.output||pe,currentNode:h})}catch{}let Pt=(this.resolvedToolsMap||{})[h]||null;f.set("_currentNodeTools",Pt);let Nt=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Nt[h]||{}),O.nodeStart(h);let De=Date.now(),oe=this.nodePrompts.get(h);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(ke(),Te));this._invokeAgent=k.invokeAgent}let Rt=this._invokeAgent,ye={},Bt=j.config?.skills||[];for(let k of Bt){let N=T(k);if(typeof N?.invokeAgentOptions=="function")try{let A=N.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:h});A&&typeof A=="object"&&(ye={...ye,...A})}catch(A){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${A.message}`)}}let Le=async(k,N,A={})=>{let C=Rt(k,N,{...ye,...A,signal:s.signal});return C.catch(()=>{}),s.signal.aborted?C:Promise.race([C,new Promise((Y,D)=>{let R=()=>{setTimeout(()=>{let Q=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);Q.name="AbortError",D(Q)},i)};s.signal.addEventListener("abort",R,{once:!0})})])},Ct=async(k={},N={})=>{let A=N.prompt||"";if(oe){let C=this._compiledPrompts.get(h);C||(C=$n.compile(oe,{noEscape:!0}),this._compiledPrompts.set(h,C));try{A=C(k)}catch(Y){throw console.error(`\u274C Template rendering failed for node '${h}':`,Y.message),new Error(`Template rendering failed: ${Y.message}`,{cause:Y})}}else if(!A)throw new Error(`No prompt template configured for node '${h}' and no prompt provided in options`);return Le(A,{state:f.getAll(),images:N.images||[]},{model:N.model||f.get("model"),workspace:f.get("workspace"),schema:N.schema,...N,signal:s.signal})},We=f.getAll(),Mt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of Mt)Object.prototype.hasOwnProperty.call(We,k)&&console.warn(`[workflow] node "${h}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ue={...We,state:f,invokeAgent:Ct,_coreInvokeAgent:Le,agent:e,nodeId:h,promptTemplate:oe,getPromptTemplate:()=>oe};try{let k=(j.config?.skills||[]).map(R=>g.get(R)).filter(Boolean),N=[...this.middleware,...k],A;A=await at(e,s.signal,async()=>N.length>0?this._composeMiddleware(N,h,async()=>j.execute(Ue,f),f.getAll(),f):j.execute(Ue,f));let C=Date.now()-De;if(se.push({node:h,success:A.success,duration:C,timestamp:new Date().toISOString()}),!A.success){if(s.signal.aborted)return O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:se,stoppedExternally:!0};f.append("errors",{node:h,error:A.error});let R=j.config?.retries||0,Q=`${h}_retries`,ie=f.getAll()[Q]||0;if(ie<R){O.stepInfo(`Retrying (attempt ${ie+1}/${R})`),f.update({[Q]:ie+1,[`${h}_raw`]:A.raw});continue}throw O.nodeFailed(h,A.error,{duration:C}),new Error(`Node '${h}' failed after ${ie} attempts: ${A.error}`)}f.update({[h]:A.output});let Y=this._summarizeNodeOutput(h,A.output);O.nodeComplete(h,{duration:C,details:Y});let D=this.edges.get(h);if(D)if(D.conditional){let R=D.routes(f.getAll());O.route(h,R),me(R,h,!1)}else if(Array.isArray(D))for(let R=D.length-1;R>=0;R--)me(D[R],h,!0);else me(D,h,!0)}catch(k){throw O.isInsideNode&&O.nodeFailed(h,k.message,{duration:Date.now()-De}),f.set("failed",!0),f.set("failedAt",h),k}}O.graphComplete();let _={success:!0,state:f.getAll(),executionLog:se};return e&&typeof e.onComplete=="function"&&await e.onComplete(_),_}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(_){console.warn(`[workflow] agent.cleanup() failed: ${_.message}`)}}}};export{$t as WorkflowGraph,kn as clearInheritedSessionEnvForFreshRun,On as generateWorkflowSessionId,Tn as readPinnedSessionPathFromEnv,Pn as resolveWorkflowSession,An as shouldTrustInheritedSessionEnv,xn as syncProcessEnvToSession};
41
+ ${m}`)}}function An(){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 Tn(){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 At(String(e).trim())}catch{return String(e).trim()}}function kn(){An()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function xn({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 On(r={}){let e=Qe.map(i=>process.env[i]).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 Pn({cwd:r=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,o="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let p=At(String(process.env.ZIBBY_SESSION_PATH));p&&(s=p,o="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let p=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(p)a=p,o="ZIBBY_SESSION_ID";else{let c=e.sessionId!=null?String(e.sessionId).trim():"";c&&c!=="last"?(a=c,o="config.sessionId"):(a=On(e),o="generated")}i=i??Date.now();let m=e.paths?.output||pe;s=z(r,m,Ke,a)}let u=!Be(s);return u&&vt(s,{recursive:!0}),(u||o!=="initialState.sessionPath")&&vn({traceFrom:n,sessionId:a,sessionPath:s,idSource:o,mkdirFresh:u}),xn({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var $t=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 o=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:o.workflow,retries:o.retries,onComplete:o.onComplete,execute:async p=>{let m=p?.state&&typeof p.state.getAll=="function"?p.state.getAll():p,c;return typeof o.input=="function"?c=o.input(m):o.input&&typeof o.input=="object"?c=o.input:c={},wt(o.workflow,{input:c,async:o.async===!0,conversationId:typeof o.conversationId=="function"?o.conversationId(m):o.conversationId,output:o.output,timeoutMs:o.timeoutMs,pollIntervalMs:o.pollIntervalMs,signal:m?._signal,parentAgent:p?.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,i=t instanceof L?t:new L(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){let n=this.edges.get(e);return n===void 0?this.edges.set(e,t):typeof n=="string"?n!==t&&this.edges.set(e,[n,t]):Array.isArray(n)?n.includes(t)||n.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:n}={}){let s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:n}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,n=i=>{t.set(i,1);for(let o of this._simpleTargets(i)){if(!o||o==="END")continue;let a=t.get(o)||0;a===1?e.add(`${i}->${o}`):a===0&&n(o)}t.set(i,2)};this.entryPoint&&n(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,n,s,i){let o=n;for(let a=e.length-1;a>=0;a--){let u=e[a],p=o;o=()=>u(t,p,s,i)}return o()}serialize(){let e=[],t={};for(let[c,l]of this.nodes){let w=this.nodeTypeMap.get(c)||(l?.config?._isRouter===!0?"decision":c);e.push({id:c,type:w,data:{nodeType:w,label:c}});let _={};l._isCustomCode&&typeof l.execute=="function"&&(_.customCode=l.execute.toString());let I=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;I&&(_.description=I);let $=this.nodePrompts.get(c);if($)_.prompt=$;else if(typeof l.prompt=="function")try{let d=l.prompt({});typeof d=="string"&&d.trim()&&(_.prompt=d,_.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(_.executeCode=l.customExecute.toString()),typeof l?.config?.dispatchesWorkflow=="string"&&l.config.dispatchesWorkflow.trim()&&(_.dispatchesWorkflow=l.config.dispatchesWorkflow.trim()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let d=null;if(typeof he?.toJSONSchema=="function")try{d=he.toJSONSchema(l.outputSchema)}catch{}if(!d)try{d=Et(l.outputSchema,{target:"openApi3"})}catch{}_.outputSchema=d?{jsonSchema:d,variables:this._flattenJsonSchemaToVariables(d)}:{schema:l.outputSchema}}else _.outputSchema={schema:l.outputSchema};let b=(this.resolvedToolsMap||{})[c];b?.toolIds&&(_.tools=b.toolIds);let f=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;f&&f.length>0&&(_.skills=[...f]);let g=Array.isArray(l?.config?.plugins)?l.config.plugins:Array.isArray(l?.plugins)?l.plugins:null;g&&g.length>0&&(_.plugins=g.map(d=>d&&typeof d=="object"?{...d}:d));let y=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;y&&y.length>0&&(_.stores=y.map(d=>d&&typeof d=="object"?{...d}:d)),Object.keys(_).length>0&&(t[c]=_)}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 w of l)n.push({source:c,target:w});else if(l.conditional){let w=this.conditionalCodeMap.get(c)||l.routes.toString(),_=this._inferConditionalTargets(l.routes,l.labels),I=l.labels||{},$=this.nodes.get(c),b=$?.config?._isRouter===!0||this.nodeTypeMap.get(c)==="decision"||!$,f=c;if(!b){let g=`${c}__branch`;e.push({id:g,type:"decision",data:{nodeType:"decision",label:g}}),n.push({source:c,target:g}),f=g}for(let g of _){let y={source:f,target:g,data:{conditionalCode:w}};I[g]&&(y.label=I[g]),n.push(y)}}let s=c=>{if(!c)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(c)}catch{}try{return Et(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 i=0;for(let c of n)if(c.target==="END"){i+=1;let l=`END__${i}`;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)){i+=1;let l=`END__${i}`;e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:c,target:l})}let o=this._topoOrderNodes(e,n),a=this._runtimeSchema(),u=s(a||this.stateSchema),p=s(this.inputSchema),m=s(this.contextSchema);return{nodes:o,edges:n,nodeConfigs:t,stateSchema:u,inputSchema:p,contextSchema:m}}_topoOrderNodes(e,t){let n=new Map(e.map((c,l)=>[c.id,l])),s=new Map(e.map(c=>[c.id,c])),i=new Map(e.map(c=>[c.id,0])),o=new Map(e.map(c=>[c.id,[]]));for(let c of t)o.has(c.source)&&i.has(c.target)&&(o.get(c.source).push(c.target),i.set(c.target,i.get(c.target)+1));let a=new Set,u=new Set(n.keys()),p=[...u].filter(c=>i.get(c)===0),m=[];for(;m.length<e.length;){let c;if(p.length>0){if(p.sort((l,w)=>n.get(l)-n.get(w)),c=p.shift(),a.has(c))continue}else c=[...u].sort((l,w)=>n.get(l)-n.get(w))[0];a.add(c),u.delete(c),m.push(s.get(c));for(let l of o.get(c)||[])i.set(l,i.get(l)-1),i.get(l)<=0&&!a.has(l)&&p.push(l)}return m}_inferConditionalTargets(e,t){let n=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,o;for(;(o=i.exec(n))!==null;){let p=o[2]!==void 0?o[2]:o[3];p!==void 0&&p!==""&&s.add(p)}let a=new Set(["END","START","__end__","__start__"]);for(let p of this.nodes.keys())a.add(p);if(t&&typeof t=="object")for(let p of Object.keys(t))a.add(p);let u=new Set;for(let p of s)a.has(p)&&u.add(p);if(u.size===0){let p=/return\s+['"]([^'"]+)['"]/g,m;for(;(m=p.exec(n))!==null;)u.add(m[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||{},i=e.required||[];for(let[o,a]of Object.entries(s)){let u=t?`${t}.${o}`:o;n.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(o),optional:!i.includes(o)}),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,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${s}: ${i}`);else if(Array.isArray(i)){let o=i.length,a=i.filter(p=>p?.passed===!0).length,u=i.some(p=>p?.passed!==void 0);n.push(u?`${s}: ${a}/${o} passed${o-a?`, ${o-a} failed`:""}`:`${s}: ${o} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(S){let h=new Error(`agent.normalizeInput() rejected the trigger input: ${S?.message||S}`);throw h.cause=S,h.code=S?.code||"NORMALIZE_INPUT_FAILED",h}let s=new AbortController;n.signal&&(n.signal.aborted?s.abort():n.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,o=t.cwd||process.cwd();En({path:z(o,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let S=z(o,".zibby.config.js");Be(S)&&(a=(await import(S)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let S=a?.agent;S?.provider?u=S.provider:S?.gemini?u="gemini":S?.claude?u="claude":S?.cursor?u="cursor":S?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let p=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},m=this._runtimeSchema();if(m){let S=m.safeParse(t);if(!S.success){let h=S.error.issues.map(B=>`${B.path.join(".")}: ${B.message}`);throw console.error("\u274C Initial state validation failed:"),h.forEach(B=>console.error(` - ${B}`)),new Error(`State validation failed: ${h.join(", ")}`)}O.step("State validated against schema")}let c=Tn(),l=t.sessionPath||c;l||kn();let{sessionPath:w,sessionTimestamp:_,sessionId:I}=Pn({cwd:o,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${I}`);let $=await fe.loadContext(t.specPath||"",o,p);Object.keys($).length>0&&O.step(`Context loaded: ${Object.keys($).join(", ")}`);let b=t.outputPath;!b&&t.specPath&&(e?.calculateOutputPath?b=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ce({...t,config:a,agentType:u,outputPath:b,sessionPath:w,sessionTimestamp:_,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(ve(),tt)),d=a.skills&&typeof a.skills=="object"?a.skills:{},v=Object.values(d).filter(S=>S&&typeof S=="object"&&typeof S.id=="string"),T=S=>{for(let h of v)if(h.id===S)return h;return y(S)},M=new Set;for(let[,S]of this.nodes)for(let h of S.config?.skills||[])M.add(h);for(let S of M){let h=T(S);if(typeof h?.middleware=="function")try{let B=await h.middleware();typeof B=="function"&&g.set(S,B)}catch{}}let{backEdges:V,joinDegree:Tt}=this._analyzeFlow(),ge=new Map,K=[],me=(S,h,B)=>{if(!S||S==="END")return;let j=Tt.get(S)||0;if(B&&j>1&&!V.has(`${h}->${S}`)){let X=(ge.get(S)||0)+1;if(X<j){ge.set(S,X);return}ge.set(S,0)}K.includes(S)||K.push(S)};this.entryPoint&&K.push(this.entryPoint);let se=[],Ce=a?.recursionLimit??100,kt=0;try{for(;K.length>0;){let h=K.pop();if(!h||h==="END")continue;if(++kt>Ce)throw new Error(`Workflow exceeded recursion limit (${Ce}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let B=z(w,Xe);if(Be(B)){try{bn(B)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
42
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:se,stoppedExternally:!0};let j=this.nodes.get(h);if(!j)throw new Error(`Node '${h}' not found in graph`);let X=JSON.stringify({sessionPath:w,sessionTimestamp:_,currentNode:h,createdAt:new Date().toISOString(),config:f.get("config")}),xt=z(w,Z);bt(xt,X,"utf-8");let Me=f.get("config")?.paths?.output||pe,Ot=z(o,Me,Z);vt(z(o,Me),{recursive:!0});try{bt(Ot,X,"utf-8")}catch{}let je=t.onPipelineProgress;if(typeof je=="function")try{je({cwd:o,sessionPath:w,sessionId:I,outputBase:f.get("config")?.paths?.output||pe,currentNode:h})}catch{}let Pt=(this.resolvedToolsMap||{})[h]||null;f.set("_currentNodeTools",Pt);let Nt=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Nt[h]||{}),O.nodeStart(h);let De=Date.now(),oe=this.nodePrompts.get(h);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(ke(),Te));this._invokeAgent=k.invokeAgent}let Rt=this._invokeAgent,ye={},Bt=j.config?.skills||[];for(let k of Bt){let N=T(k);if(typeof N?.invokeAgentOptions=="function")try{let A=N.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:h});A&&typeof A=="object"&&(ye={...ye,...A})}catch(A){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${A.message}`)}}let Le=async(k,N,A={})=>{let C=Rt(k,N,{...ye,...A,signal:s.signal});return C.catch(()=>{}),s.signal.aborted?C:Promise.race([C,new Promise((Y,D)=>{let R=()=>{setTimeout(()=>{let Q=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);Q.name="AbortError",D(Q)},i)};s.signal.addEventListener("abort",R,{once:!0})})])},Ct=async(k={},N={})=>{let A=N.prompt||"";if(oe){let C=this._compiledPrompts.get(h);C||(C=$n.compile(oe,{noEscape:!0}),this._compiledPrompts.set(h,C));try{A=C(k)}catch(Y){throw console.error(`\u274C Template rendering failed for node '${h}':`,Y.message),new Error(`Template rendering failed: ${Y.message}`,{cause:Y})}}else if(!A)throw new Error(`No prompt template configured for node '${h}' and no prompt provided in options`);return Le(A,{state:f.getAll(),images:N.images||[]},{model:N.model||f.get("model"),workspace:f.get("workspace"),schema:N.schema,...N,signal:s.signal})},We=f.getAll(),Mt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of Mt)Object.prototype.hasOwnProperty.call(We,k)&&console.warn(`[workflow] node "${h}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ue={...We,state:f,invokeAgent:Ct,_coreInvokeAgent:Le,agent:e,nodeId:h,promptTemplate:oe,getPromptTemplate:()=>oe};try{let k=(j.config?.skills||[]).map(R=>g.get(R)).filter(Boolean),N=[...this.middleware,...k],A;A=await at(e,s.signal,async()=>N.length>0?this._composeMiddleware(N,h,async()=>j.execute(Ue,f),f.getAll(),f):j.execute(Ue,f));let C=Date.now()-De;if(se.push({node:h,success:A.success,duration:C,timestamp:new Date().toISOString()}),!A.success){if(s.signal.aborted)return O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:se,stoppedExternally:!0};f.append("errors",{node:h,error:A.error});let R=j.config?.retries||0,Q=`${h}_retries`,ie=f.getAll()[Q]||0;if(ie<R){O.stepInfo(`Retrying (attempt ${ie+1}/${R})`),f.update({[Q]:ie+1,[`${h}_raw`]:A.raw});continue}throw O.nodeFailed(h,A.error,{duration:C}),new Error(`Node '${h}' failed after ${ie} attempts: ${A.error}`)}f.update({[h]:A.output});let Y=this._summarizeNodeOutput(h,A.output);O.nodeComplete(h,{duration:C,details:Y});let D=this.edges.get(h);if(D)if(D.conditional){let R=D.routes(f.getAll());O.route(h,R),me(R,h,!1)}else if(Array.isArray(D))for(let R=D.length-1;R>=0;R--)me(D[R],h,!0);else me(D,h,!0)}catch(k){throw O.isInsideNode&&O.nodeFailed(h,k.message,{duration:Date.now()-De}),f.set("failed",!0),f.set("failedAt",h),k}}O.graphComplete();let S={success:!0,state:f.getAll(),executionLog:se};return e&&typeof e.onComplete=="function"&&await e.onComplete(S),S}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(S){console.warn(`[workflow] agent.cleanup() failed: ${S.message}`)}}}};export{$t as WorkflowGraph,kn as clearInheritedSessionEnvForFreshRun,On as generateWorkflowSessionId,Tn as readPinnedSessionPathFromEnv,Pn as resolveWorkflowSession,An as shouldTrustInheritedSessionEnv,xn as syncProcessEnvToSession};
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- var yo=Object.defineProperty;var xe=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var Se=(o,e,t)=>()=>{if(t)throw t[0];try{return o&&(e=o(o=0)),e}catch(n){throw t=[n],n}};var ct=(o,e)=>{for(var t in e)yo(o,t,{get:e[t],enumerable:!0})};function _o(o){ae.impl={...dt,...o}}var lt,dt,ae,v,W=Se(()=>{lt=()=>{},dt={debug:lt,info:lt,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},ae={impl:dt};v={debug:(...o)=>ae.impl.debug?.(...o),info:(...o)=>ae.impl.info?.(...o),warn:(...o)=>ae.impl.warn?.(...o),error:(...o)=>ae.impl.error?.(...o)}});var Be,Me=Se(()=>{Be=class{constructor(e,t,n=0){this.name=e,this.description=t,this.priority=n}async invoke(e,t={}){throw new Error(`${this.constructor.name}.invoke() must be implemented`)}canHandle(e){throw new Error(`${this.constructor.name}.canHandle() must be implemented`)}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var $t={};ct($t,{clearSkills:()=>vt,getAllSkills:()=>bt,getSkill:()=>q,getSkillSource:()=>Et,hasSkill:()=>_t,listSkillIds:()=>It,registerSkill:()=>St});function St(o,e={}){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:n=!1}=e,s=o.id;if(H.has(s)&&!n){let i=de.get(s);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${s}" is already registered by ${a}; ${l} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}H.set(s,Object.freeze({...o})),t===void 0?de.delete(s):de.set(s,t)}function q(o){return H.get(o)||null}function _t(o){return H.has(o)}function Et(o){return de.get(o)||null}function bt(){return new Map(H)}function It(){return Array.from(H.keys())}function vt(){H.clear(),de.clear()}var De,Le,H,de,ue=Se(()=>{De=Symbol.for("@zibby/agent-workflow.skills"),Le=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[De]||(globalThis[De]=new Map);globalThis[Le]||(globalThis[Le]=new Map);H=globalThis[De],de=globalThis[Le]});var pe={};ct(pe,{getAgentStrategy:()=>We,invokeAgent:()=>xt,listStrategies:()=>kt,registerStrategy:()=>Tt,resolveInvocationModel:()=>At});function Tt(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=z.findIndex(t=>t.getName()===o.getName());e>=0?z[e]=o:z.push(o)}function kt(){return z.map(o=>o.getName())}function At({config:o={},options:e={},strategyName:t,envModel:n}={}){let s=o.models||{},i=e.nodeName&&s[e.nodeName]||null,r=s.default||null,a=o.agent?.[t]?.model||null,l=(typeof n=="string"?n.trim():"")||null;return i||r||a||e.model||l||null}function We(o={}){let{state:e={},preferredAgent:t=null}=o,n=t||e.agentType||process.env.AGENT_TYPE;if(!n){let i=z.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}v.debug(`[workflow] agent selection: requested=${n}`);let s=z.find(i=>i.getName()===n);if(!s){let i=z.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${i}`)}if(!s.canHandle(o))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return v.debug(`[workflow] using agent: ${s.getName()}`),s}async function xt(o,e={},t={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:n},i=We(s),r=n.config||t.config||{},a=At({config:r,options:t,strategyName:i.name,envModel:process.env.MODEL}),l={...t,model:a,workspace:n.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],extraMcpServers:t.extraMcpServers||n.extraMcpServers||e.extraMcpServers||[],plugins:t.plugins||e.plugins||[],config:r},u=o,f=l.skills||[];if(f.length>0&&!t.skipPromptFragments){let m=t.connectedIntegrations;if(!m){let b=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof b=="string"&&b.trim()!==""){m={};for(let S of b.split(",").map(h=>h.trim()).filter(Boolean))m[S]=!0}}let g=b=>{let S=b&&b.requiresIntegration;return!S||!m?!0:(Array.isArray(S)?S:[S]).some(w=>m[w]===!0)},y=f.map(b=>{let S=q(b);if(!g(S))return null;let h=S?.promptFragment;return typeof h=="function"?h():h}).filter(Boolean);y.length>0&&(u+=`
1
+ var yo=Object.defineProperty;var xe=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var Se=(o,e,t)=>()=>{if(t)throw t[0];try{return o&&(e=o(o=0)),e}catch(n){throw t=[n],n}};var ct=(o,e)=>{for(var t in e)yo(o,t,{get:e[t],enumerable:!0})};function _o(o){ae.impl={...dt,...o}}var lt,dt,ae,v,W=Se(()=>{lt=()=>{},dt={debug:lt,info:lt,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},ae={impl:dt};v={debug:(...o)=>ae.impl.debug?.(...o),info:(...o)=>ae.impl.info?.(...o),warn:(...o)=>ae.impl.warn?.(...o),error:(...o)=>ae.impl.error?.(...o)}});var Me,Be=Se(()=>{Me=class{constructor(e,t,n=0){this.name=e,this.description=t,this.priority=n}async invoke(e,t={}){throw new Error(`${this.constructor.name}.invoke() must be implemented`)}canHandle(e){throw new Error(`${this.constructor.name}.canHandle() must be implemented`)}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var $t={};ct($t,{clearSkills:()=>vt,getAllSkills:()=>bt,getSkill:()=>q,getSkillSource:()=>Et,hasSkill:()=>_t,listSkillIds:()=>It,registerSkill:()=>St});function St(o,e={}){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:n=!1}=e,s=o.id;if(H.has(s)&&!n){let i=de.get(s);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${s}" is already registered by ${a}; ${l} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}H.set(s,Object.freeze({...o})),t===void 0?de.delete(s):de.set(s,t)}function q(o){return H.get(o)||null}function _t(o){return H.has(o)}function Et(o){return de.get(o)||null}function bt(){return new Map(H)}function It(){return Array.from(H.keys())}function vt(){H.clear(),de.clear()}var De,Le,H,de,ue=Se(()=>{De=Symbol.for("@zibby/agent-workflow.skills"),Le=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[De]||(globalThis[De]=new Map);globalThis[Le]||(globalThis[Le]=new Map);H=globalThis[De],de=globalThis[Le]});var pe={};ct(pe,{getAgentStrategy:()=>We,invokeAgent:()=>xt,listStrategies:()=>kt,registerStrategy:()=>Tt,resolveInvocationModel:()=>At});function Tt(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=z.findIndex(t=>t.getName()===o.getName());e>=0?z[e]=o:z.push(o)}function kt(){return z.map(o=>o.getName())}function At({config:o={},options:e={},strategyName:t,envModel:n}={}){let s=o.models||{},i=e.nodeName&&s[e.nodeName]||null,r=s.default||null,a=o.agent?.[t]?.model||null,l=(typeof n=="string"?n.trim():"")||null;return i||r||a||e.model||l||null}function We(o={}){let{state:e={},preferredAgent:t=null}=o,n=t||e.agentType||process.env.AGENT_TYPE;if(!n){let i=z.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}v.debug(`[workflow] agent selection: requested=${n}`);let s=z.find(i=>i.getName()===n);if(!s){let i=z.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${i}`)}if(!s.canHandle(o))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return v.debug(`[workflow] using agent: ${s.getName()}`),s}async function xt(o,e={},t={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:n},i=We(s),r=n.config||t.config||{},a=At({config:r,options:t,strategyName:i.name,envModel:process.env.MODEL}),l={...t,model:a,workspace:n.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],extraMcpServers:t.extraMcpServers||n.extraMcpServers||e.extraMcpServers||[],plugins:t.plugins||e.plugins||[],config:r},u=o,f=l.skills||[];if(f.length>0&&!t.skipPromptFragments){let m=t.connectedIntegrations;if(!m){let I=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof I=="string"&&I.trim()!==""){m={};for(let _ of I.split(",").map(h=>h.trim()).filter(Boolean))m[_]=!0}}let g=I=>{let _=I&&I.requiresIntegration;return!_||!m?!0:(Array.isArray(_)?_:[_]).some(S=>m[S]===!0)},y=f.map(I=>{let _=q(I);if(!g(_))return null;let h=_?.promptFragment;return typeof h=="function"?h():h}).filter(Boolean);y.length>0&&(u+=`
2
2
 
3
3
  ${y.join(`
4
4
 
5
- `)}`)}let d=n._currentNodeConfig?.stores;if(Array.isArray(d)&&d.length>0&&typeof d[0]=="object"){let m=d.length<=8,g=d.map(y=>{let b=y?.id??y?.storeId??"",S=(y?.name??"").toString().trim()||b,h=y?.type?` \xB7 ${y.type}`:"",w=(y?.description||"").toString().replace(/\s+/g," ").trim(),E=`- ${S} \xB7 ${w||"(no description)"}${h} (id: ${b})`;if(m&&y?.schema&&typeof y.schema=="object"){let p=y.schema.properties&&typeof y.schema.properties=="object"?Object.keys(y.schema.properties):Object.keys(y.schema);p.length&&(E+=`
5
+ `)}`)}let d=n._currentNodeConfig?.stores;if(Array.isArray(d)&&d.length>0&&typeof d[0]=="object"){let m=d.length<=8,g=d.map(y=>{let I=y?.id??y?.storeId??"",_=(y?.name??"").toString().trim()||I,h=y?.type?` \xB7 ${y.type}`:"",S=(y?.description||"").toString().replace(/\s+/g," ").trim(),E=`- ${_} \xB7 ${S||"(no description)"}${h} (id: ${I})`;if(m&&y?.schema&&typeof y.schema=="object"){let p=y.schema.properties&&typeof y.schema.properties=="object"?Object.keys(y.schema.properties):Object.keys(y.schema);p.length&&(E+=`
6
6
  fields: ${p.join(", ")}`)}return E});u+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
@@ -14,7 +14,7 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
14
14
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
15
15
 
16
16
  ${c}
17
- `),v.debug(`[workflow] prompt length: ${u.length} chars`),i.invoke(u,l)}var Fe,z,X=Se(()=>{Me();W();ue();Fe=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Fe]||(globalThis[Fe]=[]);z=globalThis[Fe]});var wo=new Set(["__proto__","constructor","prototype"]);function Ne(o){if(wo.has(o))throw new Error(`Invalid state key: "${o}"`)}var se=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){Ne(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let n of t)Ne(n);this._history.push({...this._state});for(let n of t)this._state[n]=e[n]}append(e,t){Ne(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import J from"handlebars";var ie=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let n=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of n)try{return this.validate(JSON.parse(s))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[n,s]of Object.entries(this.schema)){if(s.required&&!(n in e)&&t.push(`Missing required field: ${n}`),n in e&&s.type){let i=typeof e[n];i!==s.type&&t.push(`Field '${n}' expected ${s.type}, got ${i}`)}if(s.validate&&n in e){let i=s.validate(e[n]);i&&t.push(`Field '${n}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
17
+ `),v.debug(`[workflow] prompt length: ${u.length} chars`),i.invoke(u,l)}var Fe,z,X=Se(()=>{Be();W();ue();Fe=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Fe]||(globalThis[Fe]=[]);z=globalThis[Fe]});var wo=new Set(["__proto__","constructor","prototype"]);function Ne(o){if(wo.has(o))throw new Error(`Invalid state key: "${o}"`)}var se=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){Ne(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let n of t)Ne(n);this._history.push({...this._state});for(let n of t)this._state[n]=e[n]}append(e,t){Ne(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import J from"handlebars";var ie=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let n=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of n)try{return this.validate(JSON.parse(s))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[n,s]of Object.entries(this.schema)){if(s.required&&!(n in e)&&t.push(`Missing required field: ${n}`),n in e&&s.type){let i=typeof e[n];i!==s.type&&t.push(`Field '${n}' expected ${s.type}, got ${i}`)}if(s.validate&&n in e){let i=s.validate(e[n]);i&&t.push(`Field '${n}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
18
18
  ${t.join(`
19
19
  `)}`);return e}},So={string:(o=!0)=>({type:"string",required:o}),number:(o=!0)=>({type:"number",required:o}),boolean:(o=!0)=>({type:"boolean",required:o}),array:(o=!0)=>({type:"object",required:o,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(o,e=!0)=>({type:"string",required:e,validate:t=>o.includes(t)?null:`must be one of: ${o.join(", ")}`})};W();import{writeFileSync as Ue,readFileSync as Nt,existsSync as Ot,mkdirSync as To}from"node:fs";import{join as Ge,dirname as ko}from"node:path";import N from"chalk";var wt="__WORKFLOW_GRAPH_LOG__",ce=N.gray("\u2502"),Eo=N.gray("\u250C"),ut=N.gray("\u2514"),Oe=N.green("\u25C6"),pt=N.hex("#c084fc")("\u25C6"),ft=N.hex("#2dd4bf")("\u25C6"),Pe=N.red("\u25C6"),ht=`${ce} `,gt=2;function mt(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function yt(o,e){return(t,n,s)=>{if(typeof t!="string")return o(t,n,s);let i=process.stdout.columns||120,r="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(r+=ht,e.col=gt,e.lineStart=!1),l===`
20
20
  `?(r+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,r+=l):e.inEsc?(r+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,r+=l,e.col>=i&&(r+=`
@@ -31,15 +31,15 @@ ${ht}`,e.col=gt))}return o(r,n,s)}}var _e=class{constructor(){this._currentNode=
31
31
  `)}stepFail(e){this._origStdoutWrite?this._writeDot(Pe,N.red(e)):process.stdout.write.bind(process.stdout)(`${ce} ${Pe} ${N.red(e)}
32
32
  `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Eo} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:n,details:s}=t;if(s)for(let r of s)this._rawWrite(`${Oe} ${r}`);let i=n?N.dim(` ${mt(n)}`):"";this._rawWrite(`${ut} ${N.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,n={}){this._stopIntercepting();let{duration:s}=n,i=s?N.dim(` ${mt(s)}`):"";this._rawWrite(`${Pe} ${N.red(t)}`),this._rawWrite(`${ut} ${N.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(N.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},x=new _e;var le=".zibby/output",Ce="sessions",G=".session-info.json",Re=".zibby-stop",bo="result.json",Io="raw_stream_output.txt",vo="events.json",$o=Object.freeze(["codebase-memory","code-scan","artifact"]),je=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];J.helpers.inc||J.registerHelper("inc",o=>Number(o)+1);J.helpers.json||J.registerHelper("json",o=>JSON.stringify(o,null,2));J.helpers.eq||J.registerHelper("eq",(o,e)=>o===e);var F=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new ie(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return v.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let n=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=d=>t&&typeof t.get=="function"?t.get(d):e?.[d];if(typeof this.customExecute=="function"){v.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let d=await this.customExecute(e);return typeof d=="object"&&d!==null&&d.success===!1?{success:!1,error:d.error||"Node execution failed",raw:d.raw||null}:this.isZodSchema?(v.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(d),raw:null}):{success:!0,output:d,raw:null}}catch(d){return v.error(`[workflow] node '${this.name}' failed: ${d.message}`),d.name==="ZodError"&&v.error(`Schema errors: ${JSON.stringify(d.issues||d.errors,null,2)}`),{success:!1,error:d.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=J.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(n())):i=this.prompt;let r=s("_skillHints");r&&(i=`${r}
33
33
 
34
- ${i}`);let a=n(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let d=Ge(u,G);if(Ot(d)){let m=JSON.parse(Nt(d,"utf-8"));m.currentNode=this.name,Ue(d,JSON.stringify(m,null,2),"utf-8")}let c=Ge(u,"..",G);if(Ot(c))try{let m=JSON.parse(Nt(c,"utf-8"));m.currentNode=this.name,Ue(c,JSON.stringify(m,null,2),"utf-8")}catch{}}}catch(d){v.debug(`[workflow] could not update session info: ${d.message}`)}let f=null;for(let d=0;d<=this.retries;d++)try{v.debug(`[workflow] node '${this.name}' attempt ${d}`);let c=n().config||{},m=c.agents||{},g=this.config.agent??m[this.name]??null,y={state:n()};g&&(y.preferredAgent=g);let b={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:u,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},S=e?._coreInvokeAgent;S||(S=(await Promise.resolve().then(()=>(X(),pe))).invokeAgent);let h=await S(i,y,b),w,E;if(typeof h=="string"?(w=h,E=null):h.structured?(w=h.raw||JSON.stringify(h.structured,null,2),E=h.structured):(w=h.raw||JSON.stringify(h,null,2),E=h.extracted||null),u)try{let p=Ge(u,this.name,"raw_stream_output.txt");To(ko(p),{recursive:!0}),Ue(p,typeof w=="string"?w:JSON.stringify(w),"utf-8")}catch(p){v.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&E){v.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(E,null,2)}`);let p=E;if(typeof this.onComplete=="function")try{p=await this.onComplete(n(),E)}catch($){v.warn(`[workflow] onComplete hook failed: ${$.message}`)}return{success:!0,output:p,raw:w}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:w}),raw:w}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(w);return v.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),x.step("Output parsed"),{success:!0,output:p,raw:w}}return{success:!0,output:w,raw:w}}catch(c){f=c,d<this.retries&&v.info(`[workflow] node '${this.name}' failed, retrying (${d+1}/${this.retries})\u2026`)}return{success:!1,error:f.message,raw:null}}};W();W();import{mkdirSync as No,existsSync as Z,statSync as Wt,readdirSync as Ut,rmSync as Oo}from"node:fs";import{spawn as Dt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as Po}from"node:url";import{AsyncLocalStorage as Co}from"node:async_hooks";import{AsyncLocalStorage as Ao}from"node:async_hooks";var fe=new Ao;function Q(){let o=fe.getStore();return o||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function Pt(o,e){let t=fe.getStore()||Q(),n=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null,agent:o.agent!==void 0?o.agent:t.agent??null,signal:o.signal!==void 0?o.signal:t.signal??null});return fe.run(n,e)}function Ct(o,e,t){let n=fe.getStore()||Q(),s=Object.freeze({...n,agent:o??n.agent??null,signal:e??n.signal??null});return fe.run(s,t)}var He=new Map,ze=new Map,Rt=new Map;function jt(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");He.set(o,e),ze.set(o,"ready"),Rt.set(o,{...t,cachedAt:Date.now()})}function Bt(o,e){ze.set(o,"failed"),Rt.set(o,{error:e?.message||String(e),failedAt:Date.now()}),He.delete(o)}function Mt(o){return ze.get(o)==="ready"?He.get(o):null}var Ee=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Ro(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var O=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"}},Lt=new Co,Ft=Promise.resolve();async function jo(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([r,a])=>typeof r=="string"&&r&&typeof a=="string"):[];if(t.length===0)return e();let n=Lt.getStore()===!0,s=null;if(!n){let r=Ft;Ft=new Promise(a=>{s=a}),await r}let i=new Map;try{for(let[r,a]of t)i.set(r,Object.prototype.hasOwnProperty.call(process.env,r)?process.env[r]:void 0),process.env[r]=a;return v.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await Lt.run(!0,e)}finally{for(let[r,a]of i)a===void 0?delete process.env[r]:process.env[r]=a;s&&s()}}function Bo(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,n=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!n||!s)throw new O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:s}}async function Mo({apiBase:o,authToken:e,body:t}){let n;try{n=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(i){throw new O("network",`begin fetch failed: ${i.message}`)}let s=null;try{s=await n.json()}catch{}if(!n.ok){if(n.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(n.status===429){let i=s?.quotaInfo||{},r=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw r.code="SUBGRAPH_QUOTA_EXCEEDED",r.status=429,r.quotaInfo=i,r}if(n.status===400&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new O("begin-status",`begin returned ${n.status}`)}return s?.data||s}async function Y({apiBase:o,authToken:e,payload:t}){try{let n=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});n.ok||v.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){v.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function Do(o,e){let t=U(e,".ready"),n=U(e,"graph.mjs");if(Z(t)&&Z(n))return;No(e,{recursive:!0});let s=U(e,".lock"),i=!1;try{let{openSync:r,closeSync:a}=await import("node:fs"),l=r(s,"wx");a(l),i=!0}catch(r){if(r.code!=="EEXIST")throw r}if(!i){let r=Date.now()+3e4;for(;Date.now()<r;){if(Z(t)&&Z(n))return;await new Promise(a=>setTimeout(a,100))}throw new O("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let f=Dt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),d=Dt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(d.stdin);let c,m,g=()=>{if(c!==void 0&&m!==void 0){if(c!==0)return u(new Error(`curl exited ${c}`));if(m!==0)return u(new Error(`tar exited ${m}`));l()}};f.on("close",y=>{c=y,g()}),d.on("close",y=>{m=y,g()}),f.on("error",u),d.on("error",u)});let{writeFileSync:r,unlinkSync:a}=await import("node:fs");r(t,"");try{a(s)}catch{}}catch(r){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new O("bundle-extract-failed",r.message)}}async function Lo(o){let e=U(o,"graph.mjs");if(!Z(e))throw new O("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(Po(e).href)}catch(s){throw new O("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 O("entry-class-missing","no buildGraph() class export found");return n}async function Gt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=Q(),n;try{n=Bo()}catch(p){throw p}v.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let s=await Mo({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:r,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:f,bundleReady:d,nodeConfigs:c}=s,m=Ro();if(r&&r!==m)throw await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new O("runtime-mismatch",`${m} vs ${r}`);if(!d||!a)throw await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new O("no-bundle","workflow bundle not built yet");let g=Mt(o);if(!g){let p=U(Ee,`${f}@${u||"0"}`);try{await Do(a,p);try{Wo()}catch{}}catch($){throw $.fallback&&await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{g=await Lo(p),jt(o,g,{workflowUuid:f,version:u,runtimeTag:r,cacheDir:p})}catch($){throw Bt(o,$),await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new O("import-failed",$.message)}}let y=Date.now(),b=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,S=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...S?{nodeConfigs:c}:{}},w,E;try{w=await jo(b,async()=>{let $=await(typeof g=="function"&&g.prototype?.buildGraph?new g:g).buildGraph();return Pt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,h,{signal:e.signal}))}),E=w&&typeof w=="object"&&"state"in w?w.state:w}catch(p){throw await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-y}}),p}if(w&&typeof w=="object"&&w.stoppedExternally){await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",finalState:E,durationMs:Date.now()-y}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:E,durationMs:Date.now()-y}}),{finalState:E,executionId:i}}function Fo(o){let e=0,t=[o];for(;t.length;){let n=t.pop(),s;try{s=Wt(n)}catch{continue}if(s.isDirectory()){let i;try{i=Ut(n)}catch{continue}for(let r of i)t.push(U(n,r))}else e+=s.size}return e}function Wo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Z(Ee))return{evicted:0,freedBytes:0};let e=Ut(Ee),t=[],n=0;for(let a of e){let l=U(Ee,a),u;try{u=Wt(l)}catch{continue}let f=u.isDirectory()?Fo(l):u.size;n+=f,t.push({name:a,full:l,size:f,mtimeMs:u.mtimeMs})}if(n<=o)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(o*.7),i=0,r=0;for(let a of t){if(n-i<=s)break;if(!Z(U(a.full,".lock")))try{Oo(a.full,{recursive:!0,force:!0}),i+=a.size,r+=1}catch(l){v.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return r>0&&v.info(`[sub-graph cache] evicted ${r} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:r,freedBytes:i,totalBytes:n-i}}catch(e){return v.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Uo=2e3,Go=600*1e3,Ho=new Set(["completed","failed","canceled","timeout"]);function zo(){let o=process.env.PROGRESS_API_URL;if(!o)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return o.replace(/\/executions\/?$/,"")}function Jo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Yo(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Zo(){return process.env.EXECUTION_ID||null}function Ht(o,e){return e==null?o:typeof e=="function"?e(o):typeof e=="string"?e.split(".").reduce((t,n)=>t==null?t:t[n],o):o}async function Je(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=Q();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=n)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{v.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:E}=await Gt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=Ht(E,e.output);return v.info(`[sub-graph] '${o}' completed in-process`),p}catch(E){if(E instanceof O||E?.fallback)v.info(`[sub-graph] in-process fallback for '${o}': ${E.reason||"unknown"} \u2014 using HTTP`);else throw E}let s=zo(),i=Jo(),r=Yo(),a=Zo(),l=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(o)}/trigger`,u={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};v.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let f=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(u)});if(!f.ok){let E=null,p="";try{E=await f.json(),p=E?.error||E?.message||JSON.stringify(E)}catch{p=await f.text().catch(()=>"")}if(f.status===429){let k=E?.quotaInfo||{},M=new Error(`Sub-graph '${o}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=o,M.quotaInfo=k,M}if(f.status===400){let k=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=o,k.validationErrors=E?.validationErrors||null,k.missing=E?.missing||null,k}let $=new Error(`Sub-graph '${o}' trigger rejected (${f.status}): ${p}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=f.status,$.subgraph=o,$}let d=await f.json(),c=d?.data?.jobId||d?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(d).slice(0,200)}`);if(e.async)return v.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let m=Number.isFinite(e.timeoutMs)?e.timeoutMs:Go,g=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Uo,y=`${s}/executions/${encodeURIComponent(c)}`,b=Date.now()+m,S="accepted",h=0;for(;Date.now()<b;){await new Promise(k=>setTimeout(k,g)),h+=1;let E=await fetch(y,{headers:{Authorization:`Bearer ${r}`}});if(!E.ok){if(E.status>=500){v.warn(`[sub-graph] status poll for ${c} returned ${E.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${E.status}`)}let p=await E.json(),$=p?.data||p?.execution||p;if(S=$?.status||S,Ho.has(S)){if(S!=="completed"){let te=new Error(`Sub-graph '${o}' (${c}) ended in status '${S}'`);throw te.subgraphJobId=c,te.subgraphStatus=S,te}let k=$?.finalState||$?.state||{},M=Ht(k,e.output);return v.info(`[sub-graph] '${o}' (${c}) completed after ${h} polls`),M}}let w=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(m/1e3)}s (last status: ${S})`);throw w.subgraphJobId=c,w.subgraphStatus=S,w}import{existsSync as zt,readFileSync as Vo}from"node:fs";import{join as Ye,dirname as Jt}from"node:path";var he=class{static async loadContext(e,t,n={}){let s={},i=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Jt(Ye(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let f=l.replace(/\.[^.]+$/,"").toLowerCase();s[f]=u}}}let r=n.discovery||{};for(let[a,l]of Object.entries(r))try{let u=Ye(t,l);zt(u)&&(s[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(e,t,n){let s=[],i=t;for(;i.startsWith(n);){let r=Ye(i,e);if(zt(r))try{s.unshift(await this.loadFile(r))}catch(l){console.warn(`[workflow] could not load ${e} from ${r}: ${l.message}`)}let a=Jt(i);if(a===i)break;i=a}return s.length===0?null:s.every(r=>typeof r=="string")?s.join(`
34
+ ${i}`);let a=n(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let d=Ge(u,G);if(Ot(d)){let m=JSON.parse(Nt(d,"utf-8"));m.currentNode=this.name,Ue(d,JSON.stringify(m,null,2),"utf-8")}let c=Ge(u,"..",G);if(Ot(c))try{let m=JSON.parse(Nt(c,"utf-8"));m.currentNode=this.name,Ue(c,JSON.stringify(m,null,2),"utf-8")}catch{}}}catch(d){v.debug(`[workflow] could not update session info: ${d.message}`)}let f=null;for(let d=0;d<=this.retries;d++)try{v.debug(`[workflow] node '${this.name}' attempt ${d}`);let c=n().config||{},m=c.agents||{},g=this.config.agent??m[this.name]??null,y={state:n()};g&&(y.preferredAgent=g);let I={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:u,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},_=e?._coreInvokeAgent;_||(_=(await Promise.resolve().then(()=>(X(),pe))).invokeAgent);let h=await _(i,y,I),S,E;if(typeof h=="string"?(S=h,E=null):h.structured?(S=h.raw||JSON.stringify(h.structured,null,2),E=h.structured):(S=h.raw||JSON.stringify(h,null,2),E=h.extracted||null),u)try{let p=Ge(u,this.name,"raw_stream_output.txt");To(ko(p),{recursive:!0}),Ue(p,typeof S=="string"?S:JSON.stringify(S),"utf-8")}catch(p){v.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&E){v.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(E,null,2)}`);let p=E;if(typeof this.onComplete=="function")try{p=await this.onComplete(n(),E)}catch($){v.warn(`[workflow] onComplete hook failed: ${$.message}`)}return{success:!0,output:p,raw:S}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:S}),raw:S}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(S);return v.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),x.step("Output parsed"),{success:!0,output:p,raw:S}}return{success:!0,output:S,raw:S}}catch(c){f=c,d<this.retries&&v.info(`[workflow] node '${this.name}' failed, retrying (${d+1}/${this.retries})\u2026`)}return{success:!1,error:f.message,raw:null}}};W();W();import{mkdirSync as No,existsSync as Z,statSync as Wt,readdirSync as Ut,rmSync as Oo}from"node:fs";import{spawn as Dt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as Po}from"node:url";import{AsyncLocalStorage as Co}from"node:async_hooks";import{AsyncLocalStorage as Ao}from"node:async_hooks";var fe=new Ao;function Q(){let o=fe.getStore();return o||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function Pt(o,e){let t=fe.getStore()||Q(),n=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null,agent:o.agent!==void 0?o.agent:t.agent??null,signal:o.signal!==void 0?o.signal:t.signal??null});return fe.run(n,e)}function Ct(o,e,t){let n=fe.getStore()||Q(),s=Object.freeze({...n,agent:o??n.agent??null,signal:e??n.signal??null});return fe.run(s,t)}var He=new Map,ze=new Map,Rt=new Map;function jt(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");He.set(o,e),ze.set(o,"ready"),Rt.set(o,{...t,cachedAt:Date.now()})}function Mt(o,e){ze.set(o,"failed"),Rt.set(o,{error:e?.message||String(e),failedAt:Date.now()}),He.delete(o)}function Bt(o){return ze.get(o)==="ready"?He.get(o):null}var Ee=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Ro(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var O=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"}},Lt=new Co,Ft=Promise.resolve();async function jo(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([r,a])=>typeof r=="string"&&r&&typeof a=="string"):[];if(t.length===0)return e();let n=Lt.getStore()===!0,s=null;if(!n){let r=Ft;Ft=new Promise(a=>{s=a}),await r}let i=new Map;try{for(let[r,a]of t)i.set(r,Object.prototype.hasOwnProperty.call(process.env,r)?process.env[r]:void 0),process.env[r]=a;return v.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await Lt.run(!0,e)}finally{for(let[r,a]of i)a===void 0?delete process.env[r]:process.env[r]=a;s&&s()}}function Mo(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,n=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!n||!s)throw new O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:s}}async function Bo({apiBase:o,authToken:e,body:t}){let n;try{n=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(i){throw new O("network",`begin fetch failed: ${i.message}`)}let s=null;try{s=await n.json()}catch{}if(!n.ok){if(n.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(n.status===429){let i=s?.quotaInfo||{},r=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw r.code="SUBGRAPH_QUOTA_EXCEEDED",r.status=429,r.quotaInfo=i,r}if(n.status===400&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new O("begin-status",`begin returned ${n.status}`)}return s?.data||s}async function Y({apiBase:o,authToken:e,payload:t}){try{let n=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});n.ok||v.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){v.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function Do(o,e){let t=U(e,".ready"),n=U(e,"graph.mjs");if(Z(t)&&Z(n))return;No(e,{recursive:!0});let s=U(e,".lock"),i=!1;try{let{openSync:r,closeSync:a}=await import("node:fs"),l=r(s,"wx");a(l),i=!0}catch(r){if(r.code!=="EEXIST")throw r}if(!i){let r=Date.now()+3e4;for(;Date.now()<r;){if(Z(t)&&Z(n))return;await new Promise(a=>setTimeout(a,100))}throw new O("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let f=Dt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),d=Dt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(d.stdin);let c,m,g=()=>{if(c!==void 0&&m!==void 0){if(c!==0)return u(new Error(`curl exited ${c}`));if(m!==0)return u(new Error(`tar exited ${m}`));l()}};f.on("close",y=>{c=y,g()}),d.on("close",y=>{m=y,g()}),f.on("error",u),d.on("error",u)});let{writeFileSync:r,unlinkSync:a}=await import("node:fs");r(t,"");try{a(s)}catch{}}catch(r){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new O("bundle-extract-failed",r.message)}}async function Lo(o){let e=U(o,"graph.mjs");if(!Z(e))throw new O("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(Po(e).href)}catch(s){throw new O("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 O("entry-class-missing","no buildGraph() class export found");return n}async function Gt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=Q(),n;try{n=Mo()}catch(p){throw p}v.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let s=await Bo({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:r,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:f,bundleReady:d,nodeConfigs:c}=s,m=Ro();if(r&&r!==m)throw await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new O("runtime-mismatch",`${m} vs ${r}`);if(!d||!a)throw await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new O("no-bundle","workflow bundle not built yet");let g=Bt(o);if(!g){let p=U(Ee,`${f}@${u||"0"}`);try{await Do(a,p);try{Wo()}catch{}}catch($){throw $.fallback&&await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{g=await Lo(p),jt(o,g,{workflowUuid:f,version:u,runtimeTag:r,cacheDir:p})}catch($){throw Mt(o,$),await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new O("import-failed",$.message)}}let y=Date.now(),I=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,h={...e.input||{},..._?{nodeConfigs:c}:{}},S,E;try{S=await jo(I,async()=>{let $=await(typeof g=="function"&&g.prototype?.buildGraph?new g:g).buildGraph();return Pt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,h,{signal:e.signal}))}),E=S&&typeof S=="object"&&"state"in S?S.state:S}catch(p){throw await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-y}}),p}if(S&&typeof S=="object"&&S.stoppedExternally){await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",finalState:E,durationMs:Date.now()-y}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await Y({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:E,durationMs:Date.now()-y}}),{finalState:E,executionId:i}}function Fo(o){let e=0,t=[o];for(;t.length;){let n=t.pop(),s;try{s=Wt(n)}catch{continue}if(s.isDirectory()){let i;try{i=Ut(n)}catch{continue}for(let r of i)t.push(U(n,r))}else e+=s.size}return e}function Wo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Z(Ee))return{evicted:0,freedBytes:0};let e=Ut(Ee),t=[],n=0;for(let a of e){let l=U(Ee,a),u;try{u=Wt(l)}catch{continue}let f=u.isDirectory()?Fo(l):u.size;n+=f,t.push({name:a,full:l,size:f,mtimeMs:u.mtimeMs})}if(n<=o)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(o*.7),i=0,r=0;for(let a of t){if(n-i<=s)break;if(!Z(U(a.full,".lock")))try{Oo(a.full,{recursive:!0,force:!0}),i+=a.size,r+=1}catch(l){v.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return r>0&&v.info(`[sub-graph cache] evicted ${r} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:r,freedBytes:i,totalBytes:n-i}}catch(e){return v.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Uo=2e3,Go=600*1e3,Ho=new Set(["completed","failed","canceled","timeout"]);function zo(){let o=process.env.PROGRESS_API_URL;if(!o)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return o.replace(/\/executions\/?$/,"")}function Jo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Yo(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Zo(){return process.env.EXECUTION_ID||null}function Ht(o,e){return e==null?o:typeof e=="function"?e(o):typeof e=="string"?e.split(".").reduce((t,n)=>t==null?t:t[n],o):o}async function Je(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=Q();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=n)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{v.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:E}=await Gt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=Ht(E,e.output);return v.info(`[sub-graph] '${o}' completed in-process`),p}catch(E){if(E instanceof O||E?.fallback)v.info(`[sub-graph] in-process fallback for '${o}': ${E.reason||"unknown"} \u2014 using HTTP`);else throw E}let s=zo(),i=Jo(),r=Yo(),a=Zo(),l=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(o)}/trigger`,u={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};v.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let f=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(u)});if(!f.ok){let E=null,p="";try{E=await f.json(),p=E?.error||E?.message||JSON.stringify(E)}catch{p=await f.text().catch(()=>"")}if(f.status===429){let k=E?.quotaInfo||{},B=new Error(`Sub-graph '${o}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw B.code="SUBGRAPH_QUOTA_EXCEEDED",B.status=429,B.subgraph=o,B.quotaInfo=k,B}if(f.status===400){let k=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=o,k.validationErrors=E?.validationErrors||null,k.missing=E?.missing||null,k}let $=new Error(`Sub-graph '${o}' trigger rejected (${f.status}): ${p}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=f.status,$.subgraph=o,$}let d=await f.json(),c=d?.data?.jobId||d?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(d).slice(0,200)}`);if(e.async)return v.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let m=Number.isFinite(e.timeoutMs)?e.timeoutMs:Go,g=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Uo,y=`${s}/executions/${encodeURIComponent(c)}`,I=Date.now()+m,_="accepted",h=0;for(;Date.now()<I;){await new Promise(k=>setTimeout(k,g)),h+=1;let E=await fetch(y,{headers:{Authorization:`Bearer ${r}`}});if(!E.ok){if(E.status>=500){v.warn(`[sub-graph] status poll for ${c} returned ${E.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${E.status}`)}let p=await E.json(),$=p?.data||p?.execution||p;if(_=$?.status||_,Ho.has(_)){if(_!=="completed"){let te=new Error(`Sub-graph '${o}' (${c}) ended in status '${_}'`);throw te.subgraphJobId=c,te.subgraphStatus=_,te}let k=$?.finalState||$?.state||{},B=Ht(k,e.output);return v.info(`[sub-graph] '${o}' (${c}) completed after ${h} polls`),B}}let S=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(m/1e3)}s (last status: ${_})`);throw S.subgraphJobId=c,S.subgraphStatus=_,S}import{existsSync as zt,readFileSync as Vo}from"node:fs";import{join as Ye,dirname as Jt}from"node:path";var he=class{static async loadContext(e,t,n={}){let s={},i=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Jt(Ye(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let f=l.replace(/\.[^.]+$/,"").toLowerCase();s[f]=u}}}let r=n.discovery||{};for(let[a,l]of Object.entries(r))try{let u=Ye(t,l);zt(u)&&(s[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(e,t,n){let s=[],i=t;for(;i.startsWith(n);){let r=Ye(i,e);if(zt(r))try{s.unshift(await this.loadFile(r))}catch(l){console.warn(`[workflow] could not load ${e} from ${r}: ${l.message}`)}let a=Jt(i);if(a===i)break;i=a}return s.length===0?null:s.every(r=>typeof r=="string")?s.join(`
35
35
 
36
36
  ---
37
37
 
38
38
  `):s.every(r=>typeof r=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=Vo(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 Vt,existsSync as Ze,writeFileSync as Yt,unlinkSync as Ko}from"node:fs";import{join as V,resolve as Kt}from"node:path";import{config as qo}from"dotenv";import{zodToJsonSchema as Zt}from"zod-to-json-schema";import{z as be}from"zod";import Xo from"handlebars";function Qo({traceFrom:o,sessionId:e,sessionPath:t,idSource:n,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let r=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${o} pid=${process.pid} ppid=${r} sessionId=${e} source=${n} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let f=(new Error("session trace").stack||"").split(`
39
39
  `).slice(2,14).join(`
40
40
  `);console.log(`[zibby:session] stack (${o}):
41
- ${f}`)}}function qt(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Xt(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Kt(String(e).trim())}catch{return String(e).trim()}}function Qt(){qt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function eo({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function to(o={}){let e=je.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,s=o.paths?.sessionPrefix;return s?`${s}_${n}`:n}function oo({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,r="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=Kt(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,r="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,r="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,r="config.sessionId"):(a=to(e),r="generated")}i=i??Date.now();let f=e.paths?.output||le;s=V(o,f,Ce,a)}let l=!Ze(s);return l&&Vt(s,{recursive:!0}),(l||r!=="initialState.sessionPath")&&Qo({traceFrom:n,sessionId:a,sessionPath:s,idSource:r,mkdirFresh:l}),eo({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var ee=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,n={}){if(!(t instanceof F)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let r=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:r.workflow,retries:r.retries,onComplete:r.onComplete,execute:async u=>{let f=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof r.input=="function"?d=r.input(f):r.input&&typeof r.input=="object"?d=r.input:d={},Je(r.workflow,{input:d,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(f):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:f?._signal,parentAgent:u?.agent})}},l=new F(a);return l.name=e,this.nodes.set(e,l),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let s=!(t instanceof F)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof F?t:new F(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){let n=this.edges.get(e);return n===void 0?this.edges.set(e,t):typeof n=="string"?n!==t&&this.edges.set(e,[n,t]):Array.isArray(n)?n.includes(t)||n.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:n}={}){let s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:n}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,n=i=>{t.set(i,1);for(let r of this._simpleTargets(i)){if(!r||r==="END")continue;let a=t.get(r)||0;a===1?e.add(`${i}->${r}`):a===0&&n(r)}t.set(i,2)};this.entryPoint&&n(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let r of this._simpleTargets(i))!r||r==="END"||e.has(`${i}->${r}`)||s.set(r,(s.get(r)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,s,i){let r=n;for(let a=e.length-1;a>=0;a--){let l=e[a],u=r;r=()=>l(t,u,s,i)}return r()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let m=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:m,data:{nodeType:m,label:d}});let g={};c._isCustomCode&&typeof c.execute=="function"&&(g.customCode=c.execute.toString());let y=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;y&&(g.description=y);let b=this.nodePrompts.get(d);if(b)g.prompt=b;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(g.prompt=p,g.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(g.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(g.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof be?.toJSONSchema=="function")try{p=be.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Zt(c.outputSchema,{target:"openApi3"})}catch{}g.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else g.outputSchema={schema:c.outputSchema};let S=(this.resolvedToolsMap||{})[d];S?.toolIds&&(g.tools=S.toolIds);let h=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;h&&h.length>0&&(g.skills=[...h]);let w=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;w&&w.length>0&&(g.plugins=w.map(p=>p&&typeof p=="object"?{...p}:p));let E=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;E&&E.length>0&&(g.stores=E.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(g).length>0&&(t[d]=g)}let n=[];for(let[d,c]of this.edges)if(typeof c=="string")n.push({source:d,target:c});else if(Array.isArray(c))for(let m of c)n.push({source:d,target:m});else if(c.conditional){let m=this.conditionalCodeMap.get(d)||c.routes.toString(),g=this._inferConditionalTargets(c.routes,c.labels),y=c.labels||{},b=this.nodes.get(d),S=b?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!b,h=d;if(!S){let w=`${d}__branch`;e.push({id:w,type:"decision",data:{nodeType:"decision",label:w}}),n.push({source:d,target:w}),h=w}for(let w of g){let E={source:h,target:w,data:{conditionalCode:m}};y[w]&&(E.label=y[w]),n.push(E)}}let s=d=>{if(!d)return null;if(typeof be?.toJSONSchema=="function")try{return be.toJSONSchema(d)}catch{}try{return Zt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of n)if(d.target==="END"){i+=1;let c=`END__${i}`;d.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:d,target:c})}let r=this._topoOrderNodes(e,n),a=this._runtimeSchema(),l=s(a||this.stateSchema),u=s(this.inputSchema),f=s(this.contextSchema);return{nodes:r,edges:n,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:f}}_topoOrderNodes(e,t){let n=new Map(e.map((d,c)=>[d.id,c])),s=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),r=new Map(e.map(d=>[d.id,[]]));for(let d of t)r.has(d.source)&&i.has(d.target)&&(r.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(n.keys()),u=[...l].filter(d=>i.get(d)===0),f=[];for(;f.length<e.length;){let d;if(u.length>0){if(u.sort((c,m)=>n.get(c)-n.get(m)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,m)=>n.get(c)-n.get(m))[0];a.add(d),l.delete(d),f.push(s.get(d));for(let c of r.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return f}_inferConditionalTargets(e,t){let n=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,r;for(;(r=i.exec(n))!==null;){let u=r[2]!==void 0?r[2]:r[3];u!==void 0&&u!==""&&s.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of s)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,f;for(;(f=u.exec(n))!==null;)l.add(f[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");n=e.definitions[s]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],s=e.properties||{},i=e.required||[];for(let[r,a]of Object.entries(s)){let l=t?`${t}.${r}`:r;n.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!i.includes(r)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${l}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${s}: ${i}`);else if(Array.isArray(i)){let r=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);n.push(l?`${s}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${s}: ${r} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t)&&(t=e.normalizeInput(t)??t);let s=new AbortController;n.signal&&(n.signal.aborted?s.abort():n.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();qo({path:V(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let I=V(r,".zibby.config.js");Ze(I)&&(a=(await import(I)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let I=a?.agent;I?.provider?l=I.provider:I?.gemini?l="gemini":I?.claude?l="claude":I?.cursor?l="cursor":I?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},f=this._runtimeSchema();if(f){let I=f.safeParse(t);if(!I.success){let _=I.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),_.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${_.join(", ")}`)}x.step("State validated against schema")}let d=Xt(),c=t.sessionPath||d;c||Qt();let{sessionPath:m,sessionTimestamp:g,sessionId:y}=oo({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});x.step(`Session ${y}`);let b=await he.loadContext(t.specPath||"",r,u);Object.keys(b).length>0&&x.step(`Context loaded: ${Object.keys(b).join(", ")}`);let S=t.outputPath;!S&&t.specPath&&(e?.calculateOutputPath?S=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new se({...t,config:a,agentType:l,outputPath:S,sessionPath:m,sessionTimestamp:g,context:b,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),w=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:E}=await Promise.resolve().then(()=>(ue(),$t)),p=a.skills&&typeof a.skills=="object"?a.skills:{},$=Object.values(p).filter(I=>I&&typeof I=="object"&&typeof I.id=="string"),k=I=>{for(let _ of $)if(_.id===I)return _;return E(I)},M=new Set;for(let[,I]of this.nodes)for(let _ of I.config?.skills||[])M.add(_);for(let I of M){let _=k(I);if(typeof _?.middleware=="function")try{let R=await _.middleware();typeof R=="function"&&w.set(I,R)}catch{}}let{backEdges:te,joinDegree:io}=this._analyzeFlow(),Te=new Map,oe=[],ke=(I,_,R)=>{if(!I||I==="END")return;let D=io.get(I)||0;if(R&&D>1&&!te.has(`${_}->${I}`)){let ne=(Te.get(I)||0)+1;if(ne<D){Te.set(I,ne);return}Te.set(I,0)}oe.includes(I)||oe.push(I)};this.entryPoint&&oe.push(this.entryPoint);let me=[],tt=a?.recursionLimit??100,ao=0;try{for(;oe.length>0;){let _=oe.pop();if(!_||_==="END")continue;if(++ao>tt)throw new Error(`Workflow exceeded recursion limit (${tt}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let R=V(m,Re);if(Ze(R)){try{Ko(R)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
42
- \u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:me,stoppedExternally:!0};let D=this.nodes.get(_);if(!D)throw new Error(`Node '${_}' not found in graph`);let ne=JSON.stringify({sessionPath:m,sessionTimestamp:g,currentNode:_,createdAt:new Date().toISOString(),config:h.get("config")}),co=V(m,G);Yt(co,ne,"utf-8");let ot=h.get("config")?.paths?.output||le,lo=V(r,ot,G);Vt(V(r,ot),{recursive:!0});try{Yt(lo,ne,"utf-8")}catch{}let nt=t.onPipelineProgress;if(typeof nt=="function")try{nt({cwd:r,sessionPath:m,sessionId:y,outputBase:h.get("config")?.paths?.output||le,currentNode:_})}catch{}let uo=(this.resolvedToolsMap||{})[_]||null;h.set("_currentNodeTools",uo);let po=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",po[_]||{}),x.nodeStart(_);let rt=Date.now(),ye=this.nodePrompts.get(_);if(!this._invokeAgent){let A=await Promise.resolve().then(()=>(X(),pe));this._invokeAgent=A.invokeAgent}let fo=this._invokeAgent,Ae={},ho=D.config?.skills||[];for(let A of ho){let P=k(A);if(typeof P?.invokeAgentOptions=="function")try{let T=P.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:_});T&&typeof T=="object"&&(Ae={...Ae,...T})}catch(T){console.warn(`[graph] skill '${A}' invokeAgentOptions threw: ${T.message}`)}}let st=async(A,P,T={})=>{let j=fo(A,P,{...Ae,...T,signal:s.signal});return j.catch(()=>{}),s.signal.aborted?j:Promise.race([j,new Promise((K,L)=>{let C=()=>{setTimeout(()=>{let re=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);re.name="AbortError",L(re)},i)};s.signal.addEventListener("abort",C,{once:!0})})])},go=async(A={},P={})=>{let T=P.prompt||"";if(ye){let j=this._compiledPrompts.get(_);j||(j=Xo.compile(ye,{noEscape:!0}),this._compiledPrompts.set(_,j));try{T=j(A)}catch(K){throw console.error(`\u274C Template rendering failed for node '${_}':`,K.message),new Error(`Template rendering failed: ${K.message}`,{cause:K})}}else if(!T)throw new Error(`No prompt template configured for node '${_}' and no prompt provided in options`);return st(T,{state:h.getAll(),images:P.images||[]},{model:P.model||h.get("model"),workspace:h.get("workspace"),schema:P.schema,...P,signal:s.signal})},it=h.getAll(),mo=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let A of mo)Object.prototype.hasOwnProperty.call(it,A)&&console.warn(`[workflow] node "${_}": state key "${A}" is shadowed by the engine context prop; read it via context.state.get('${A}')`);let at={...it,state:h,invokeAgent:go,_coreInvokeAgent:st,agent:e,nodeId:_,promptTemplate:ye,getPromptTemplate:()=>ye};try{let A=(D.config?.skills||[]).map(C=>w.get(C)).filter(Boolean),P=[...this.middleware,...A],T;T=await Ct(e,s.signal,async()=>P.length>0?this._composeMiddleware(P,_,async()=>D.execute(at,h),h.getAll(),h):D.execute(at,h));let j=Date.now()-rt;if(me.push({node:_,success:T.success,duration:j,timestamp:new Date().toISOString()}),!T.success){if(s.signal.aborted)return x.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:me,stoppedExternally:!0};h.append("errors",{node:_,error:T.error});let C=D.config?.retries||0,re=`${_}_retries`,we=h.getAll()[re]||0;if(we<C){x.stepInfo(`Retrying (attempt ${we+1}/${C})`),h.update({[re]:we+1,[`${_}_raw`]:T.raw});continue}throw x.nodeFailed(_,T.error,{duration:j}),new Error(`Node '${_}' failed after ${we} attempts: ${T.error}`)}h.update({[_]:T.output});let K=this._summarizeNodeOutput(_,T.output);x.nodeComplete(_,{duration:j,details:K});let L=this.edges.get(_);if(L)if(L.conditional){let C=L.routes(h.getAll());x.route(_,C),ke(C,_,!1)}else if(Array.isArray(L))for(let C=L.length-1;C>=0;C--)ke(L[C],_,!0);else ke(L,_,!0)}catch(A){throw x.isInsideNode&&x.nodeFailed(_,A.message,{duration:Date.now()-rt}),h.set("failed",!0),h.set("failedAt",_),A}}x.graphComplete();let I={success:!0,state:h.getAll(),executionLog:me};return e&&typeof e.onComplete=="function"&&await e.onComplete(I),I}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(I){console.warn(`[workflow] agent.cleanup() failed: ${I.message}`)}}}};var Ve=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Ve]||(globalThis[Ve]=new Map);var ge=globalThis[Ve];function no(o,e){ge.set(o,e)}function Ke(o){return ge.get(o)}function Ie(o){return ge.has(o)}function en(){return Array.from(ge.keys())}function qe(o){let e=ge.get(o);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}no("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let n=t?._coreInvokeAgent;n||(n=(await Promise.resolve().then(()=>(X(),pe))).invokeAgent);let s=e.extraPromptInstructions||"Execute the task based on the current state.",i=tn(s,t),r=await n(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:r,nodeId:o},raw:typeof r=="string"?r:r.raw}}})});function tn(o,e){let t=/@([\w.]+)/g,n=new Set,s;for(;(s=t.exec(o))!==null;)n.add(s[1]);if(n.size===0)return o;let i=[],r=new Set;for(let a of n){let l=a.split(".")[0];if(r.has(l))continue;let u=a.split(".").reduce((c,m)=>c?.[m],e);if(u===void 0)continue;let f=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),d=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${d}
41
+ ${f}`)}}function qt(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Xt(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Kt(String(e).trim())}catch{return String(e).trim()}}function Qt(){qt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function eo({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function to(o={}){let e=je.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,s=o.paths?.sessionPrefix;return s?`${s}_${n}`:n}function oo({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,r="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=Kt(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,r="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,r="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,r="config.sessionId"):(a=to(e),r="generated")}i=i??Date.now();let f=e.paths?.output||le;s=V(o,f,Ce,a)}let l=!Ze(s);return l&&Vt(s,{recursive:!0}),(l||r!=="initialState.sessionPath")&&Qo({traceFrom:n,sessionId:a,sessionPath:s,idSource:r,mkdirFresh:l}),eo({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var ee=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,n={}){if(!(t instanceof F)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let r=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:r.workflow,retries:r.retries,onComplete:r.onComplete,execute:async u=>{let f=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof r.input=="function"?d=r.input(f):r.input&&typeof r.input=="object"?d=r.input:d={},Je(r.workflow,{input:d,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(f):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:f?._signal,parentAgent:u?.agent})}},l=new F(a);return l.name=e,this.nodes.set(e,l),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let s=!(t instanceof F)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof F?t:new F(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){let n=this.edges.get(e);return n===void 0?this.edges.set(e,t):typeof n=="string"?n!==t&&this.edges.set(e,[n,t]):Array.isArray(n)?n.includes(t)||n.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:n}={}){let s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:n}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,n=i=>{t.set(i,1);for(let r of this._simpleTargets(i)){if(!r||r==="END")continue;let a=t.get(r)||0;a===1?e.add(`${i}->${r}`):a===0&&n(r)}t.set(i,2)};this.entryPoint&&n(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let r of this._simpleTargets(i))!r||r==="END"||e.has(`${i}->${r}`)||s.set(r,(s.get(r)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,s,i){let r=n;for(let a=e.length-1;a>=0;a--){let l=e[a],u=r;r=()=>l(t,u,s,i)}return r()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let m=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:m,data:{nodeType:m,label:d}});let g={};c._isCustomCode&&typeof c.execute=="function"&&(g.customCode=c.execute.toString());let y=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;y&&(g.description=y);let I=this.nodePrompts.get(d);if(I)g.prompt=I;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(g.prompt=p,g.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(g.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(g.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof be?.toJSONSchema=="function")try{p=be.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Zt(c.outputSchema,{target:"openApi3"})}catch{}g.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else g.outputSchema={schema:c.outputSchema};let _=(this.resolvedToolsMap||{})[d];_?.toolIds&&(g.tools=_.toolIds);let h=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;h&&h.length>0&&(g.skills=[...h]);let S=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;S&&S.length>0&&(g.plugins=S.map(p=>p&&typeof p=="object"?{...p}:p));let E=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;E&&E.length>0&&(g.stores=E.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(g).length>0&&(t[d]=g)}let n=[];for(let[d,c]of this.edges)if(typeof c=="string")n.push({source:d,target:c});else if(Array.isArray(c))for(let m of c)n.push({source:d,target:m});else if(c.conditional){let m=this.conditionalCodeMap.get(d)||c.routes.toString(),g=this._inferConditionalTargets(c.routes,c.labels),y=c.labels||{},I=this.nodes.get(d),_=I?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!I,h=d;if(!_){let S=`${d}__branch`;e.push({id:S,type:"decision",data:{nodeType:"decision",label:S}}),n.push({source:d,target:S}),h=S}for(let S of g){let E={source:h,target:S,data:{conditionalCode:m}};y[S]&&(E.label=y[S]),n.push(E)}}let s=d=>{if(!d)return null;if(typeof be?.toJSONSchema=="function")try{return be.toJSONSchema(d)}catch{}try{return Zt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of n)if(d.target==="END"){i+=1;let c=`END__${i}`;d.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:d,target:c})}let r=this._topoOrderNodes(e,n),a=this._runtimeSchema(),l=s(a||this.stateSchema),u=s(this.inputSchema),f=s(this.contextSchema);return{nodes:r,edges:n,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:f}}_topoOrderNodes(e,t){let n=new Map(e.map((d,c)=>[d.id,c])),s=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),r=new Map(e.map(d=>[d.id,[]]));for(let d of t)r.has(d.source)&&i.has(d.target)&&(r.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(n.keys()),u=[...l].filter(d=>i.get(d)===0),f=[];for(;f.length<e.length;){let d;if(u.length>0){if(u.sort((c,m)=>n.get(c)-n.get(m)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,m)=>n.get(c)-n.get(m))[0];a.add(d),l.delete(d),f.push(s.get(d));for(let c of r.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return f}_inferConditionalTargets(e,t){let n=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,r;for(;(r=i.exec(n))!==null;){let u=r[2]!==void 0?r[2]:r[3];u!==void 0&&u!==""&&s.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of s)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,f;for(;(f=u.exec(n))!==null;)l.add(f[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");n=e.definitions[s]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],s=e.properties||{},i=e.required||[];for(let[r,a]of Object.entries(s)){let l=t?`${t}.${r}`:r;n.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!i.includes(r)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${l}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${s}: ${i}`);else if(Array.isArray(i)){let r=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);n.push(l?`${s}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${s}: ${r} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(b){let w=new Error(`agent.normalizeInput() rejected the trigger input: ${b?.message||b}`);throw w.cause=b,w.code=b?.code||"NORMALIZE_INPUT_FAILED",w}let s=new AbortController;n.signal&&(n.signal.aborted?s.abort():n.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();qo({path:V(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let b=V(r,".zibby.config.js");Ze(b)&&(a=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let b=a?.agent;b?.provider?l=b.provider:b?.gemini?l="gemini":b?.claude?l="claude":b?.cursor?l="cursor":b?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},f=this._runtimeSchema();if(f){let b=f.safeParse(t);if(!b.success){let w=b.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),w.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${w.join(", ")}`)}x.step("State validated against schema")}let d=Xt(),c=t.sessionPath||d;c||Qt();let{sessionPath:m,sessionTimestamp:g,sessionId:y}=oo({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});x.step(`Session ${y}`);let I=await he.loadContext(t.specPath||"",r,u);Object.keys(I).length>0&&x.step(`Context loaded: ${Object.keys(I).join(", ")}`);let _=t.outputPath;!_&&t.specPath&&(e?.calculateOutputPath?_=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new se({...t,config:a,agentType:l,outputPath:_,sessionPath:m,sessionTimestamp:g,context:I,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),S=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:E}=await Promise.resolve().then(()=>(ue(),$t)),p=a.skills&&typeof a.skills=="object"?a.skills:{},$=Object.values(p).filter(b=>b&&typeof b=="object"&&typeof b.id=="string"),k=b=>{for(let w of $)if(w.id===b)return w;return E(b)},B=new Set;for(let[,b]of this.nodes)for(let w of b.config?.skills||[])B.add(w);for(let b of B){let w=k(b);if(typeof w?.middleware=="function")try{let R=await w.middleware();typeof R=="function"&&S.set(b,R)}catch{}}let{backEdges:te,joinDegree:io}=this._analyzeFlow(),Te=new Map,oe=[],ke=(b,w,R)=>{if(!b||b==="END")return;let D=io.get(b)||0;if(R&&D>1&&!te.has(`${w}->${b}`)){let ne=(Te.get(b)||0)+1;if(ne<D){Te.set(b,ne);return}Te.set(b,0)}oe.includes(b)||oe.push(b)};this.entryPoint&&oe.push(this.entryPoint);let me=[],tt=a?.recursionLimit??100,ao=0;try{for(;oe.length>0;){let w=oe.pop();if(!w||w==="END")continue;if(++ao>tt)throw new Error(`Workflow exceeded recursion limit (${tt}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let R=V(m,Re);if(Ze(R)){try{Ko(R)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
42
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:me,stoppedExternally:!0};let D=this.nodes.get(w);if(!D)throw new Error(`Node '${w}' not found in graph`);let ne=JSON.stringify({sessionPath:m,sessionTimestamp:g,currentNode:w,createdAt:new Date().toISOString(),config:h.get("config")}),co=V(m,G);Yt(co,ne,"utf-8");let ot=h.get("config")?.paths?.output||le,lo=V(r,ot,G);Vt(V(r,ot),{recursive:!0});try{Yt(lo,ne,"utf-8")}catch{}let nt=t.onPipelineProgress;if(typeof nt=="function")try{nt({cwd:r,sessionPath:m,sessionId:y,outputBase:h.get("config")?.paths?.output||le,currentNode:w})}catch{}let uo=(this.resolvedToolsMap||{})[w]||null;h.set("_currentNodeTools",uo);let po=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",po[w]||{}),x.nodeStart(w);let rt=Date.now(),ye=this.nodePrompts.get(w);if(!this._invokeAgent){let A=await Promise.resolve().then(()=>(X(),pe));this._invokeAgent=A.invokeAgent}let fo=this._invokeAgent,Ae={},ho=D.config?.skills||[];for(let A of ho){let P=k(A);if(typeof P?.invokeAgentOptions=="function")try{let T=P.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:w});T&&typeof T=="object"&&(Ae={...Ae,...T})}catch(T){console.warn(`[graph] skill '${A}' invokeAgentOptions threw: ${T.message}`)}}let st=async(A,P,T={})=>{let j=fo(A,P,{...Ae,...T,signal:s.signal});return j.catch(()=>{}),s.signal.aborted?j:Promise.race([j,new Promise((K,L)=>{let C=()=>{setTimeout(()=>{let re=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);re.name="AbortError",L(re)},i)};s.signal.addEventListener("abort",C,{once:!0})})])},go=async(A={},P={})=>{let T=P.prompt||"";if(ye){let j=this._compiledPrompts.get(w);j||(j=Xo.compile(ye,{noEscape:!0}),this._compiledPrompts.set(w,j));try{T=j(A)}catch(K){throw console.error(`\u274C Template rendering failed for node '${w}':`,K.message),new Error(`Template rendering failed: ${K.message}`,{cause:K})}}else if(!T)throw new Error(`No prompt template configured for node '${w}' and no prompt provided in options`);return st(T,{state:h.getAll(),images:P.images||[]},{model:P.model||h.get("model"),workspace:h.get("workspace"),schema:P.schema,...P,signal:s.signal})},it=h.getAll(),mo=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let A of mo)Object.prototype.hasOwnProperty.call(it,A)&&console.warn(`[workflow] node "${w}": state key "${A}" is shadowed by the engine context prop; read it via context.state.get('${A}')`);let at={...it,state:h,invokeAgent:go,_coreInvokeAgent:st,agent:e,nodeId:w,promptTemplate:ye,getPromptTemplate:()=>ye};try{let A=(D.config?.skills||[]).map(C=>S.get(C)).filter(Boolean),P=[...this.middleware,...A],T;T=await Ct(e,s.signal,async()=>P.length>0?this._composeMiddleware(P,w,async()=>D.execute(at,h),h.getAll(),h):D.execute(at,h));let j=Date.now()-rt;if(me.push({node:w,success:T.success,duration:j,timestamp:new Date().toISOString()}),!T.success){if(s.signal.aborted)return x.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:me,stoppedExternally:!0};h.append("errors",{node:w,error:T.error});let C=D.config?.retries||0,re=`${w}_retries`,we=h.getAll()[re]||0;if(we<C){x.stepInfo(`Retrying (attempt ${we+1}/${C})`),h.update({[re]:we+1,[`${w}_raw`]:T.raw});continue}throw x.nodeFailed(w,T.error,{duration:j}),new Error(`Node '${w}' failed after ${we} attempts: ${T.error}`)}h.update({[w]:T.output});let K=this._summarizeNodeOutput(w,T.output);x.nodeComplete(w,{duration:j,details:K});let L=this.edges.get(w);if(L)if(L.conditional){let C=L.routes(h.getAll());x.route(w,C),ke(C,w,!1)}else if(Array.isArray(L))for(let C=L.length-1;C>=0;C--)ke(L[C],w,!0);else ke(L,w,!0)}catch(A){throw x.isInsideNode&&x.nodeFailed(w,A.message,{duration:Date.now()-rt}),h.set("failed",!0),h.set("failedAt",w),A}}x.graphComplete();let b={success:!0,state:h.getAll(),executionLog:me};return e&&typeof e.onComplete=="function"&&await e.onComplete(b),b}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(b){console.warn(`[workflow] agent.cleanup() failed: ${b.message}`)}}}};var Ve=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Ve]||(globalThis[Ve]=new Map);var ge=globalThis[Ve];function no(o,e){ge.set(o,e)}function Ke(o){return ge.get(o)}function Ie(o){return ge.has(o)}function en(){return Array.from(ge.keys())}function qe(o){let e=ge.get(o);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}no("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let n=t?._coreInvokeAgent;n||(n=(await Promise.resolve().then(()=>(X(),pe))).invokeAgent);let s=e.extraPromptInstructions||"Execute the task based on the current state.",i=tn(s,t),r=await n(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:r,nodeId:o},raw:typeof r=="string"?r:r.raw}}})});function tn(o,e){let t=/@([\w.]+)/g,n=new Set,s;for(;(s=t.exec(o))!==null;)n.add(s[1]);if(n.size===0)return o;let i=[],r=new Set;for(let a of n){let l=a.split(".")[0];if(r.has(l))continue;let u=a.split(".").reduce((c,m)=>c?.[m],e);if(u===void 0)continue;let f=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),d=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${d}
43
43
  ${f}`),a.includes(".")||r.add(l)}return i.length===0?o:`${o}
44
44
 
45
45
  ---
@@ -47,7 +47,7 @@ ${f}`),a.includes(".")||r.add(l)}return i.length===0?o:`${o}
47
47
 
48
48
  ${i.join(`
49
49
 
50
- `)}`}ue();W();var ve={};function Qe(o,e){if(Array.isArray(e))return Xe(e);let t=ve[o];return!t||t.length===0?null:Xe(t)}function Xe(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},n=[];for(let s of o){let i=q(s);if(!i){v.warn(`[workflow] unknown skill "${s}" \u2014 skipping`);continue}n.push(s);for(let r of i.tools||[])e.push({name:r.name,description:r.description,input_schema:r.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let r=i.resolve();r&&(t[i.serverName]={...r,toolPrefix:s})}else{let r={};for(let a of i.envKeys||[]){let l=process.env[a];l&&(r[a]=l)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:r,toolPrefix:s}}}return n.length===0?null:{toolIds:n,claudeTools:e,mcpServers:t}}W();function on(o,e={}){let{nodes:t,edges:n,nodeConfigs:s={}}=o;if(!Array.isArray(t)||t.length===0)throw new B("Graph must have at least one node");if(!Array.isArray(n))throw new B("Graph edges must be an array");let i=new ee(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let r=new Set,a=new Map,l={};for(let c of t){let m=$e(c);a.set(c.id,{...c,resolvedType:m}),m==="decision"&&r.add(c.id)}for(let[c,m]of a){if(r.has(c))continue;let g=m.resolvedType,y=s[c]||{},b=Qe(g,y.tools);b&&(l[c]=b);let S={};y.prompt&&(S.prompt=y.prompt);let h=Ie(g);if(v.debug(`[workflow] compiler: node "${c}" type="${g}" registered=${h}`),y.customCode&&!h)i.addNode(c,ro(c,y.customCode,y),S),i.setNodeType(c,g);else if(h){let w=Ke(g);w.factory?i.addNode(c,w.create(c,{...y,resolvedTools:b}),S):i.addNode(c,w,S),i.setNodeType(c,g)}else if(y.executeCode)i.addNode(c,ro(c,y.executeCode,y),S),i.setNodeType(c,g);else throw new B(`Unknown node type "${g}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=l;let u=new Set;for(let c of n)r.has(c.target)||u.add(c.target);let f=t.find(c=>!r.has(c.id)&&!u.has(c.id));if(!f)throw new B("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(f.id);let d=sn(n,"source");for(let c of n)if(!r.has(c.source))if(r.has(c.target)){let m=c.target,g=d.get(m)||[];if(g.length===0)throw new B(`Decision node "${m}" has no outgoing edges`);let y=an(m,g,r);i.addConditionalEdges(c.source,y)}else i.addEdge(c.source,c.target);return i}function nn(o){let e=[];if(!o||typeof o!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(o.nodes)||o.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(o.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=o.nodeConfigs||{};for(let a of o.nodes){let l=$e(a);if(l==="decision"||Ie(l))continue;let u=t[a.id]||{};u.customCode||u.executeCode||e.push(`Unknown node type "${l}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let n=new Set(o.nodes.map(a=>a.id));for(let a of o.edges)n.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),n.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let s=new Set(o.nodes.filter(a=>$e(a)==="decision").map(a=>a.id)),i=new Set;for(let a of o.edges)s.has(a.target)||i.add(a.target);let r=o.nodes.filter(a=>!s.has(a.id)&&!i.has(a.id));r.length===0?e.push("No entry point found (every node has incoming edges)"):r.length>1&&e.push(`Multiple entry points found: ${r.map(a=>a.id).join(", ")}`);for(let a of s){let l=o.edges.filter(f=>f.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(f=>f.data?.conditionalCode||f.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function rn(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>$e(e)!=="decision").map(e=>e.id)}function $e(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function sn(o,e){let t=new Map;for(let n of o){let s=n[e];t.has(s)||t.set(s,[]),t.get(s).push(n)}return t}function an(o,e,t){let n=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!n)throw new B(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let s=n.data?.conditionalCode||n.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),r;try{let l=new Function(`return (${s})`)();r=u=>{let f=l(u);return i.has(f)||v.warn(`[workflow] conditional route from "${o}" returned "${f}" which is not in valid targets: ${[...i].join(", ")}`),f}}catch(a){throw new B(`Failed to compile conditionalCode for "${o}": ${a.message}`)}return r}function ro(o,e,t={}){let n;try{n=new Function("invokeAgent","require","console",`return (${e})`)}catch(r){throw new B(`Failed to compile customCode for node "${o}": ${r.message}`)}let s=n(async(...r)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(X(),pe));return a(...r)},typeof xe<"u"?xe:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:i,execute:async r=>{try{let a=await s(r);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var B=class extends Error{constructor(e){super(e),this.name="CompilationError"}};ue();var et=/^[a-z][a-z0-9_]{0,40}$/;function cn(o){if(o==null)return[];if(!Array.isArray(o))return["stores must be an array of { name, description } objects"];let e=[],t=new Map;return o.forEach((n,s)=>{if(n==null||typeof n!="object"||Array.isArray(n)){e.push(`stores[${s}] must be an object { name, description }`);return}let{name:i}=n;if(typeof i!="string"||i.length===0){e.push(`stores[${s}] is missing a string "name"`);return}et.test(i)||e.push(`stores[${s}] name "${i}" is invalid \u2014 must match ${et} (lowercase letter first, then up to 40 of [a-z0-9_])`),t.has(i)?e.push(`stores[${s}] duplicate store name "${i}" (also at index ${t.get(i)}) \u2014 store names must be unique within a workflow`):t.set(i,s)}),e}Me();X();function ln(o,e={}){let{nodes:t,edges:n,nodeConfigs:s={}}=o,i=new Set,r=[],a=new Map;for(let b of t){let S=b.data?.nodeType||b.type;a.set(b.id,S),S==="decision"?i.add(b.id):r.push({id:b.id,nodeType:S,label:b.data?.label||b.id})}let l=r.some(b=>{let S=s[b.id]||{};return!S.customCode&&!S.executeCode}),{toolsPerNode:u,toolIdsByVar:f}=yn(r,s),{simpleEdges:d,conditionalEdges:c}=wn(n,i),m=Sn(r,n,i),g=[],y=e.workflowType||"workflow";return g.push(un(e)),g.push(pn(y,{usesRegisteredNodes:l})),g.push(fn(f)),g.push(hn(y)),g.push(gn(r,s)),g.push(mn(r,m,d,c,u,y)),g.filter(Boolean).join(`
50
+ `)}`}ue();W();var ve={};function Qe(o,e){if(Array.isArray(e))return Xe(e);let t=ve[o];return!t||t.length===0?null:Xe(t)}function Xe(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},n=[];for(let s of o){let i=q(s);if(!i){v.warn(`[workflow] unknown skill "${s}" \u2014 skipping`);continue}n.push(s);for(let r of i.tools||[])e.push({name:r.name,description:r.description,input_schema:r.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let r=i.resolve();r&&(t[i.serverName]={...r,toolPrefix:s})}else{let r={};for(let a of i.envKeys||[]){let l=process.env[a];l&&(r[a]=l)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:r,toolPrefix:s}}}return n.length===0?null:{toolIds:n,claudeTools:e,mcpServers:t}}W();function on(o,e={}){let{nodes:t,edges:n,nodeConfigs:s={}}=o;if(!Array.isArray(t)||t.length===0)throw new M("Graph must have at least one node");if(!Array.isArray(n))throw new M("Graph edges must be an array");let i=new ee(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let r=new Set,a=new Map,l={};for(let c of t){let m=$e(c);a.set(c.id,{...c,resolvedType:m}),m==="decision"&&r.add(c.id)}for(let[c,m]of a){if(r.has(c))continue;let g=m.resolvedType,y=s[c]||{},I=Qe(g,y.tools);I&&(l[c]=I);let _={};y.prompt&&(_.prompt=y.prompt);let h=Ie(g);if(v.debug(`[workflow] compiler: node "${c}" type="${g}" registered=${h}`),y.customCode&&!h)i.addNode(c,ro(c,y.customCode,y),_),i.setNodeType(c,g);else if(h){let S=Ke(g);S.factory?i.addNode(c,S.create(c,{...y,resolvedTools:I}),_):i.addNode(c,S,_),i.setNodeType(c,g)}else if(y.executeCode)i.addNode(c,ro(c,y.executeCode,y),_),i.setNodeType(c,g);else throw new M(`Unknown node type "${g}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=l;let u=new Set;for(let c of n)r.has(c.target)||u.add(c.target);let f=t.find(c=>!r.has(c.id)&&!u.has(c.id));if(!f)throw new M("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(f.id);let d=sn(n,"source");for(let c of n)if(!r.has(c.source))if(r.has(c.target)){let m=c.target,g=d.get(m)||[];if(g.length===0)throw new M(`Decision node "${m}" has no outgoing edges`);let y=an(m,g,r);i.addConditionalEdges(c.source,y)}else i.addEdge(c.source,c.target);return i}function nn(o){let e=[];if(!o||typeof o!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(o.nodes)||o.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(o.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=o.nodeConfigs||{};for(let a of o.nodes){let l=$e(a);if(l==="decision"||Ie(l))continue;let u=t[a.id]||{};u.customCode||u.executeCode||e.push(`Unknown node type "${l}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let n=new Set(o.nodes.map(a=>a.id));for(let a of o.edges)n.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),n.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let s=new Set(o.nodes.filter(a=>$e(a)==="decision").map(a=>a.id)),i=new Set;for(let a of o.edges)s.has(a.target)||i.add(a.target);let r=o.nodes.filter(a=>!s.has(a.id)&&!i.has(a.id));r.length===0?e.push("No entry point found (every node has incoming edges)"):r.length>1&&e.push(`Multiple entry points found: ${r.map(a=>a.id).join(", ")}`);for(let a of s){let l=o.edges.filter(f=>f.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(f=>f.data?.conditionalCode||f.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function rn(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>$e(e)!=="decision").map(e=>e.id)}function $e(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function sn(o,e){let t=new Map;for(let n of o){let s=n[e];t.has(s)||t.set(s,[]),t.get(s).push(n)}return t}function an(o,e,t){let n=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!n)throw new M(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let s=n.data?.conditionalCode||n.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),r;try{let l=new Function(`return (${s})`)();r=u=>{let f=l(u);return i.has(f)||v.warn(`[workflow] conditional route from "${o}" returned "${f}" which is not in valid targets: ${[...i].join(", ")}`),f}}catch(a){throw new M(`Failed to compile conditionalCode for "${o}": ${a.message}`)}return r}function ro(o,e,t={}){let n;try{n=new Function("invokeAgent","require","console",`return (${e})`)}catch(r){throw new M(`Failed to compile customCode for node "${o}": ${r.message}`)}let s=n(async(...r)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(X(),pe));return a(...r)},typeof xe<"u"?xe:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:i,execute:async r=>{try{let a=await s(r);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var M=class extends Error{constructor(e){super(e),this.name="CompilationError"}};ue();var et=/^[a-z][a-z0-9_]{0,40}$/;function cn(o){if(o==null)return[];if(!Array.isArray(o))return["stores must be an array of { name, description } objects"];let e=[],t=new Map;return o.forEach((n,s)=>{if(n==null||typeof n!="object"||Array.isArray(n)){e.push(`stores[${s}] must be an object { name, description }`);return}let{name:i}=n;if(typeof i!="string"||i.length===0){e.push(`stores[${s}] is missing a string "name"`);return}et.test(i)||e.push(`stores[${s}] name "${i}" is invalid \u2014 must match ${et} (lowercase letter first, then up to 40 of [a-z0-9_])`),t.has(i)?e.push(`stores[${s}] duplicate store name "${i}" (also at index ${t.get(i)}) \u2014 store names must be unique within a workflow`):t.set(i,s)}),e}Be();X();function ln(o,e={}){let{nodes:t,edges:n,nodeConfigs:s={}}=o,i=new Set,r=[],a=new Map;for(let I of t){let _=I.data?.nodeType||I.type;a.set(I.id,_),_==="decision"?i.add(I.id):r.push({id:I.id,nodeType:_,label:I.data?.label||I.id})}let l=r.some(I=>{let _=s[I.id]||{};return!_.customCode&&!_.executeCode}),{toolsPerNode:u,toolIdsByVar:f}=yn(r,s),{simpleEdges:d,conditionalEdges:c}=wn(n,i),m=Sn(r,n,i),g=[],y=e.workflowType||"workflow";return g.push(un(e)),g.push(pn(y,{usesRegisteredNodes:l})),g.push(fn(f)),g.push(hn(y)),g.push(gn(r,s)),g.push(mn(r,m,d,c,u,y)),g.filter(Boolean).join(`
51
51
  `)}function dn(o){let e={};for(let[t,n]of Object.entries(o)){let{tools:s,...i}=n;Object.keys(i).length>0&&(e[t]=i)}return e}function un(o){let e=o.workflowType||"workflow";return["// Generated workflow",`// ${o.projectId?`Project: ${o.projectId} | `:""}Type: ${e} | Version: ${o.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
52
52
  `)}function pn(o,{usesRegisteredNodes:e=!0}={}){let t=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return e&&t.push("// import './register-nodes.js'; // register custom node types here"),t.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),t.join(`
53
53
  `)}function fn(o){if(o.size===0)return"";let e=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];for(let[t,n]of o)e.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(n)}); // ${n.join(", ")}`);return e.push(""),e.join(`
@@ -125,4 +125,4 @@ template workflow.json) and paste the exact array. The platform then
125
125
  automatically SUPPRESSES the wrapped members' own subscriptions (any workflow
126
126
  listed in a deployed wrapper's composedOf stops receiving standalone webhook
127
127
  events), so the same event never double-fires a brick inside AND outside the
128
- wrapper. Cron / manual / chat-triggered compositions need nothing special.`;export{Be as AgentStrategy,je as CI_ENV_VARS,_n as COMPOSE_KNOWLEDGE,B as CompilationError,he as ContextLoader,le as DEFAULT_OUTPUT_BASE,vo as EVENTS_FILE,ee as Graph,ve as NODE_DEFAULT_TOOLS,$o as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,F as Node,ie as OutputParser,Io as RAW_OUTPUT_FILE,bo as RESULT_FILE,Ce as SESSIONS_DIR,G as SESSION_INFO_FILE,Re as STOP_REQUEST_FILE,et as STORE_NAME_REGEX,So as SchemaTypes,_e as Timeline,wt as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,ee as WorkflowGraph,se as WorkflowState,Qt as clearInheritedSessionEnvForFreshRun,vt as clearSkills,on as compileGraph,Je as dispatchSubgraph,rn as extractSteps,dn as generateNodeConfigsJson,ln as generateWorkflowCode,to as generateWorkflowSessionId,We as getAgentStrategy,bt as getAllSkills,Ke as getNodeImpl,qe as getNodeTemplate,Xe as getResolvedToolDefinitions,q as getSkill,Et as getSkillSource,Ie as hasNode,_t as hasSkill,xt as invokeAgent,en as listNodeTypes,It as listSkillIds,kt as listStrategies,Xt as readPinnedSessionPathFromEnv,no as registerNode,St as registerSkill,Tt as registerStrategy,Qe as resolveNodeTools,oo as resolveWorkflowSession,_o as setLogger,qt as shouldTrustInheritedSessionEnv,eo as syncProcessEnvToSession,x as timeline,nn as validateGraphConfig,cn as validateStoreDefs};
128
+ wrapper. Cron / manual / chat-triggered compositions need nothing special.`;export{Me as AgentStrategy,je as CI_ENV_VARS,_n as COMPOSE_KNOWLEDGE,M as CompilationError,he as ContextLoader,le as DEFAULT_OUTPUT_BASE,vo as EVENTS_FILE,ee as Graph,ve as NODE_DEFAULT_TOOLS,$o as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,F as Node,ie as OutputParser,Io as RAW_OUTPUT_FILE,bo as RESULT_FILE,Ce as SESSIONS_DIR,G as SESSION_INFO_FILE,Re as STOP_REQUEST_FILE,et as STORE_NAME_REGEX,So as SchemaTypes,_e as Timeline,wt as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,ee as WorkflowGraph,se as WorkflowState,Qt as clearInheritedSessionEnvForFreshRun,vt as clearSkills,on as compileGraph,Je as dispatchSubgraph,rn as extractSteps,dn as generateNodeConfigsJson,ln as generateWorkflowCode,to as generateWorkflowSessionId,We as getAgentStrategy,bt as getAllSkills,Ke as getNodeImpl,qe as getNodeTemplate,Xe as getResolvedToolDefinitions,q as getSkill,Et as getSkillSource,Ie as hasNode,_t as hasSkill,xt as invokeAgent,en as listNodeTypes,It as listSkillIds,kt as listStrategies,Xt as readPinnedSessionPathFromEnv,no as registerNode,St as registerSkill,Tt as registerStrategy,Qe as resolveNodeTools,oo as resolveWorkflowSession,_o as setLogger,qt as shouldTrustInheritedSessionEnv,eo as syncProcessEnvToSession,x as timeline,nn as validateGraphConfig,cn as validateStoreDefs};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/agent-workflow",
3
- "version": "0.6.2",
3
+ "version": "0.6.3",
4
4
  "description": "Graph-based AI agent workflow orchestration. Bring your own agent strategies.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",