@zibby/agent-workflow 2.0.2 → 2.0.4

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