@zibby/agent-workflow 0.6.8 → 0.6.10

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