@zibby/agent-workflow 0.6.0 → 0.6.1

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.
@@ -54,6 +54,18 @@ export declare function getExecContext(): any;
54
54
  * @returns {Promise<T> | T}
55
55
  */
56
56
  export declare function runInContext(ctx: any, fn: any): unknown;
57
+ /**
58
+ * Add the currently-running graph's `agent` shell + abort `signal` to the
59
+ * active context WITHOUT touching executionId / parentExecutionId / depth.
60
+ *
61
+ * The engine wraps each node's execute() in this so a node that hand-rolls
62
+ * `dispatchSubgraph(slug, { input })` — the documented fan-out pattern — gets
63
+ * the parent agent + cancel signal AUTOMATICALLY, exactly like the built-in
64
+ * sub-workflow node form already does. Without it, a hand-rolled dispatch ran
65
+ * the in-process child with no agent (LLM nodes fail) or fell back to HTTP.
66
+ * Explicitly-passed `parentAgent`/`signal` still win — this only fills the gap.
67
+ */
68
+ export declare function withAgentContext(agent: any, signal: any, fn: any): unknown;
57
69
  /**
58
70
  * Synchronously initialize the root execution context. Use this at the
59
71
  * very top of the CLI entrypoint — `runInContext` is the preferred call
@@ -1 +1 @@
1
- import{AsyncLocalStorage as d}from"node:async_hooks";var t=new d;function c(){let e=t.getStore();return e||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function i(e,o){let n=t.getStore()||c(),r=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??n.executionId??null,depth:(n.depth||0)+(e.executionId!==n.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:n.conversationId??null,dispatchMode:e.dispatchMode??null});return t.run(r,o)}function I(e,o){return t.run(Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??null,depth:0,conversationId:e.conversationId??null,dispatchMode:e.dispatchMode??"cold"}),o)}export{c as getExecContext,i as runInContext,I as withRootContext};
1
+ import{AsyncLocalStorage as i}from"node:async_hooks";var t=new i;function l(){let n=t.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 d(n,o){let e=t.getStore()||l(),r=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??e.executionId??null,depth:(e.depth||0)+(n.executionId!==e.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:e.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:e.agent??null,signal:n.signal!==void 0?n.signal:e.signal??null});return t.run(r,o)}function s(n,o,e){let r=t.getStore()||l(),u=Object.freeze({...r,agent:n??r.agent??null,signal:o??r.signal??null});return t.run(u,e)}function c(n,o){return t.run(Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??null,depth:0,conversationId:n.conversationId??null,dispatchMode:n.dispatchMode??"cold",agent:n.agent??null,signal:n.signal??null}),o)}export{l as getExecContext,d as runInContext,s as withAgentContext,c as withRootContext};
@@ -1,4 +1,4 @@
1
- var Wt=Object.defineProperty;var we=(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 ae=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var Je=(n,e)=>{for(var t in e)Wt(n,t,{get:e[t],enumerable:!0})};var Ye,Gt,ue,b,W=ae(()=>{Ye=()=>{},Gt={debug:Ye,info:Ye,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},ue={impl:Gt},b={debug:(...n)=>ue.impl.debug?.(...n),info:(...n)=>ue.impl.info?.(...n),warn:(...n)=>ue.impl.warn?.(...n),error:(...n)=>ue.impl.error?.(...n)}});var ot=ae(()=>{});var rt={};Je(rt,{clearSkills:()=>Vt,getAllSkills:()=>qt,getSkill:()=>ee,getSkillSource:()=>zt,hasSkill:()=>Zt,listSkillIds:()=>Kt,registerSkill:()=>Yt});function Yt(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(F.has(s)&&!o){let i=Q.get(s);if(!(i===t)){let a=i||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${s}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}F.set(s,Object.freeze({...n})),t===void 0?Q.delete(s):Q.set(s,t)}function ee(n){return F.get(n)||null}function Zt(n){return F.has(n)}function zt(n){return Q.get(n)||null}function qt(){return new Map(F)}function Kt(){return Array.from(F.keys())}function Vt(){F.clear(),Q.clear()}var $e,ve,F,Q,pe=ae(()=>{$e=Symbol.for("@zibby/agent-workflow.skills"),ve=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[$e]||(globalThis[$e]=new Map);globalThis[ve]||(globalThis[ve]=new Map);F=globalThis[$e],Q=globalThis[ve]});var te={};Je(te,{getAgentStrategy:()=>it,invokeAgent:()=>en,listStrategies:()=>Qt,registerStrategy:()=>Xt,resolveInvocationModel:()=>st});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=G.findIndex(t=>t.getName()===n.getName());e>=0?G[e]=n:G.push(n)}function Qt(){return G.map(n=>n.getName())}function st({config:n={},options:e={},strategyName:t,envModel:o}={}){let s=n.models||{},i=e.nodeName&&s[e.nodeName]||null,r=s.default||null,a=n.agent?.[t]?.model||null,u=(typeof o=="string"?o.trim():"")||null;return i||r||a||e.model||u||null}function it(n={}){let{state:e={},preferredAgent:t=null}=n,o=t||e.agentType||process.env.AGENT_TYPE;if(!o){let i=G.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}b.debug(`[workflow] agent selection: requested=${o}`);let s=G.find(i=>i.getName()===o);if(!s){let i=G.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 b.debug(`[workflow] using agent: ${s.getName()}`),s}async function en(n,e={},t={}){let o=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:o},i=it(s),r=o.config||t.config||{},a=st({config:r,options:t,strategyName:i.name,envModel:process.env.MODEL}),u={...t,model:a,workspace:o.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],extraMcpServers:t.extraMcpServers||o.extraMcpServers||e.extraMcpServers||[],plugins:t.plugins||e.plugins||[],config:r},d=n,f=u.skills||[];if(f.length>0&&!t.skipPromptFragments){let y=f.map(g=>{let m=ee(g)?.promptFragment;return typeof m=="function"?m():m}).filter(Boolean);y.length>0&&(d+=`
1
+ var Ft=Object.defineProperty;var _e=(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 ce=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var Je=(n,e)=>{for(var t in e)Ft(n,t,{get:e[t],enumerable:!0})};var Ye,Ht,de,b,U=ce(()=>{Ye=()=>{},Ht={debug:Ye,info:Ye,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},de={impl:Ht},b={debug:(...n)=>de.impl.debug?.(...n),info:(...n)=>de.impl.info?.(...n),warn:(...n)=>de.impl.warn?.(...n),error:(...n)=>de.impl.error?.(...n)}});var ot=ce(()=>{});var rt={};Je(rt,{clearSkills:()=>Xt,getAllSkills:()=>Kt,getSkill:()=>te,getSkillSource:()=>qt,hasSkill:()=>Zt,listSkillIds:()=>Vt,registerSkill:()=>zt});function zt(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:o=!1}=e,r=n.id;if(F.has(r)&&!o){let i=ee.get(r);if(!(i===t)){let a=i||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${r}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}F.set(r,Object.freeze({...n})),t===void 0?ee.delete(r):ee.set(r,t)}function te(n){return F.get(n)||null}function Zt(n){return F.has(n)}function qt(n){return ee.get(n)||null}function Kt(){return new Map(F)}function Vt(){return Array.from(F.keys())}function Xt(){F.clear(),ee.clear()}var ve,Te,F,ee,fe=ce(()=>{ve=Symbol.for("@zibby/agent-workflow.skills"),Te=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[ve]||(globalThis[ve]=new Map);globalThis[Te]||(globalThis[Te]=new Map);F=globalThis[ve],ee=globalThis[Te]});var ne={};Je(ne,{getAgentStrategy:()=>it,invokeAgent:()=>tn,listStrategies:()=>en,registerStrategy:()=>Qt,resolveInvocationModel:()=>st});function Qt(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=G.findIndex(t=>t.getName()===n.getName());e>=0?G[e]=n:G.push(n)}function en(){return G.map(n=>n.getName())}function st({config:n={},options:e={},strategyName:t,envModel:o}={}){let r=n.models||{},i=e.nodeName&&r[e.nodeName]||null,s=r.default||null,a=n.agent?.[t]?.model||null,u=(typeof o=="string"?o.trim():"")||null;return i||s||a||e.model||u||null}function it(n={}){let{state:e={},preferredAgent:t=null}=n,o=t||e.agentType||process.env.AGENT_TYPE;if(!o){let i=G.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}b.debug(`[workflow] agent selection: requested=${o}`);let r=G.find(i=>i.getName()===o);if(!r){let i=G.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${i}`)}if(!r.canHandle(n))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return b.debug(`[workflow] using agent: ${r.getName()}`),r}async function tn(n,e={},t={}){let o=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},r={...e,state:o},i=it(r),s=o.config||t.config||{},a=st({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL}),u={...t,model:a,workspace:o.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],extraMcpServers:t.extraMcpServers||o.extraMcpServers||e.extraMcpServers||[],plugins:t.plugins||e.plugins||[],config:s},d=n,f=u.skills||[];if(f.length>0&&!t.skipPromptFragments){let y=f.map(g=>{let m=te(g)?.promptFragment;return typeof m=="function"?m():m}).filter(Boolean);y.length>0&&(d+=`
2
2
 
3
3
  ${y.join(`
4
4
 
@@ -14,37 +14,37 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
14
14
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
15
15
 
16
16
  ${c}
17
- `),b.debug(`[workflow] prompt length: ${d.length} chars`),i.invoke(d,u)}var Te,G,ne=ae(()=>{ot();W();pe();Te=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Te]||(globalThis[Te]=[]);G=globalThis[Te]});var Ft=new Set(["__proto__","constructor","prototype"]);function _e(n){if(Ft.has(n))throw new Error(`Invalid state key: "${n}"`)}var ce=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){_e(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)_e(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){_e(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 H from"handlebars";var le=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:
17
+ `),b.debug(`[workflow] prompt length: ${d.length} chars`),i.invoke(d,u)}var ke,G,oe=ce(()=>{ot();U();fe();ke=Symbol.for("@zibby/agent-workflow.strategies");globalThis[ke]||(globalThis[ke]=[]);G=globalThis[ke]});var Gt=new Set(["__proto__","constructor","prototype"]);function be(n){if(Gt.has(n))throw new Error(`Invalid state key: "${n}"`)}var le=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){be(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)be(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){be(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 H from"handlebars";var ue=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let o=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(r=>r[0]);for(let r of o)try{return this.validate(JSON.parse(r))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,r]of Object.entries(this.schema)){if(r.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&r.type){let i=typeof e[o];i!==r.type&&t.push(`Field '${o}' expected ${r.type}, got ${i}`)}if(r.validate&&o in e){let i=r.validate(e[o]);i&&t.push(`Field '${o}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
18
18
  ${t.join(`
19
- `)}`);return e}};W();import{writeFileSync as ke,readFileSync as at,existsSync as ct,mkdirSync as tn}from"node:fs";import{join as Ae,dirname as nn}from"node:path";import x from"chalk";var Ht="__WORKFLOW_GRAPH_LOG__",X=x.gray("\u2502"),Jt=x.gray("\u250C"),Ze=x.gray("\u2514"),be=x.green("\u25C6"),ze=x.hex("#c084fc")("\u25C6"),qe=x.hex("#2dd4bf")("\u25C6"),Ie=x.red("\u25C6"),Ke=`${X} `,Ve=2;function Xe(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function Qe(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 u=t[a];e.lineStart&&(r+=Ke,e.col=Ve,e.lineStart=!1),u===`
20
- `?(r+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,r+=u):e.inEsc?(r+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,r+=u,e.col>=i&&(r+=`
21
- ${Ke}`,e.col=Ve))}return n(r,o,s)}}var Ee=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=Qe(this._origStdoutWrite,e),process.stderr.write=Qe(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
19
+ `)}`);return e}};U();import{writeFileSync as Ae,readFileSync as at,existsSync as ct,mkdirSync as nn}from"node:fs";import{join as xe,dirname as on}from"node:path";import x from"chalk";var Jt="__WORKFLOW_GRAPH_LOG__",Q=x.gray("\u2502"),Yt=x.gray("\u250C"),ze=x.gray("\u2514"),Ie=x.green("\u25C6"),Ze=x.hex("#c084fc")("\u25C6"),qe=x.hex("#2dd4bf")("\u25C6"),Ee=x.red("\u25C6"),Ke=`${Q} `,Ve=2;function Xe(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function Qe(n,e){return(t,o,r)=>{if(typeof t!="string")return n(t,o,r);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let u=t[a];e.lineStart&&(s+=Ke,e.col=Ve,e.lineStart=!1),u===`
20
+ `?(s+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,s+=u):e.inEsc?(s+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,s+=u,e.col>=i&&(s+=`
21
+ ${Ke}`,e.col=Ve))}return n(s,o,r)}}var $e=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=Qe(this._origStdoutWrite,e),process.stderr.write=Qe(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=`${Ht}${JSON.stringify(e)}
24
+ `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Jt}${JSON.stringify(e)}
25
25
  `;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
26
26
  `),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
27
27
  `)):process.stdout.write.bind(process.stdout)(`${e} ${t}
28
- `)}step(e){this._origStdoutWrite?this._writeDot(be,e):process.stdout.write.bind(process.stdout)(`${X} ${be} ${e}
29
- `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(ze,e):process.stdout.write.bind(process.stdout)(`${X} ${ze} ${e}
30
- `)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(qe,t):process.stdout.write.bind(process.stdout)(`${X} ${qe} ${t}
31
- `)}stepFail(e){this._origStdoutWrite?this._writeDot(Ie,x.red(e)):process.stdout.write.bind(process.stdout)(`${X} ${Ie} ${x.red(e)}
32
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Jt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:s}=t;if(s)for(let r of s)this._rawWrite(`${be} ${r}`);let i=o?x.dim(` ${Xe(o)}`):"";this._rawWrite(`${Ze} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:s}=o,i=s?x.dim(` ${Xe(s)}`):"";this._rawWrite(`${Ie} ${x.red(t)}`),this._rawWrite(`${Ze} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},P=new Ee;var de=".zibby/output",et="sessions",K=".session-info.json",tt=".zibby-stop";var Zn=Object.freeze(["codebase-memory","code-scan","artifact"]),nt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];H.helpers.inc||H.registerHelper("inc",n=>Number(n)+1);H.helpers.json||H.registerHelper("json",n=>JSON.stringify(n,null,2));H.helpers.eq||H.registerHelper("eq",(n,e)=>n===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new le(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return b.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=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){b.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(b.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){return b.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&b.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=H.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(o())):i=this.prompt;let r=s("_skillHints");r&&(i=`${r}
28
+ `)}step(e){this._origStdoutWrite?this._writeDot(Ie,e):process.stdout.write.bind(process.stdout)(`${Q} ${Ie} ${e}
29
+ `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Ze,e):process.stdout.write.bind(process.stdout)(`${Q} ${Ze} ${e}
30
+ `)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(qe,t):process.stdout.write.bind(process.stdout)(`${Q} ${qe} ${t}
31
+ `)}stepFail(e){this._origStdoutWrite?this._writeDot(Ee,x.red(e)):process.stdout.write.bind(process.stdout)(`${Q} ${Ee} ${x.red(e)}
32
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Yt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:r}=t;if(r)for(let s of r)this._rawWrite(`${Ie} ${s}`);let i=o?x.dim(` ${Xe(o)}`):"";this._rawWrite(`${ze} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:r}=o,i=r?x.dim(` ${Xe(r)}`):"";this._rawWrite(`${Ee} ${x.red(t)}`),this._rawWrite(`${ze} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},O=new $e;var pe=".zibby/output",et="sessions",K=".session-info.json",tt=".zibby-stop";var Zn=Object.freeze(["codebase-memory","code-scan","artifact"]),nt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];H.helpers.inc||H.registerHelper("inc",n=>Number(n)+1);H.helpers.json||H.registerHelper("json",n=>JSON.stringify(n,null,2));H.helpers.eq||H.registerHelper("eq",(n,e)=>n===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new ue(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 b.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let o=()=>t&&typeof t.getAll=="function"?t.getAll():e,r=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){b.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(b.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){return b.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&b.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=H.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(o())):i=this.prompt;let s=r("_skillHints");s&&(i=`${s}
33
33
 
34
- ${i}`);let a=o(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Ae(d,K);if(ct(l)){let y=JSON.parse(at(l,"utf-8"));y.currentNode=this.name,ke(l,JSON.stringify(y,null,2),"utf-8")}let c=Ae(d,"..",K);if(ct(c))try{let y=JSON.parse(at(c,"utf-8"));y.currentNode=this.name,ke(c,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(l){b.debug(`[workflow] could not update session info: ${l.message}`)}let f=null;for(let l=0;l<=this.retries;l++)try{b.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=o().config||{},y=c.agents||{},g=this.config.agent??y[this.name]??null,m={state:o()};g&&(m.preferredAgent=g);let v={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},I=e?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(ne(),te))).invokeAgent);let h=await I(i,m,v),S,w;if(typeof h=="string"?(S=h,w=null):h.structured?(S=h.raw||JSON.stringify(h.structured,null,2),w=h.structured):(S=h.raw||JSON.stringify(h,null,2),w=h.extracted||null),d)try{let p=Ae(d,this.name,"raw_stream_output.txt");tn(nn(p),{recursive:!0}),ke(p,typeof S=="string"?S:JSON.stringify(S),"utf-8")}catch(p){b.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&w){b.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(w,null,2)}`);let p=w;if(typeof this.onComplete=="function")try{p=await this.onComplete(o(),w)}catch($){b.warn(`[workflow] onComplete hook failed: ${$.message}`)}return{success:!0,output:p,raw:S}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:S}),raw:S}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(S);return b.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),P.step("Output parsed"),{success:!0,output:p,raw:S}}return{success:!0,output:S,raw:S}}catch(c){f=c,l<this.retries&&b.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:f.message,raw:null}}};W();W();import{mkdirSync as sn,existsSync as Y,statSync as yt,readdirSync as St,rmSync as an}from"node:fs";import{spawn as ht}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as cn}from"node:url";import{AsyncLocalStorage as ln}from"node:async_hooks";import{AsyncLocalStorage as on}from"node:async_hooks";var xe=new on;function oe(){let n=xe.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})}function lt(n,e){let t=xe.getStore()||oe(),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});return xe.run(o,e)}var Pe=new Map,Oe=new Map,ut=new Map;function dt(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");Pe.set(n,e),Oe.set(n,"ready"),ut.set(n,{...t,cachedAt:Date.now()})}function pt(n,e){Oe.set(n,"failed"),ut.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Pe.delete(n)}function ft(n){return Oe.get(n)==="ready"?Pe.get(n):null}var fe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function un(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var O=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}},gt=new ln,mt=Promise.resolve();async function dn(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=gt.getStore()===!0,s=null;if(!o){let r=mt;mt=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 b.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await gt.run(!0,e)}finally{for(let[r,a]of i)a===void 0?delete process.env[r]:process.env[r]=a;s&&s()}}function pn(){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 O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:s}}async function fn({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 O("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 O("begin-status",`begin returned ${o.status}`)}return s?.data||s}async function J({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||b.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){b.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function hn(n,e){let t=U(e,".ready"),o=U(e,"graph.mjs");if(Y(t)&&Y(o))return;sn(e,{recursive:!0});let s=U(e,".lock"),i=!1;try{let{openSync:r,closeSync:a}=await import("node:fs"),u=r(s,"wx");a(u),i=!0}catch(r){if(r.code!=="EEXIST")throw r}if(!i){let r=Date.now()+3e4;for(;Date.now()<r;){if(Y(t)&&Y(o))return;await new Promise(a=>setTimeout(a,100))}throw new O("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let f=ht("curl",["-fsSL",n],{stdio:["ignore","pipe","inherit"]}),l=ht("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(l.stdin);let c,y,g=()=>{if(c!==void 0&&y!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(y!==0)return d(new Error(`tar exited ${y}`));u()}};f.on("close",m=>{c=m,g()}),l.on("close",m=>{y=m,g()}),f.on("error",d),l.on("error",d)});let{writeFileSync:r,unlinkSync:a}=await import("node:fs");r(t,"");try{a(s)}catch{}}catch(r){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new O("bundle-extract-failed",r.message)}}async function gn(n){let e=U(n,"graph.mjs");if(!Y(e))throw new O("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(cn(e).href)}catch(s){throw new O("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 O("entry-class-missing","no buildGraph() class export found");return o}async function wt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=oe(),o;try{o=pn()}catch(p){throw p}b.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let s=await fn({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:u,workflowVersion:d,workflowUuid:f,bundleReady:l,nodeConfigs:c}=s,y=un();if(r&&r!==y)throw await J({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:`runtimeTag mismatch: parent=${y} child=${r}`,code:"RUNTIME_MISMATCH"}}}),new O("runtime-mismatch",`${y} vs ${r}`);if(!l||!a)throw await J({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new O("no-bundle","workflow bundle not built yet");let g=ft(n);if(!g){let p=U(fe,`${f}@${d||"0"}`);try{await hn(a,p);try{yn()}catch{}}catch($){throw $.fallback&&await J({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{g=await gn(p),dt(n,g,{workflowUuid:f,version:d,runtimeTag:r,cacheDir:p})}catch($){throw pt(n,$),await J({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new O("import-failed",$.message)}}let m=Date.now(),v=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,I=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...I?{nodeConfigs:c}:{}},S,w;try{S=await dn(v,async()=>{let $=await(typeof g=="function"&&g.prototype?.buildGraph?new g:g).buildGraph();return lt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,h,{signal:e.signal}))}),w=S&&typeof S=="object"&&"state"in S?S.state:S}catch(p){throw await J({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-m}}),p}if(S&&typeof S=="object"&&S.stoppedExternally){await J({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"canceled",finalState:w,durationMs:Date.now()-m}});let p=new Error(`Sub-graph '${n}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await J({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"completed",finalState:w,durationMs:Date.now()-m}}),{finalState:w,executionId:i}}function mn(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),s;try{s=yt(o)}catch{continue}if(s.isDirectory()){let i;try{i=St(o)}catch{continue}for(let r of i)t.push(U(o,r))}else e+=s.size}return e}function yn({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(fe))return{evicted:0,freedBytes:0};let e=St(fe),t=[],o=0;for(let a of e){let u=U(fe,a),d;try{d=yt(u)}catch{continue}let f=d.isDirectory()?mn(u):d.size;o+=f,t.push({name:a,full:u,size:f,mtimeMs:d.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let s=Math.floor(n*.7),i=0,r=0;for(let a of t){if(o-i<=s)break;if(!Y(U(a.full,".lock")))try{an(a.full,{recursive:!0,force:!0}),i+=a.size,r+=1}catch(u){b.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return r>0&&b.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 b.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Sn=2e3,wn=600*1e3,_n=new Set(["completed","failed","canceled","timeout"]);function bn(){let 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 In(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function En(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function $n(){return process.env.EXECUTION_ID||null}function _t(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 bt(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=oe(),o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=o)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{b.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:w}=await wt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=_t(w,e.output);return b.info(`[sub-graph] '${n}' completed in-process`),p}catch(w){if(w instanceof O||w?.fallback)b.info(`[sub-graph] in-process fallback for '${n}': ${w.reason||"unknown"} \u2014 using HTTP`);else throw w}let s=bn(),i=In(),r=En(),a=$n(),u=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(n)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};b.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let f=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(d)});if(!f.ok){let w=null,p="";try{w=await f.json(),p=w?.error||w?.message||JSON.stringify(w)}catch{p=await f.text().catch(()=>"")}if(f.status===429){let k=w?.quotaInfo||{},M=new Error(`Sub-graph '${n}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=n,M.quotaInfo=k,M}if(f.status===400){let k=new Error(`Sub-graph '${n}' rejected input: ${p}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=n,k.validationErrors=w?.validationErrors||null,k.missing=w?.missing||null,k}let $=new Error(`Sub-graph '${n}' trigger rejected (${f.status}): ${p}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=f.status,$.subgraph=n,$}let l=await f.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return b.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:n};let y=Number.isFinite(e.timeoutMs)?e.timeoutMs:wn,g=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Sn,m=`${s}/executions/${encodeURIComponent(c)}`,v=Date.now()+y,I="accepted",h=0;for(;Date.now()<v;){await new Promise(k=>setTimeout(k,g)),h+=1;let w=await fetch(m,{headers:{Authorization:`Bearer ${r}`}});if(!w.ok){if(w.status>=500){b.warn(`[sub-graph] status poll for ${c} returned ${w.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${w.status}`)}let p=await w.json(),$=p?.data||p?.execution||p;if(I=$?.status||I,_n.has(I)){if(I!=="completed"){let _=new Error(`Sub-graph '${n}' (${c}) ended in status '${I}'`);throw _.subgraphJobId=c,_.subgraphStatus=I,_}let k=$?.finalState||$?.state||{},M=_t(k,e.output);return b.info(`[sub-graph] '${n}' (${c}) completed after ${h} polls`),M}}let S=new Error(`Sub-graph '${n}' (${c}) timed out after ${Math.round(y/1e3)}s (last status: ${I})`);throw S.subgraphJobId=c,S.subgraphStatus=I,S}import{existsSync as It,readFileSync as vn}from"node:fs";import{join as Ne,dirname as Et}from"node:path";var he=class{static async loadContext(e,t,o={}){let s={},i=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Et(Ne(t,e));for(let u of i){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let f=u.replace(/\.[^.]+$/,"").toLowerCase();s[f]=d}}}let r=o.discovery||{};for(let[a,u]of Object.entries(r))try{let d=Ne(t,u);It(d)&&(s[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return s}static async findAndMergeContextFiles(e,t,o){let s=[],i=t;for(;i.startsWith(o);){let r=Ne(i,e);if(It(r))try{s.unshift(await this.loadFile(r))}catch(u){console.warn(`[workflow] could not load ${e} from ${r}: ${u.message}`)}let a=Et(i);if(a===i)break;i=a}return s.length===0?null:s.every(r=>typeof r=="string")?s.join(`
34
+ ${i}`);let a=o(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=xe(d,K);if(ct(l)){let y=JSON.parse(at(l,"utf-8"));y.currentNode=this.name,Ae(l,JSON.stringify(y,null,2),"utf-8")}let c=xe(d,"..",K);if(ct(c))try{let y=JSON.parse(at(c,"utf-8"));y.currentNode=this.name,Ae(c,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(l){b.debug(`[workflow] could not update session info: ${l.message}`)}let f=null;for(let l=0;l<=this.retries;l++)try{b.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=o().config||{},y=c.agents||{},g=this.config.agent??y[this.name]??null,m={state:o()};g&&(m.preferredAgent=g);let v={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},I=e?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(oe(),ne))).invokeAgent);let h=await I(i,m,v),S,w;if(typeof h=="string"?(S=h,w=null):h.structured?(S=h.raw||JSON.stringify(h.structured,null,2),w=h.structured):(S=h.raw||JSON.stringify(h,null,2),w=h.extracted||null),d)try{let p=xe(d,this.name,"raw_stream_output.txt");nn(on(p),{recursive:!0}),Ae(p,typeof S=="string"?S:JSON.stringify(S),"utf-8")}catch(p){b.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&w){b.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(w,null,2)}`);let p=w;if(typeof this.onComplete=="function")try{p=await this.onComplete(o(),w)}catch($){b.warn(`[workflow] onComplete hook failed: ${$.message}`)}return{success:!0,output:p,raw:S}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:S}),raw:S}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(S);return b.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),O.step("Output parsed"),{success:!0,output:p,raw:S}}return{success:!0,output:S,raw:S}}catch(c){f=c,l<this.retries&&b.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:f.message,raw:null}}};U();U();import{mkdirSync as an,existsSync as Y,statSync as St,readdirSync as wt,rmSync as cn}from"node:fs";import{spawn as gt}from"node:child_process";import{join as W}from"node:path";import{pathToFileURL as ln}from"node:url";import{AsyncLocalStorage as un}from"node:async_hooks";import{AsyncLocalStorage as rn}from"node:async_hooks";var re=new rn;function V(){let n=re.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 lt(n,e){let t=re.getStore()||V(),o=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return re.run(o,e)}function ut(n,e,t){let o=re.getStore()||V(),r=Object.freeze({...o,agent:n??o.agent??null,signal:e??o.signal??null});return re.run(r,t)}var Oe=new Map,Pe=new Map,dt=new Map;function pt(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");Oe.set(n,e),Pe.set(n,"ready"),dt.set(n,{...t,cachedAt:Date.now()})}function ft(n,e){Pe.set(n,"failed"),dt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Oe.delete(n)}function ht(n){return Pe.get(n)==="ready"?Oe.get(n):null}var he=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function dn(){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"}},mt=new un,yt=Promise.resolve();async function pn(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(t.length===0)return e();let o=mt.getStore()===!0,r=null;if(!o){let s=yt;yt=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 b.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await mt.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;r&&r()}}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,r=process.env.PROJECT_API_TOKEN;if(!t||!o||!r)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:r}}async function hn({apiBase:n,authToken:e,body:t}){let o;try{o=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(i){throw new P("network",`begin fetch failed: ${i.message}`)}let r=null;try{r=await o.json()}catch{}if(!o.ok){if(o.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(o.status===429){let i=r?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=i,s}if(o.status===400&&r?.validationErrors){let i=new Error(`Sub-graph rejected input: ${r?.error||r?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=r.validationErrors,i.missing=r.missing,i}throw new P("begin-status",`begin returned ${o.status}`)}return r?.data||r}async function J({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||b.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){b.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function gn(n,e){let t=W(e,".ready"),o=W(e,"graph.mjs");if(Y(t)&&Y(o))return;an(e,{recursive:!0});let r=W(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),u=s(r,"wx");a(u),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(Y(t)&&Y(o))return;await new Promise(a=>setTimeout(a,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let f=gt("curl",["-fsSL",n],{stdio:["ignore","pipe","inherit"]}),l=gt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(l.stdin);let c,y,g=()=>{if(c!==void 0&&y!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(y!==0)return d(new Error(`tar exited ${y}`));u()}};f.on("close",m=>{c=m,g()}),l.on("close",m=>{y=m,g()}),f.on("error",d),l.on("error",d)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(r)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(r)}catch{}throw new P("bundle-extract-failed",s.message)}}async function mn(n){let e=W(n,"graph.mjs");if(!Y(e))throw new P("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(ln(e).href)}catch(r){throw new P("import-failed",`${r?.code||r?.name||"unknown"}: ${r.message}`)}let o=t.default||Object.values(t).find(r=>typeof r=="function"&&r.prototype?.buildGraph);if(!o)throw new P("entry-class-missing","no buildGraph() class export found");return o}async function _t(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=V(),o;try{o=fn()}catch(p){throw p}b.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let r=await hn({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:f,bundleReady:l,nodeConfigs:c}=r,y=dn();if(s&&s!==y)throw await J({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new P("runtime-mismatch",`${y} vs ${s}`);if(!l||!a)throw await J({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new P("no-bundle","workflow bundle not built yet");let g=ht(n);if(!g){let p=W(he,`${f}@${d||"0"}`);try{await gn(a,p);try{Sn()}catch{}}catch($){throw $.fallback&&await J({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{g=await mn(p),pt(n,g,{workflowUuid:f,version:d,runtimeTag:s,cacheDir:p})}catch($){throw ft(n,$),await J({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new P("import-failed",$.message)}}let m=Date.now(),v=r.env&&typeof r.env=="object"&&!Array.isArray(r.env)?r.env:null,I=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...I?{nodeConfigs:c}:{}},S,w;try{S=await pn(v,async()=>{let $=await(typeof g=="function"&&g.prototype?.buildGraph?new g:g).buildGraph();return lt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,h,{signal:e.signal}))}),w=S&&typeof S=="object"&&"state"in S?S.state:S}catch(p){throw await J({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-m}}),p}if(S&&typeof S=="object"&&S.stoppedExternally){await J({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"canceled",finalState:w,durationMs:Date.now()-m}});let p=new Error(`Sub-graph '${n}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await J({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"completed",finalState:w,durationMs:Date.now()-m}}),{finalState:w,executionId:i}}function yn(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),r;try{r=St(o)}catch{continue}if(r.isDirectory()){let i;try{i=wt(o)}catch{continue}for(let s of i)t.push(W(o,s))}else e+=r.size}return e}function Sn({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(he))return{evicted:0,freedBytes:0};let e=wt(he),t=[],o=0;for(let a of e){let u=W(he,a),d;try{d=St(u)}catch{continue}let f=d.isDirectory()?yn(u):d.size;o+=f,t.push({name:a,full:u,size:f,mtimeMs:d.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let r=Math.floor(n*.7),i=0,s=0;for(let a of t){if(o-i<=r)break;if(!Y(W(a.full,".lock")))try{cn(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(u){b.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return s>0&&b.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:o-i}}catch(e){return b.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var wn=2e3,_n=600*1e3,bn=new Set(["completed","failed","canceled","timeout"]);function In(){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 En(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function $n(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function vn(){return process.env.EXECUTION_ID||null}function bt(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 It(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=V();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=o)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{b.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:w}=await _t(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=bt(w,e.output);return b.info(`[sub-graph] '${n}' completed in-process`),p}catch(w){if(w instanceof P||w?.fallback)b.info(`[sub-graph] in-process fallback for '${n}': ${w.reason||"unknown"} \u2014 using HTTP`);else throw w}let r=In(),i=En(),s=$n(),a=vn(),u=`${r}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(n)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};b.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let f=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(d)});if(!f.ok){let w=null,p="";try{w=await f.json(),p=w?.error||w?.message||JSON.stringify(w)}catch{p=await f.text().catch(()=>"")}if(f.status===429){let k=w?.quotaInfo||{},M=new Error(`Sub-graph '${n}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=n,M.quotaInfo=k,M}if(f.status===400){let k=new Error(`Sub-graph '${n}' rejected input: ${p}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=n,k.validationErrors=w?.validationErrors||null,k.missing=w?.missing||null,k}let $=new Error(`Sub-graph '${n}' trigger rejected (${f.status}): ${p}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=f.status,$.subgraph=n,$}let l=await f.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return b.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:n};let y=Number.isFinite(e.timeoutMs)?e.timeoutMs:_n,g=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:wn,m=`${r}/executions/${encodeURIComponent(c)}`,v=Date.now()+y,I="accepted",h=0;for(;Date.now()<v;){await new Promise(k=>setTimeout(k,g)),h+=1;let w=await fetch(m,{headers:{Authorization:`Bearer ${s}`}});if(!w.ok){if(w.status>=500){b.warn(`[sub-graph] status poll for ${c} returned ${w.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${w.status}`)}let p=await w.json(),$=p?.data||p?.execution||p;if(I=$?.status||I,bn.has(I)){if(I!=="completed"){let _=new Error(`Sub-graph '${n}' (${c}) ended in status '${I}'`);throw _.subgraphJobId=c,_.subgraphStatus=I,_}let k=$?.finalState||$?.state||{},M=bt(k,e.output);return b.info(`[sub-graph] '${n}' (${c}) completed after ${h} polls`),M}}let S=new Error(`Sub-graph '${n}' (${c}) timed out after ${Math.round(y/1e3)}s (last status: ${I})`);throw S.subgraphJobId=c,S.subgraphStatus=I,S}import{existsSync as Et,readFileSync as Tn}from"node:fs";import{join as Ne,dirname as $t}from"node:path";var ge=class{static async loadContext(e,t,o={}){let r={},i=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=$t(Ne(t,e));for(let u of i){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let f=u.replace(/\.[^.]+$/,"").toLowerCase();r[f]=d}}}let s=o.discovery||{};for(let[a,u]of Object.entries(s))try{let d=Ne(t,u);Et(d)&&(r[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return r}static async findAndMergeContextFiles(e,t,o){let r=[],i=t;for(;i.startsWith(o);){let s=Ne(i,e);if(Et(s))try{r.unshift(await this.loadFile(s))}catch(u){console.warn(`[workflow] could not load ${e} from ${s}: ${u.message}`)}let a=$t(i);if(a===i)break;i=a}return r.length===0?null:r.every(s=>typeof s=="string")?r.join(`
35
35
 
36
36
  ---
37
37
 
38
- `):s.every(r=>typeof r=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=vn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),s=await import(o(e).href);return s.default||s}return t}};import{mkdirSync as Tt,existsSync as Ce,writeFileSync as $t,unlinkSync as Tn}from"node:fs";import{join as Z,resolve as kt}from"node:path";import{config as kn}from"dotenv";import{zodToJsonSchema as vt}from"zod-to-json-schema";import{z as ge}from"zod";import An from"handlebars";function xn({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 f=(new Error("session trace").stack||"").split(`
38
+ `):r.every(s=>typeof s=="object")?Object.assign({},...r):r[r.length-1]}static async loadFile(e){let t=Tn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),r=await import(o(e).href);return r.default||r}return t}};import{mkdirSync as kt,existsSync as Ce,writeFileSync as vt,unlinkSync as kn}from"node:fs";import{join as z,resolve as At}from"node:path";import{config as An}from"dotenv";import{zodToJsonSchema as Tt}from"zod-to-json-schema";import{z as me}from"zod";import xn from"handlebars";function On({traceFrom:n,sessionId:e,sessionPath:t,idSource:o,mkdirFresh:r}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${n} pid=${process.pid} ppid=${s} sessionId=${e} source=${o} mkdir=${r?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let f=(new Error("session trace").stack||"").split(`
39
39
  `).slice(2,14).join(`
40
40
  `);console.log(`[zibby:session] stack (${n}):
41
- ${f}`)}}function Pn(){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 On(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return kt(String(e).trim())}catch{return String(e).trim()}}function Nn(){Pn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Cn({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 Rn(n={}){let e=nt.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 Bn({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 d=kt(String(process.env.ZIBBY_SESSION_PATH));d&&(s=d,r="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,r="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,r="config.sessionId"):(a=Rn(e),r="generated")}i=i??Date.now();let f=e.paths?.output||de;s=Z(n,f,et,a)}let u=!Ce(s);return u&&Tt(s,{recursive:!0}),(u||r!=="initialState.sessionPath")&&xn({traceFrom:o,sessionId:a,sessionPath:s,idSource:r,mkdirFresh:u}),Cn({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var me=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 L)&&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 d=>{let f=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof r.input=="function"?l=r.input(f):r.input&&typeof r.input=="object"?l=r.input:l={},bt(r.workflow,{input:l,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(f):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:f?._signal,parentAgent:d?.agent})}},u=new L(a);return u.name=e,this.nodes.set(e,u),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let s=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof L?t:new L(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),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){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:o}={}){return 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}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 u=e[a],d=r;r=()=>u(t,d,s,i)}return r()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let y=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:y,data:{nodeType:y,label:l}});let g={};c._isCustomCode&&typeof c.execute=="function"&&(g.customCode=c.execute.toString());let m=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;m&&(g.description=m);let v=this.nodePrompts.get(l);if(v)g.prompt=v;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(g.prompt=p,g.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(g.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(g.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof ge?.toJSONSchema=="function")try{p=ge.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=vt(c.outputSchema,{target:"openApi3"})}catch{}g.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else g.outputSchema={schema:c.outputSchema};let I=(this.resolvedToolsMap||{})[l];I?.toolIds&&(g.tools=I.toolIds);let h=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;h&&h.length>0&&(g.skills=[...h]);let S=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;S&&S.length>0&&(g.plugins=S.map(p=>p&&typeof p=="object"?{...p}:p));let w=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;w&&w.length>0&&(g.stores=w.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(g).length>0&&(t[l]=g)}let o=[];for(let[l,c]of this.edges)if(typeof c=="string")o.push({source:l,target:c});else if(c.conditional){let y=this.conditionalCodeMap.get(l)||c.routes.toString(),g=this._inferConditionalTargets(c.routes,c.labels),m=c.labels||{},v=this.nodes.get(l),I=v?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!v,h=l;if(!I){let S=`${l}__branch`;e.push({id:S,type:"decision",data:{nodeType:"decision",label:S}}),o.push({source:l,target:S}),h=S}for(let S of g){let w={source:h,target:S,data:{conditionalCode:y}};m[S]&&(w.label=m[S]),o.push(w)}}let s=l=>{if(!l)return null;if(typeof ge?.toJSONSchema=="function")try{return ge.toJSONSchema(l)}catch{}try{return vt(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let i=0;for(let l of o)if(l.target==="END"){i+=1;let c=`END__${i}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:l,target:c})}let r=this._topoOrderNodes(e,o),a=this._runtimeSchema(),u=s(a||this.stateSchema),d=s(this.inputSchema),f=s(this.contextSchema);return{nodes:r,edges:o,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:f}}_topoOrderNodes(e,t){let o=new Map(e.map((l,c)=>[l.id,c])),s=new Map(e.map(l=>[l.id,l])),i=new Map(e.map(l=>[l.id,0])),r=new Map(e.map(l=>[l.id,[]]));for(let l of t)r.has(l.source)&&i.has(l.target)&&(r.get(l.source).push(l.target),i.set(l.target,i.get(l.target)+1));let a=new Set,u=new Set(o.keys()),d=[...u].filter(l=>i.get(l)===0),f=[];for(;f.length<e.length;){let l;if(d.length>0){if(d.sort((c,y)=>o.get(c)-o.get(y)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,y)=>o.get(c)-o.get(y))[0];a.add(l),u.delete(l),f.push(s.get(l));for(let c of r.get(l)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return f}_inferConditionalTargets(e,t){let o=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,r;for(;(r=i.exec(o))!==null;){let d=r[2]!==void 0?r[2]:r[3];d!==void 0&&d!==""&&s.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let u=new Set;for(let d of s)a.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,f;for(;(f=d.exec(o))!==null;)u.add(f[1])}return[...u]}_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 u=t?`${t}.${r}`:r;o.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!i.includes(r)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${u}[]`))}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[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(d=>d?.passed===!0).length,u=i.some(d=>d?.passed!==void 0);o.push(u?`${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");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();kn({path:Z(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let E=Z(r,".zibby.config.js");Ce(E)&&(a=(await import(E)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let E=a?.agent;E?.provider?u=E.provider:E?.gemini?u="gemini":E?.claude?u="claude":E?.cursor?u="cursor":E?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},f=this._runtimeSchema();if(f){let E=f.safeParse(t);if(!E.success){let N=E.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),N.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${N.join(", ")}`)}P.step("State validated against schema")}let l=On(),c=t.sessionPath||l;c||Nn();let{sessionPath:y,sessionTimestamp:g,sessionId:m}=Bn({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});P.step(`Session ${m}`);let v=await he.loadContext(t.specPath||"",r,d);Object.keys(v).length>0&&P.step(`Context loaded: ${Object.keys(v).join(", ")}`);let I=t.outputPath;!I&&t.specPath&&(e?.calculateOutputPath?I=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new ce({...t,config:a,agentType:u,outputPath:I,sessionPath:y,sessionTimestamp:g,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),S=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:w}=await Promise.resolve().then(()=>(pe(),rt)),p=a.skills&&typeof a.skills=="object"?a.skills:{},$=Object.values(p).filter(E=>E&&typeof E=="object"&&typeof E.id=="string"),k=E=>{for(let N of $)if(N.id===E)return N;return w(E)},M=new Set;for(let[,E]of this.nodes)for(let N of E.config?.skills||[])M.add(N);for(let E of M){let N=k(E);if(typeof N?.middleware=="function")try{let C=await N.middleware();typeof C=="function"&&S.set(E,C)}catch{}}let _=this.entryPoint,re=[],je=a?.recursionLimit??100,Nt=0;try{for(;_&&_!=="END";){if(++Nt>je)throw new Error(`Workflow exceeded recursion limit (${je}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let N=Z(y,tt);if(Ce(N)){try{Tn(N)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
42
- \u{1F6D1} External stop requested \u2014 ending workflow.`),P.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:re,stoppedExternally:!0};let C=this.nodes.get(_);if(!C)throw new Error(`Node '${_}' not found in graph`);let De=JSON.stringify({sessionPath:y,sessionTimestamp:g,currentNode:_,createdAt:new Date().toISOString(),config:h.get("config")}),Ct=Z(y,K);$t(Ct,De,"utf-8");let Le=h.get("config")?.paths?.output||de,Rt=Z(r,Le,K);Tt(Z(r,Le),{recursive:!0});try{$t(Rt,De,"utf-8")}catch{}let Ue=t.onPipelineProgress;if(typeof Ue=="function")try{Ue({cwd:r,sessionPath:y,sessionId:m,outputBase:h.get("config")?.paths?.output||de,currentNode:_})}catch{}let Bt=(this.resolvedToolsMap||{})[_]||null;h.set("_currentNodeTools",Bt);let Mt=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",Mt[_]||{}),P.nodeStart(_);let We=Date.now(),se=this.nodePrompts.get(_);if(!this._invokeAgent){let A=await Promise.resolve().then(()=>(ne(),te));this._invokeAgent=A.invokeAgent}let jt=this._invokeAgent,Se={},Dt=C.config?.skills||[];for(let A of Dt){let R=k(A);if(typeof R?.invokeAgentOptions=="function")try{let T=R.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:_});T&&typeof T=="object"&&(Se={...Se,...T})}catch(T){console.warn(`[graph] skill '${A}' invokeAgentOptions threw: ${T.message}`)}}let Fe=async(A,R,T={})=>{let B=jt(A,R,{...Se,...T,signal:s.signal});return B.catch(()=>{}),s.signal.aborted?B:Promise.race([B,new Promise((z,q)=>{let D=()=>{setTimeout(()=>{let V=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);V.name="AbortError",q(V)},i)};s.signal.addEventListener("abort",D,{once:!0})})])},Lt=async(A={},R={})=>{let T=R.prompt||"";if(se){let B=this._compiledPrompts.get(_);B||(B=An.compile(se,{noEscape:!0}),this._compiledPrompts.set(_,B));try{T=B(A)}catch(z){throw console.error(`\u274C Template rendering failed for node '${_}':`,z.message),new Error(`Template rendering failed: ${z.message}`,{cause:z})}}else if(!T)throw new Error(`No prompt template configured for node '${_}' and no prompt provided in options`);return Fe(T,{state:h.getAll(),images:R.images||[]},{model:R.model||h.get("model"),workspace:h.get("workspace"),schema:R.schema,...R,signal:s.signal})},Ge=h.getAll(),Ut=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let A of Ut)Object.prototype.hasOwnProperty.call(Ge,A)&&console.warn(`[workflow] node "${_}": state key "${A}" is shadowed by the engine context prop; read it via context.state.get('${A}')`);let He={...Ge,state:h,invokeAgent:Lt,_coreInvokeAgent:Fe,agent:e,nodeId:_,promptTemplate:se,getPromptTemplate:()=>se};try{let A=(C.config?.skills||[]).map(D=>S.get(D)).filter(Boolean),R=[...this.middleware,...A],T;R.length>0?T=await this._composeMiddleware(R,_,async()=>C.execute(He,h),h.getAll(),h):T=await C.execute(He,h);let B=Date.now()-We;if(re.push({node:_,success:T.success,duration:B,timestamp:new Date().toISOString()}),!T.success){if(s.signal.aborted)return P.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:re,stoppedExternally:!0};h.append("errors",{node:_,error:T.error});let D=C.config?.retries||0,V=`${_}_retries`,ie=h.getAll()[V]||0;if(ie<D){P.stepInfo(`Retrying (attempt ${ie+1}/${D})`),h.update({[V]:ie+1,[`${_}_raw`]:T.raw});continue}throw P.nodeFailed(_,T.error,{duration:B}),new Error(`Node '${_}' failed after ${ie} attempts: ${T.error}`)}h.update({[_]:T.output});let z=this._summarizeNodeOutput(_,T.output);P.nodeComplete(_,{duration:B,details:z});let q=this.edges.get(_);if(!q)_="END";else if(q.conditional){let D=q.routes(h.getAll());P.route(_,D),_=D}else _=q}catch(A){throw P.isInsideNode&&P.nodeFailed(_,A.message,{duration:Date.now()-We}),h.set("failed",!0),h.set("failedAt",_),A}}P.graphComplete();let E={success:!0,state:h.getAll(),executionLog:re};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 Re=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Re]||(globalThis[Re]=new Map);var Be=globalThis[Re];function Mn(n,e){Be.set(n,e)}function At(n){return Be.get(n)}function Me(n){return Be.has(n)}Mn("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(()=>(ne(),te))).invokeAgent);let s=e.extraPromptInstructions||"Execute the task based on the current state.",i=jn(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 jn(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 u=a.split(".")[0];if(r.has(u))continue;let d=a.split(".").reduce((c,y)=>c?.[y],e);if(d===void 0)continue;let f=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),l=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${l}
43
- ${f}`),a.includes(".")||r.add(u)}return i.length===0?n:`${n}
41
+ ${f}`)}}function Pn(){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 Nn(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return At(String(e).trim())}catch{return String(e).trim()}}function Cn(){Pn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Rn({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 Bn(n={}){let e=nt.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,r=n.paths?.sessionPrefix;return r?`${r}_${o}`:o}function Mn({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let r=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!r&&process.env.ZIBBY_SESSION_PATH)try{let d=At(String(process.env.ZIBBY_SESSION_PATH));d&&(r=d,s="ZIBBY_SESSION_PATH")}catch{}let a;if(r)a=String(r).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,s="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,s="config.sessionId"):(a=Bn(e),s="generated")}i=i??Date.now();let f=e.paths?.output||pe;r=z(n,f,et,a)}let u=!Ce(r);return u&&kt(r,{recursive:!0}),(u||s!=="initialState.sessionPath")&&On({traceFrom:o,sessionId:a,sessionPath:r,idSource:s,mkdirFresh:u}),Rn({sessionPath:r,sessionId:a}),{sessionPath:r,sessionId:a,sessionTimestamp:i}}var ye=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 L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async d=>{let f=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof s.input=="function"?l=s.input(f):s.input&&typeof s.input=="object"?l=s.input:l={},It(s.workflow,{input:l,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(f):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:f?._signal,parentAgent:d?.agent})}},u=new L(a);return u.name=e,this.nodes.set(e,u),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let r=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof L?t:new L(r?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),o.prompt?this.nodePrompts.set(e,o.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:o}={}){return 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}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,r,i){let s=o;for(let a=e.length-1;a>=0;a--){let u=e[a],d=s;s=()=>u(t,d,r,i)}return s()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let y=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:y,data:{nodeType:y,label:l}});let g={};c._isCustomCode&&typeof c.execute=="function"&&(g.customCode=c.execute.toString());let m=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;m&&(g.description=m);let v=this.nodePrompts.get(l);if(v)g.prompt=v;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(g.prompt=p,g.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(g.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(g.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof me?.toJSONSchema=="function")try{p=me.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Tt(c.outputSchema,{target:"openApi3"})}catch{}g.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else g.outputSchema={schema:c.outputSchema};let I=(this.resolvedToolsMap||{})[l];I?.toolIds&&(g.tools=I.toolIds);let h=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;h&&h.length>0&&(g.skills=[...h]);let S=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;S&&S.length>0&&(g.plugins=S.map(p=>p&&typeof p=="object"?{...p}:p));let w=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;w&&w.length>0&&(g.stores=w.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(g).length>0&&(t[l]=g)}let o=[];for(let[l,c]of this.edges)if(typeof c=="string")o.push({source:l,target:c});else if(c.conditional){let y=this.conditionalCodeMap.get(l)||c.routes.toString(),g=this._inferConditionalTargets(c.routes,c.labels),m=c.labels||{},v=this.nodes.get(l),I=v?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!v,h=l;if(!I){let S=`${l}__branch`;e.push({id:S,type:"decision",data:{nodeType:"decision",label:S}}),o.push({source:l,target:S}),h=S}for(let S of g){let w={source:h,target:S,data:{conditionalCode:y}};m[S]&&(w.label=m[S]),o.push(w)}}let r=l=>{if(!l)return null;if(typeof me?.toJSONSchema=="function")try{return me.toJSONSchema(l)}catch{}try{return Tt(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let i=0;for(let l of o)if(l.target==="END"){i+=1;let c=`END__${i}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:l,target:c})}let s=this._topoOrderNodes(e,o),a=this._runtimeSchema(),u=r(a||this.stateSchema),d=r(this.inputSchema),f=r(this.contextSchema);return{nodes:s,edges:o,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:f}}_topoOrderNodes(e,t){let o=new Map(e.map((l,c)=>[l.id,c])),r=new Map(e.map(l=>[l.id,l])),i=new Map(e.map(l=>[l.id,0])),s=new Map(e.map(l=>[l.id,[]]));for(let l of t)s.has(l.source)&&i.has(l.target)&&(s.get(l.source).push(l.target),i.set(l.target,i.get(l.target)+1));let a=new Set,u=new Set(o.keys()),d=[...u].filter(l=>i.get(l)===0),f=[];for(;f.length<e.length;){let l;if(d.length>0){if(d.sort((c,y)=>o.get(c)-o.get(y)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,y)=>o.get(c)-o.get(y))[0];a.add(l),u.delete(l),f.push(r.get(l));for(let c of s.get(l)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return f}_inferConditionalTargets(e,t){let o=e.toString(),r=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(o))!==null;){let d=s[2]!==void 0?s[2]:s[3];d!==void 0&&d!==""&&r.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let u=new Set;for(let d of r)a.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,f;for(;(f=d.exec(o))!==null;)u.add(f[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let r=e.$ref.replace("#/definitions/","");o=e.definitions[r]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],r=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(r)){let u=t?`${t}.${s}`:s;o.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${u}[]`))}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[r,i]of Object.entries(t))if(!(r==="success"||r==="raw"||r==="nextNode")){if(typeof i=="string"&&i.length<=80)o.push(`${r}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(d=>d?.passed===!0).length,u=i.some(d=>d?.passed!==void 0);o.push(u?`${r}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${r}: ${s} items`)}if(o.length>=4)break}return o}async run(e,t={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let r=new AbortController;o.signal&&(o.signal.aborted?r.abort():o.signal.addEventListener("abort",()=>r.abort(),{once:!0}));let i=o.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();An({path:z(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let E=z(s,".zibby.config.js");Ce(E)&&(a=(await import(E)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let E=a?.agent;E?.provider?u=E.provider:E?.gemini?u="gemini":E?.claude?u="claude":E?.cursor?u="cursor":E?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},f=this._runtimeSchema();if(f){let E=f.safeParse(t);if(!E.success){let N=E.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),N.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${N.join(", ")}`)}O.step("State validated against schema")}let l=Nn(),c=t.sessionPath||l;c||Cn();let{sessionPath:y,sessionTimestamp:g,sessionId:m}=Mn({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${m}`);let v=await ge.loadContext(t.specPath||"",s,d);Object.keys(v).length>0&&O.step(`Context loaded: ${Object.keys(v).join(", ")}`);let I=t.outputPath;!I&&t.specPath&&(e?.calculateOutputPath?I=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new le({...t,config:a,agentType:u,outputPath:I,sessionPath:y,sessionTimestamp:g,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:r.signal}),S=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:w}=await Promise.resolve().then(()=>(fe(),rt)),p=a.skills&&typeof a.skills=="object"?a.skills:{},$=Object.values(p).filter(E=>E&&typeof E=="object"&&typeof E.id=="string"),k=E=>{for(let N of $)if(N.id===E)return N;return w(E)},M=new Set;for(let[,E]of this.nodes)for(let N of E.config?.skills||[])M.add(N);for(let E of M){let N=k(E);if(typeof N?.middleware=="function")try{let C=await N.middleware();typeof C=="function"&&S.set(E,C)}catch{}}let _=this.entryPoint,se=[],je=a?.recursionLimit??100,Ct=0;try{for(;_&&_!=="END";){if(++Ct>je)throw new Error(`Workflow exceeded recursion limit (${je}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let N=z(y,tt);if(Ce(N)){try{kn(N)}catch{}r.abort()}if(r.signal.aborted)return console.warn(`
42
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:se,stoppedExternally:!0};let C=this.nodes.get(_);if(!C)throw new Error(`Node '${_}' not found in graph`);let De=JSON.stringify({sessionPath:y,sessionTimestamp:g,currentNode:_,createdAt:new Date().toISOString(),config:h.get("config")}),Rt=z(y,K);vt(Rt,De,"utf-8");let Le=h.get("config")?.paths?.output||pe,Bt=z(s,Le,K);kt(z(s,Le),{recursive:!0});try{vt(Bt,De,"utf-8")}catch{}let We=t.onPipelineProgress;if(typeof We=="function")try{We({cwd:s,sessionPath:y,sessionId:m,outputBase:h.get("config")?.paths?.output||pe,currentNode:_})}catch{}let Mt=(this.resolvedToolsMap||{})[_]||null;h.set("_currentNodeTools",Mt);let jt=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",jt[_]||{}),O.nodeStart(_);let Ue=Date.now(),ie=this.nodePrompts.get(_);if(!this._invokeAgent){let A=await Promise.resolve().then(()=>(oe(),ne));this._invokeAgent=A.invokeAgent}let Dt=this._invokeAgent,we={},Lt=C.config?.skills||[];for(let A of Lt){let R=k(A);if(typeof R?.invokeAgentOptions=="function")try{let T=R.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:_});T&&typeof T=="object"&&(we={...we,...T})}catch(T){console.warn(`[graph] skill '${A}' invokeAgentOptions threw: ${T.message}`)}}let Fe=async(A,R,T={})=>{let B=Dt(A,R,{...we,...T,signal:r.signal});return B.catch(()=>{}),r.signal.aborted?B:Promise.race([B,new Promise((Z,q)=>{let D=()=>{setTimeout(()=>{let X=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);X.name="AbortError",q(X)},i)};r.signal.addEventListener("abort",D,{once:!0})})])},Wt=async(A={},R={})=>{let T=R.prompt||"";if(ie){let B=this._compiledPrompts.get(_);B||(B=xn.compile(ie,{noEscape:!0}),this._compiledPrompts.set(_,B));try{T=B(A)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${_}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}}else if(!T)throw new Error(`No prompt template configured for node '${_}' and no prompt provided in options`);return Fe(T,{state:h.getAll(),images:R.images||[]},{model:R.model||h.get("model"),workspace:h.get("workspace"),schema:R.schema,...R,signal:r.signal})},Ge=h.getAll(),Ut=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let A of Ut)Object.prototype.hasOwnProperty.call(Ge,A)&&console.warn(`[workflow] node "${_}": state key "${A}" is shadowed by the engine context prop; read it via context.state.get('${A}')`);let He={...Ge,state:h,invokeAgent:Wt,_coreInvokeAgent:Fe,agent:e,nodeId:_,promptTemplate:ie,getPromptTemplate:()=>ie};try{let A=(C.config?.skills||[]).map(D=>S.get(D)).filter(Boolean),R=[...this.middleware,...A],T;T=await ut(e,r.signal,async()=>R.length>0?this._composeMiddleware(R,_,async()=>C.execute(He,h),h.getAll(),h):C.execute(He,h));let B=Date.now()-Ue;if(se.push({node:_,success:T.success,duration:B,timestamp:new Date().toISOString()}),!T.success){if(r.signal.aborted)return O.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:se,stoppedExternally:!0};h.append("errors",{node:_,error:T.error});let D=C.config?.retries||0,X=`${_}_retries`,ae=h.getAll()[X]||0;if(ae<D){O.stepInfo(`Retrying (attempt ${ae+1}/${D})`),h.update({[X]:ae+1,[`${_}_raw`]:T.raw});continue}throw O.nodeFailed(_,T.error,{duration:B}),new Error(`Node '${_}' failed after ${ae} attempts: ${T.error}`)}h.update({[_]:T.output});let Z=this._summarizeNodeOutput(_,T.output);O.nodeComplete(_,{duration:B,details:Z});let q=this.edges.get(_);if(!q)_="END";else if(q.conditional){let D=q.routes(h.getAll());O.route(_,D),_=D}else _=q}catch(A){throw O.isInsideNode&&O.nodeFailed(_,A.message,{duration:Date.now()-Ue}),h.set("failed",!0),h.set("failedAt",_),A}}O.graphComplete();let E={success:!0,state:h.getAll(),executionLog:se};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 Re=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Re]||(globalThis[Re]=new Map);var Be=globalThis[Re];function jn(n,e){Be.set(n,e)}function xt(n){return Be.get(n)}function Me(n){return Be.has(n)}jn("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(()=>(oe(),ne))).invokeAgent);let r=e.extraPromptInstructions||"Execute the task based on the current state.",i=Dn(r,t),s=await o(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:s,nodeId:n},raw:typeof s=="string"?s:s.raw}}})});function Dn(n,e){let t=/@([\w.]+)/g,o=new Set,r;for(;(r=t.exec(n))!==null;)o.add(r[1]);if(o.size===0)return n;let i=[],s=new Set;for(let a of o){let u=a.split(".")[0];if(s.has(u))continue;let d=a.split(".").reduce((c,y)=>c?.[y],e);if(d===void 0)continue;let f=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),l=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${l}
43
+ ${f}`),a.includes(".")||s.add(u)}return i.length===0?n:`${n}
44
44
 
45
45
  ---
46
46
  # Referenced Context
47
47
 
48
48
  ${i.join(`
49
49
 
50
- `)}`}pe();W();var Dn={};function Pt(n,e){if(Array.isArray(e))return xt(e);let t=Dn[n];return!t||t.length===0?null:xt(t)}function xt(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},o=[];for(let s of n){let i=ee(s);if(!i){b.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 u=process.env[a];u&&(r[a]=u)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:r,toolPrefix:s}}}return o.length===0?null:{toolIds:o,claudeTools:e,mcpServers:t}}W();function Zo(n,e={}){let{nodes:t,edges:o,nodeConfigs:s={}}=n;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(o))throw new j("Graph edges must be an array");let i=new me(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let r=new Set,a=new Map,u={};for(let c of t){let y=ye(c);a.set(c.id,{...c,resolvedType:y}),y==="decision"&&r.add(c.id)}for(let[c,y]of a){if(r.has(c))continue;let g=y.resolvedType,m=s[c]||{},v=Pt(g,m.tools);v&&(u[c]=v);let I={};m.prompt&&(I.prompt=m.prompt);let h=Me(g);if(b.debug(`[workflow] compiler: node "${c}" type="${g}" registered=${h}`),m.customCode&&!h)i.addNode(c,Ot(c,m.customCode,m),I),i.setNodeType(c,g);else if(h){let S=At(g);S.factory?i.addNode(c,S.create(c,{...m,resolvedTools:v}),I):i.addNode(c,S,I),i.setNodeType(c,g)}else if(m.executeCode)i.addNode(c,Ot(c,m.executeCode,m),I),i.setNodeType(c,g);else throw new j(`Unknown node type "${g}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=u;let d=new Set;for(let c of o)r.has(c.target)||d.add(c.target);let f=t.find(c=>!r.has(c.id)&&!d.has(c.id));if(!f)throw new j("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(f.id);let l=Ln(o,"source");for(let c of o)if(!r.has(c.source))if(r.has(c.target)){let y=c.target,g=l.get(y)||[];if(g.length===0)throw new j(`Decision node "${y}" has no outgoing edges`);let m=Un(y,g,r);i.addConditionalEdges(c.source,m)}else i.addEdge(c.source,c.target);return i}function zo(n){let e=[];if(!n||typeof n!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(n.nodes)||n.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(n.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=n.nodeConfigs||{};for(let a of n.nodes){let u=ye(a);if(u==="decision"||Me(u))continue;let d=t[a.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${u}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let o=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)o.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),o.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let s=new Set(n.nodes.filter(a=>ye(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 u=n.edges.filter(f=>f.source===a);u.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),u.some(f=>f.data?.conditionalCode||f.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function qo(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>ye(e)!=="decision").map(e=>e.id)}function ye(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function Ln(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 Un(n,e,t){let o=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!o)throw new j(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let s=o.data?.conditionalCode||o.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),r;try{let u=new Function(`return (${s})`)();r=d=>{let f=u(d);return i.has(f)||b.warn(`[workflow] conditional route from "${n}" returned "${f}" which is not in valid targets: ${[...i].join(", ")}`),f}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return r}function Ot(n,e,t={}){let o;try{o=new Function("invokeAgent","require","console",`return (${e})`)}catch(r){throw new j(`Failed to compile customCode for node "${n}": ${r.message}`)}let s=o(async(...r)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(ne(),te));return a(...r)},typeof we<"u"?we: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 j=class extends Error{constructor(e){super(e),this.name="CompilationError"}};export{j as CompilationError,Zo as compileGraph,qo as extractSteps,zo as validateGraphConfig};
50
+ `)}`}fe();U();var Ln={};function Pt(n,e){if(Array.isArray(e))return Ot(e);let t=Ln[n];return!t||t.length===0?null:Ot(t)}function Ot(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},o=[];for(let r of n){let i=te(r);if(!i){b.warn(`[workflow] unknown skill "${r}" \u2014 skipping`);continue}o.push(r);for(let s of i.tools||[])e.push({name:s.name,description:s.description,input_schema:s.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let s=i.resolve();s&&(t[i.serverName]={...s,toolPrefix:r})}else{let s={};for(let a of i.envKeys||[]){let u=process.env[a];u&&(s[a]=u)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:s,toolPrefix:r}}}return o.length===0?null:{toolIds:o,claudeTools:e,mcpServers:t}}U();function qo(n,e={}){let{nodes:t,edges:o,nodeConfigs:r={}}=n;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(o))throw new j("Graph edges must be an array");let i=new ye(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let s=new Set,a=new Map,u={};for(let c of t){let y=Se(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,m=r[c]||{},v=Pt(g,m.tools);v&&(u[c]=v);let I={};m.prompt&&(I.prompt=m.prompt);let h=Me(g);if(b.debug(`[workflow] compiler: node "${c}" type="${g}" registered=${h}`),m.customCode&&!h)i.addNode(c,Nt(c,m.customCode,m),I),i.setNodeType(c,g);else if(h){let S=xt(g);S.factory?i.addNode(c,S.create(c,{...m,resolvedTools:v}),I):i.addNode(c,S,I),i.setNodeType(c,g)}else if(m.executeCode)i.addNode(c,Nt(c,m.executeCode,m),I),i.setNodeType(c,g);else throw new j(`Unknown node type "${g}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=u;let d=new Set;for(let c of o)s.has(c.target)||d.add(c.target);let f=t.find(c=>!s.has(c.id)&&!d.has(c.id));if(!f)throw new j("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(f.id);let l=Wn(o,"source");for(let c of o)if(!s.has(c.source))if(s.has(c.target)){let y=c.target,g=l.get(y)||[];if(g.length===0)throw new j(`Decision node "${y}" has no outgoing edges`);let m=Un(y,g,s);i.addConditionalEdges(c.source,m)}else i.addEdge(c.source,c.target);return i}function Ko(n){let e=[];if(!n||typeof n!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(n.nodes)||n.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(n.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=n.nodeConfigs||{};for(let a of n.nodes){let u=Se(a);if(u==="decision"||Me(u))continue;let d=t[a.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${u}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let o=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)o.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),o.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let r=new Set(n.nodes.filter(a=>Se(a)==="decision").map(a=>a.id)),i=new Set;for(let a of n.edges)r.has(a.target)||i.add(a.target);let s=n.nodes.filter(a=>!r.has(a.id)&&!i.has(a.id));s.length===0?e.push("No entry point found (every node has incoming edges)"):s.length>1&&e.push(`Multiple entry points found: ${s.map(a=>a.id).join(", ")}`);for(let a of r){let u=n.edges.filter(f=>f.source===a);u.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),u.some(f=>f.data?.conditionalCode||f.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Vo(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>Se(e)!=="decision").map(e=>e.id)}function Se(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function Wn(n,e){let t=new Map;for(let o of n){let r=o[e];t.has(r)||t.set(r,[]),t.get(r).push(o)}return t}function Un(n,e,t){let o=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!o)throw new j(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let r=o.data?.conditionalCode||o.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),s;try{let u=new Function(`return (${r})`)();s=d=>{let f=u(d);return i.has(f)||b.warn(`[workflow] conditional route from "${n}" returned "${f}" which is not in valid targets: ${[...i].join(", ")}`),f}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return s}function Nt(n,e,t={}){let o;try{o=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new j(`Failed to compile customCode for node "${n}": ${s.message}`)}let r=o(async(...s)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(oe(),ne));return a(...s)},typeof _e<"u"?_e:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:n,_isCustomCode:!0,outputSchema:i,execute:async s=>{try{let a=await r(s);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var j=class extends Error{constructor(e){super(e),this.name="CompilationError"}};export{j as CompilationError,qo as compileGraph,Vo as extractSteps,Ko as validateGraphConfig};