@zibby/agent-workflow 0.1.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/graph.js CHANGED
@@ -1,37 +1,37 @@
1
- var Zt=Object.defineProperty;var j=(n,t)=>()=>(n&&(t=n(n=0)),t);var mt=(n,t)=>{for(var e in t)Zt(n,e,{get:t[e],enumerable:!0})};var gt,Jt,Z,_,V=j(()=>{gt=()=>{},Jt={debug:gt,info:gt,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},Z={impl:Jt},_={debug:(...n)=>Z.impl.debug?.(...n),info:(...n)=>Z.impl.info?.(...n),warn:(...n)=>Z.impl.warn?.(...n),error:(...n)=>Z.impl.error?.(...n)}});var bt=j(()=>{});var vt={};mt(vt,{clearSkills:()=>Qt,getAllSkills:()=>qt,getSkill:()=>Q,hasSkill:()=>zt,listSkillIds:()=>Xt,registerSkill:()=>Vt});function Vt(n){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");R.set(n.id,Object.freeze({...n}))}function Q(n){return R.get(n)||null}function zt(n){return R.has(n)}function qt(){return new Map(R)}function Xt(){return Array.from(R.keys())}function Qt(){R.clear()}var R,tt=j(()=>{R=new Map});var ot={};mt(ot,{getAgentStrategy:()=>Tt,invokeAgent:()=>oe,listStrategies:()=>ee,registerStrategy:()=>te});function te(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=x.findIndex(e=>e.getName()===n.getName());t>=0?x[t]=n:x.push(n)}function ee(){return x.map(n=>n.getName())}function Tt(n={}){let{state:t={},preferredAgent:e=null}=n,o=e||t.agentType||process.env.AGENT_TYPE;if(!o){let r=x.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${r}`)}_.debug(`[workflow] agent selection: requested=${o}`);let s=x.find(r=>r.getName()===o);if(!s){let r=x.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${r}`)}if(!s.canHandle(n))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return _.debug(`[workflow] using agent: ${s.getName()}`),s}async function oe(n,t={},e={}){let o=Tt(t),s=t.state?.config||e.config||{},r=s.models||{},i=e.nodeName&&r[e.nodeName]||null,a=r.default||null,c=s.agent?.[o.name]?.model||null,u=i||a||c||e.model||null,h={...e,model:u,workspace:t.state?.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],config:s},l=n,S=h.skills||[];if(S.length>0&&!e.skipPromptFragments){let f=S.map(b=>{let v=Q(b)?.promptFragment;return typeof v=="function"?v():v}).filter(Boolean);f.length>0&&(l+=`
1
+ var zt=Object.defineProperty;var G=(i,t)=>()=>(i&&(t=i(i=0)),t);var yt=(i,t)=>{for(var e in t)zt(i,e,{get:t[e],enumerable:!0})};var Et,Xt,K,_,Q=G(()=>{Et=()=>{},Xt={debug:Et,info:Et,warn:(...i)=>console.warn("[workflow]",...i),error:(...i)=>console.error("[workflow]",...i)},K={impl:Xt},_={debug:(...i)=>K.impl.debug?.(...i),info:(...i)=>K.impl.info?.(...i),warn:(...i)=>K.impl.warn?.(...i),error:(...i)=>K.impl.error?.(...i)}});var Pt=G(()=>{});var Ct={};yt(Ct,{clearSkills:()=>ne,getAllSkills:()=>se,getSkill:()=>rt,hasSkill:()=>oe,listSkillIds:()=>re,registerSkill:()=>ee});function ee(i){if(!i||typeof i.id!="string")throw new Error("Skill definition must include a string id");D.set(i.id,Object.freeze({...i}))}function rt(i){return D.get(i)||null}function oe(i){return D.has(i)}function se(){return new Map(D)}function re(){return Array.from(D.keys())}function ne(){D.clear()}var st,D,nt=G(()=>{st=Symbol.for("@zibby/agent-workflow.skills");globalThis[st]||(globalThis[st]=new Map);D=globalThis[st]});var at={};yt(at,{getAgentStrategy:()=>Rt,invokeAgent:()=>ce,listStrategies:()=>ae,registerStrategy:()=>ie});function ie(i){if(!i||typeof i.getName!="function"||typeof i.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=C.findIndex(e=>e.getName()===i.getName());t>=0?C[t]=i:C.push(i)}function ae(){return C.map(i=>i.getName())}function Rt(i={}){let{state:t={},preferredAgent:e=null}=i,s=e||t.agentType||process.env.AGENT_TYPE;if(!s){let r=C.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${r}`)}_.debug(`[workflow] agent selection: requested=${s}`);let o=C.find(r=>r.getName()===s);if(!o){let r=C.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${s}'. Available: ${r}`)}if(!o.canHandle(i))throw new Error(`Agent '${s}' is not available in this environment. Check credentials/environment.`);return _.debug(`[workflow] using agent: ${o.getName()}`),o}async function ce(i,t={},e={}){let s=Rt(t),o=t.state?.config||e.config||{},r=o.models||{},n=e.nodeName&&r[e.nodeName]||null,a=r.default||null,c=o.agent?.[s.name]?.model||null,d=n||a||c||e.model||null,h={...e,model:d,workspace:t.state?.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],config:o},l=i,m=h.skills||[];if(m.length>0&&!e.skipPromptFragments){let x=m.map(P=>{let T=rt(P)?.promptFragment;return typeof T=="function"?T():T}).filter(Boolean);x.length>0&&(l+=`
2
2
 
3
- ${f.join(`
3
+ ${x.join(`
4
4
 
5
- `)}`)}let I=t.state?._currentNodeConfig?.extraPromptInstructions?.trim();return I&&(l+=`
5
+ `)}`)}let E=t.state?._currentNodeConfig?.extraPromptInstructions?.trim();return E&&(l+=`
6
6
 
7
7
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
8
8
  PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
9
9
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
10
10
 
11
- ${I}
12
- `),_.debug(`[workflow] prompt length: ${l.length} chars`),o.invoke(l,h)}var et,x,st=j(()=>{bt();V();tt();et=Symbol.for("@zibby/agent-workflow.strategies");globalThis[et]||(globalThis[et]=[]);x=globalThis[et]});var Gt=new Set(["__proto__","constructor","prototype"]);function K(n){if(Gt.has(n))throw new Error(`Invalid state key: "${n}"`)}var U=class{constructor(t={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...t}),this._history=[]}get(t){return this._state[t]}set(t,e){K(t),this._history.push({...this._state}),this._state[t]=e}update(t){let e=Object.getOwnPropertyNames(t);for(let o of e)K(o);this._history.push({...this._state});for(let o of e)this._state[o]=t[o]}append(t,e){K(t),this._history.push({...this._state}),Array.isArray(this._state[t])||(this._state[t]=[]),this._state[t].push(e)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};var Y=class{constructor(t){this.schema=t}parse(t){let e=t.match(/```json\s*([\s\S]*?)\s*```/);if(e)return this.validate(JSON.parse(e[1]));let o=t.match(/\{[\s\S]*\}/);return o?this.validate(JSON.parse(o[0])):this.validate({result:t.trim()})}validate(t){let e=[];for(let[o,s]of Object.entries(this.schema)){if(s.required&&!(o in t)&&e.push(`Missing required field: ${o}`),o in t&&s.type){let r=typeof t[o];r!==s.type&&e.push(`Field '${o}' expected ${s.type}, got ${r}`)}if(s.validate&&o in t){let r=s.validate(t[o]);r&&e.push(`Field '${o}': ${r}`)}}if(e.length>0)throw new Error(`Output validation failed:
11
+ ${E}
12
+ `),_.debug(`[workflow] prompt length: ${l.length} chars`),s.invoke(l,h)}var it,C,ct=G(()=>{Pt();Q();nt();it=Symbol.for("@zibby/agent-workflow.strategies");globalThis[it]||(globalThis[it]=[]);C=globalThis[it]});var qt=new Set(["__proto__","constructor","prototype"]);function X(i){if(qt.has(i))throw new Error(`Invalid state key: "${i}"`)}var H=class{constructor(t={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...t}),this._history=[]}get(t){return this._state[t]}set(t,e){X(t),this._history.push({...this._state}),this._state[t]=e}update(t){let e=Object.getOwnPropertyNames(t);for(let s of e)X(s);this._history.push({...this._state});for(let s of e)this._state[s]=t[s]}append(t,e){X(t),this._history.push({...this._state}),Array.isArray(this._state[t])||(this._state[t]=[]),this._state[t].push(e)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};var J=class{constructor(t){this.schema=t}parse(t){let e=t.match(/```json\s*([\s\S]*?)\s*```/);if(e)return this.validate(JSON.parse(e[1]));let s=[t.match(/\{[\s\S]*?\}/),t.match(/\{[\s\S]*\}/)].filter(Boolean).map(o=>o[0]);for(let o of s)try{return this.validate(JSON.parse(o))}catch(r){if(!(r instanceof SyntaxError))throw r}return this.validate({result:t.trim()})}validate(t){let e=[];for(let[s,o]of Object.entries(this.schema)){if(o.required&&!(s in t)&&e.push(`Missing required field: ${s}`),s in t&&o.type){let r=typeof t[s];r!==o.type&&e.push(`Field '${s}' expected ${o.type}, got ${r}`)}if(o.validate&&s in t){let r=o.validate(t[s]);r&&e.push(`Field '${s}': ${r}`)}}if(e.length>0)throw new Error(`Output validation failed:
13
13
  ${e.join(`
14
- `)}`);return t}};V();import{writeFileSync as rt,readFileSync as xt,existsSync as At,mkdirSync as se}from"node:fs";import{join as nt,dirname as re}from"node:path";import g from"chalk";var Ht="__WORKFLOW_GRAPH_LOG__",M=g.gray("\u2502"),Kt=g.gray("\u250C"),St=g.gray("\u2514"),z=g.green("\u25C6"),wt=g.hex("#c084fc")("\u25C6"),_t=g.hex("#2dd4bf")("\u25C6"),q=g.red("\u25C6"),yt=`${M} `,Et=2;function It(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function $t(n,t){return(e,o,s)=>{if(typeof e!="string")return n(e,o,s);let r=process.stdout.columns||120,i="";for(let a=0;a<e.length;a++){let c=e[a];t.lineStart&&(i+=yt,t.col=Et,t.lineStart=!1),c===`
15
- `?(i+=c,t.lineStart=!0,t.col=0,t.inEsc=!1):c==="\x1B"?(t.inEsc=!0,i+=c):t.inEsc?(i+=c,(c>="A"&&c<="Z"||c>="a"&&c<="z")&&(t.inEsc=!1)):(t.col++,i+=c,t.col>=r&&(i+=`
16
- ${yt}`,t.col=Et))}return n(i,o,s)}}var X=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let t=String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase(),e=String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1";this._emitWorkflowGraphMarkers=e||t==="studio"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=$t(this._origStdoutWrite,t),process.stderr.write=$t(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
14
+ `)}`);return t}};Q();import{writeFileSync as lt,readFileSync as Wt,existsSync as Bt,mkdirSync as le}from"node:fs";import{join as ut,dirname as ue}from"node:path";import g from"chalk";var Qt="__WORKFLOW_GRAPH_LOG__",Y=g.gray("\u2502"),te=g.gray("\u250C"),It=g.gray("\u2514"),tt=g.green("\u25C6"),$t=g.hex("#c084fc")("\u25C6"),bt=g.hex("#2dd4bf")("\u25C6"),et=g.red("\u25C6"),Nt=`${Y} `,Ot=2;function kt(i){return i<1e3?`${i}ms`:`${(i/1e3).toFixed(1)}s`}function vt(i,t){return(e,s,o)=>{if(typeof e!="string")return i(e,s,o);let r=process.stdout.columns||120,n="";for(let a=0;a<e.length;a++){let c=e[a];t.lineStart&&(n+=Nt,t.col=Ot,t.lineStart=!1),c===`
15
+ `?(n+=c,t.lineStart=!0,t.col=0,t.inEsc=!1):c==="\x1B"?(t.inEsc=!0,n+=c):t.inEsc?(n+=c,(c>="A"&&c<="Z"||c>="a"&&c<="z")&&(t.inEsc=!1)):(t.col++,n+=c,t.col>=r&&(n+=`
16
+ ${Nt}`,t.col=Ot))}return i(n,s,o)}}var ot=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 t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=vt(this._origStdoutWrite,t),process.stderr.write=vt(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
17
17
  `),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
18
18
  `),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
19
- `)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${Ht}${JSON.stringify(t)}
19
+ `)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${Qt}${JSON.stringify(t)}
20
20
  `;this._origStdoutWrite?this._origStdoutWrite(e):process.stdout.write(e)}_writeDot(t,e){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
21
21
  `),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${t} ${e}
22
22
  `)):process.stdout.write.bind(process.stdout)(`${t} ${e}
23
- `)}step(t){this._origStdoutWrite?this._writeDot(z,t):process.stdout.write.bind(process.stdout)(`${M} ${z} ${t}
24
- `)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(wt,t):process.stdout.write.bind(process.stdout)(`${M} ${wt} ${t}
25
- `)}stepMemory(t){let e=g.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(_t,e):process.stdout.write.bind(process.stdout)(`${M} ${_t} ${e}
26
- `)}stepFail(t){this._origStdoutWrite?this._writeDot(q,g.red(t)):process.stdout.write.bind(process.stdout)(`${M} ${q} ${g.red(t)}
27
- `)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Kt} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:s}=e;if(s)for(let i of s)this._rawWrite(`${z} ${i}`);let r=o?g.dim(` ${It(o)}`):"";this._rawWrite(`${St} ${g.green("done")}${r}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:s}=o,r=s?g.dim(` ${It(s)}`):"";this._rawWrite(`${q} ${g.red(e)}`),this._rawWrite(`${St} ${g.red("failed")}${r}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(g.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){this._rawWrite(g.green.bold("\u2713 Workflow completed"))}},y=new X;var G=".zibby/output",Ot="sessions",C=".session-info.json",Nt=".zibby-studio-stop";var kt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var W=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode)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=t.outputSchema&&!this.isZodSchema?new Y(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){let o=()=>e&&typeof e.getAll=="function"?e.getAll():t,s=l=>e&&typeof e.get=="function"?e.get(l):t?.[l];if(typeof this.customExecute=="function"){_.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(t);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(_.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 _.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&_.error(`Schema errors: ${JSON.stringify(l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let r=typeof this.prompt=="function"?this.prompt(o()):this.prompt,i=s("_skillHints");i&&(r=`${i}
23
+ `)}step(t){this._origStdoutWrite?this._writeDot(tt,t):process.stdout.write.bind(process.stdout)(`${Y} ${tt} ${t}
24
+ `)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot($t,t):process.stdout.write.bind(process.stdout)(`${Y} ${$t} ${t}
25
+ `)}stepMemory(t){let e=g.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(bt,e):process.stdout.write.bind(process.stdout)(`${Y} ${bt} ${e}
26
+ `)}stepFail(t){this._origStdoutWrite?this._writeDot(et,g.red(t)):process.stdout.write.bind(process.stdout)(`${Y} ${et} ${g.red(t)}
27
+ `)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${te} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:s,details:o}=e;if(o)for(let n of o)this._rawWrite(`${tt} ${n}`);let r=s?g.dim(` ${kt(s)}`):"";this._rawWrite(`${It} ${g.green("done")}${r}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,s={}){this._stopIntercepting();let{duration:o}=s,r=o?g.dim(` ${kt(o)}`):"";this._rawWrite(`${et} ${g.red(e)}`),this._rawWrite(`${It} ${g.red("failed")}${r}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(g.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){this._rawWrite(g.green.bold("\u2713 Workflow completed"))}},w=new ot;var V=".zibby/output",Tt="sessions",L=".session-info.json",At=".zibby-stop";var xt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var F=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode)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=t.outputSchema&&!this.isZodSchema?new J(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){let s=()=>e&&typeof e.getAll=="function"?e.getAll():t,o=l=>e&&typeof e.get=="function"?e.get(l):t?.[l];if(typeof this.customExecute=="function"){_.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(t);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(_.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 _.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&_.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let r=typeof this.prompt=="function"?this.prompt(s()):this.prompt,n=o("_skillHints");n&&(r=`${n}
28
28
 
29
- ${r}`);let a=o(),c=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let l=nt(u,C);if(At(l)){let I=JSON.parse(xt(l,"utf-8"));I.currentNode=this.name,rt(l,JSON.stringify(I,null,2),"utf-8")}let S=nt(u,"..",C);if(At(S))try{let I=JSON.parse(xt(S,"utf-8"));I.currentNode=this.name,rt(S,JSON.stringify(I,null,2),"utf-8")}catch{}}}catch(l){_.debug(`[workflow] could not update session info: ${l.message}`)}let h=null;for(let l=0;l<=this.retries;l++)try{_.debug(`[workflow] node '${this.name}' attempt ${l}`);let S=o().config||{},I=S.agents||{},f=this.config.agent??I[this.name]??null,b={state:o()};f&&(b.preferredAgent=f);let v={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:u,config:S,nodeName:this.name,timeout:this.config?.timeout||3e5},P=t?._coreInvokeAgent;P||(P=(await Promise.resolve().then(()=>(st(),ot))).invokeAgent);let d=await P(r,b,v),m,$;if(typeof d=="string"?(m=d,$=null):d.structured?(m=d.raw||JSON.stringify(d.structured,null,2),$=d.structured):(m=d.raw||JSON.stringify(d,null,2),$=d.extracted||null),u)try{let p=nt(u,this.name,"raw_stream_output.txt");se(re(p),{recursive:!0}),rt(p,typeof m=="string"?m:JSON.stringify(m),"utf-8")}catch(p){_.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&$){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify($,null,2)}`);let p=$;if(typeof this.onComplete=="function")try{p=await this.onComplete(o(),$)}catch(w){_.warn(`[workflow] onComplete hook failed: ${w.message}`)}return{success:!0,output:p,raw:m}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:m}),raw:m}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(m);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),y.step("Output parsed"),{success:!0,output:p,raw:m}}return{success:!0,output:m,raw:m}}catch(S){h=S,l<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}},J=class extends W{constructor(t){super({...t,_isCustomCode:!0}),this.condition=t.condition}async execute(t,e){let o=e&&typeof e.getAll=="function"?e.getAll():t;return{success:!0,output:{nextNode:this.condition(o)},raw:null}}};import{existsSync as Pt,readFileSync as ne}from"node:fs";import{join as it,dirname as Ct}from"node:path";var H=class{static async loadContext(t,e,o={}){let s={},r=o.filenames||["CONTEXT.md","AGENTS.md"];if(t){let a=Ct(it(e,t));for(let c of r){let u=await this.findAndMergeContextFiles(c,a,e);if(u){let h=c.replace(/\.[^.]+$/,"").toLowerCase();s[h]=u}}}let i=o.discovery||{};for(let[a,c]of Object.entries(i))try{let u=it(e,c);Pt(u)&&(s[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${c}': ${u.message}`)}return s}static async findAndMergeContextFiles(t,e,o){let s=[],r=e;for(;r.startsWith(o);){let i=it(r,t);if(Pt(i))try{s.unshift(await this.loadFile(i))}catch(c){console.warn(`[workflow] could not load ${t} from ${i}: ${c.message}`)}let a=Ct(r);if(a===r)break;r=a}return s.length===0?null:s.every(i=>typeof i=="string")?s.join(`
29
+ ${r}`);let a=s(),c=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=ut(d,L);if(Bt(l)){let E=JSON.parse(Wt(l,"utf-8"));E.currentNode=this.name,lt(l,JSON.stringify(E,null,2),"utf-8")}let m=ut(d,"..",L);if(Bt(m))try{let E=JSON.parse(Wt(m,"utf-8"));E.currentNode=this.name,lt(m,JSON.stringify(E,null,2),"utf-8")}catch{}}}catch(l){_.debug(`[workflow] could not update session info: ${l.message}`)}let h=null;for(let l=0;l<=this.retries;l++)try{_.debug(`[workflow] node '${this.name}' attempt ${l}`);let m=s().config||{},E=m.agents||{},x=this.config.agent??E[this.name]??null,P={state:s()};x&&(P.preferredAgent=x);let T={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:d,config:m,nodeName:this.name,timeout:this.config?.timeout||3e5},p=t?._coreInvokeAgent;p||(p=(await Promise.resolve().then(()=>(ct(),at))).invokeAgent);let $=await p(r,P,T),y,O;if(typeof $=="string"?(y=$,O=null):$.structured?(y=$.raw||JSON.stringify($.structured,null,2),O=$.structured):(y=$.raw||JSON.stringify($,null,2),O=$.extracted||null),d)try{let u=ut(d,this.name,"raw_stream_output.txt");le(ue(u),{recursive:!0}),lt(u,typeof y=="string"?y:JSON.stringify(y),"utf-8")}catch(u){_.debug(`[workflow] could not save raw output: ${u.message}`)}if(this.isZodSchema&&O){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(O,null,2)}`);let u=O;if(typeof this.onComplete=="function")try{u=await this.onComplete(s(),O)}catch(W){_.warn(`[workflow] onComplete hook failed: ${W.message}`)}return{success:!0,output:u,raw:y}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(s(),{raw:y}),raw:y}}catch(u){throw new Error(`onComplete failed: ${u.message}`,{cause:u})}if(this.parser){let u=this.parser.parse(y);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(u,null,2)}`),w.step("Output parsed"),{success:!0,output:u,raw:y}}return{success:!0,output:y,raw:y}}catch(m){h=m,l<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}},z=class extends F{constructor(t){super({...t,_isCustomCode:!0}),this.condition=t.condition}async execute(t,e){let s=e&&typeof e.getAll=="function"?e.getAll():t;return{success:!0,output:{nextNode:this.condition(s)},raw:null}}};import{existsSync as Mt,readFileSync as de}from"node:fs";import{join as dt,dirname as Lt}from"node:path";var q=class{static async loadContext(t,e,s={}){let o={},r=s.filenames||["CONTEXT.md","AGENTS.md"];if(t){let a=Lt(dt(e,t));for(let c of r){let d=await this.findAndMergeContextFiles(c,a,e);if(d){let h=c.replace(/\.[^.]+$/,"").toLowerCase();o[h]=d}}}let n=s.discovery||{};for(let[a,c]of Object.entries(n))try{let d=dt(e,c);Mt(d)&&(o[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${c}': ${d.message}`)}return o}static async findAndMergeContextFiles(t,e,s){let o=[],r=e;for(;r.startsWith(s);){let n=dt(r,t);if(Mt(n))try{o.unshift(await this.loadFile(n))}catch(c){console.warn(`[workflow] could not load ${t} from ${n}: ${c.message}`)}let a=Lt(r);if(a===r)break;r=a}return o.length===0?null:o.every(n=>typeof n=="string")?o.join(`
30
30
 
31
31
  ---
32
32
 
33
- `):s.every(i=>typeof i=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(t){let e=ne(t,"utf-8");if(t.endsWith(".json"))return JSON.parse(e);if(t.endsWith(".js")||t.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),s=await import(o(t).href);return s.default||s}return e}};import{mkdirSync as Mt,existsSync as at,writeFileSync as Rt,unlinkSync as ie}from"node:fs";import{join as A,resolve as Lt}from"node:path";import{config as ae}from"dotenv";import{zodToJsonSchema as Wt}from"zod-to-json-schema";import ce from"handlebars";function le({traceFrom:n,sessionId:t,sessionPath:e,idSource:o,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let i=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${n} pid=${process.pid} ppid=${i} sessionId=${t} source=${o} mkdir=${s?"yes":"no"} path=${e}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let h=(new Error("session trace").stack||"").split(`
33
+ `):o.every(n=>typeof n=="object")?Object.assign({},...o):o[o.length-1]}static async loadFile(t){let e=de(t,"utf-8");if(t.endsWith(".json"))return JSON.parse(e);if(t.endsWith(".js")||t.endsWith(".mjs")){let{pathToFileURL:s}=await import("url"),o=await import(s(t).href);return o.default||o}return e}};import{mkdirSync as Yt,existsSync as pt,writeFileSync as Dt,unlinkSync as pe}from"node:fs";import{join as R,resolve as Zt}from"node:path";import{config as fe}from"dotenv";import{zodToJsonSchema as Ft}from"zod-to-json-schema";import he from"handlebars";function me({traceFrom:i,sessionId:t,sessionPath:e,idSource:s,mkdirFresh:o}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let n=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${i} pid=${process.pid} ppid=${n} sessionId=${t} source=${s} mkdir=${o?"yes":"no"} path=${e}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let h=(new Error("session trace").stack||"").split(`
34
34
  `).slice(2,14).join(`
35
- `);console.log(`[zibby:session] stack (${n}):
36
- ${h}`)}}function ue(){return process.env.ZIBBY_RUN_SOURCE==="studio"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function de(){if(process.env.ZIBBY_RUN_SOURCE!=="studio")return;let n=process.env.ZIBBY_SESSION_PATH;if(!(n==null||String(n).trim()===""))try{return Lt(String(n).trim())}catch{return String(n).trim()}}function pe(){ue()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function fe({sessionPath:n,sessionId:t}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),t!=null&&String(t).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(t).trim())}function he(n={}){let t=kt.map(r=>process.env[r]).find(Boolean),e=Math.random().toString(36).slice(2,6),o=t||`${Date.now()}_${e}`,s=n.paths?.sessionPrefix;return s?`${s}_${o}`:o}function me({cwd:n=process.cwd(),config:t={},initialState:e={},traceFrom:o="resolveWorkflowSession"}={}){let s=e.sessionPath,r=e.sessionTimestamp,i="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=Lt(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,i="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),r==null&&(r=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,i="ZIBBY_SESSION_ID";else{let l=t.sessionId!=null?String(t.sessionId).trim():"";l&&l!=="last"?(a=l,i="config.sessionId"):(a=he(t),i="generated")}r=r??Date.now();let h=t.paths?.output||G;s=A(n,h,Ot,a)}let c=!at(s);return c&&Mt(s,{recursive:!0}),(c||i!=="initialState.sessionPath")&&le({traceFrom:o,sessionId:a,sessionPath:s,idSource:i,mkdirFresh:c}),fe({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:r}}var Bt=class{constructor(t={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(t.middleware)?[...t.middleware]:[],t.nodeMiddleware&&this.middleware.push(t.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=t.stateSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=t.invokeAgent||null}setStateSchema(t){return this.stateSchema=t,this}getStateSchema(){return this.stateSchema}addNode(t,e,o={}){let s=e instanceof W?e:new W(e);return s.name=t,this.nodes.set(t,s),o.prompt&&this.nodePrompts.set(t,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}addConditionalNode(t,e){return this.nodes.set(t,new J({...e,name:t})),this}addEdge(t,e){return this.edges.set(t,e),this}setNodeType(t,e){return this.nodeTypeMap.set(t,e),this}addConditionalEdges(t,e,{labels:o}={}){return this.edges.set(t,{conditional:!0,routes:e,labels:o}),typeof e=="function"&&this.conditionalCodeMap.set(t,e.toString()),this}setEntryPoint(t){return this.entryPoint=t,this}use(t){return typeof t=="function"&&this.middleware.push(t),this}_composeMiddleware(t,e,o,s,r){let i=o;for(let a=t.length-1;a>=0;a--){let c=t[a],u=i;i=()=>c(e,u,s,r)}return i()}serialize(){let t=[],e={};for(let[r,i]of this.nodes){let a=this.nodeTypeMap.get(r)||r;t.push({id:r,type:a,data:{nodeType:a,label:r}});let c={};i._isCustomCode&&typeof i.execute=="function"&&(c.customCode=i.execute.toString());let u=this.nodePrompts.get(r);if(u&&(c.prompt=u),typeof i.customExecute=="function"&&(c.executeCode=i.customExecute.toString()),i.outputSchema)try{if(typeof i.outputSchema._def<"u"){let l=Wt(i.outputSchema,{target:"openApi3"});c.outputSchema={jsonSchema:l,variables:this._flattenJsonSchemaToVariables(l)}}else c.outputSchema={schema:i.outputSchema}}catch(l){console.warn(`[workflow] failed to convert schema for ${r}:`,l.message)}let h=(this.resolvedToolsMap||{})[r];h?.toolIds&&(c.tools=h.toolIds),Object.keys(c).length>0&&(e[r]=c)}let o=[];for(let[r,i]of this.edges)if(typeof i=="string")o.push({source:r,target:i});else if(i.conditional){let a=this.conditionalCodeMap.get(r)||i.routes.toString(),c=this._inferConditionalTargets(i.routes),u=i.labels||{};for(let h of c){let l={source:r,target:h,data:{conditionalCode:a}};u[h]&&(l.label=u[h]),o.push(l)}}let s=null;if(this.stateSchema)try{s=Wt(this.stateSchema,{target:"openApi3"})}catch{s=this.stateSchema}return{nodes:t,edges:o,nodeConfigs:e,stateSchema:s}}_inferConditionalTargets(t){let e=t.toString(),o=new Set,s=/return\s+['"]([^'"]+)['"]/g,r;for(;(r=s.exec(e))!==null;)o.add(r[1]);return[...o]}_flattenJsonSchemaToVariables(t,e=""){let o=t;if(t.$ref&&t.definitions){let s=t.$ref.replace("#/definitions/","");o=t.definitions[s]||t}return this._flattenSchema(o,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let o=[],s=t.properties||{},r=t.required||[];for(let[i,a]of Object.entries(s)){let c=e?`${e}.${i}`:i;o.push({path:c,type:a.type||"unknown",label:a.description||this._formatLabel(i),optional:!r.includes(i)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,c)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${c}[]`))}return o}_formatLabel(t){return t.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}_summarizeNodeOutput(t,e){if(!e||typeof e!="object")return[];let o=[];e.success!==void 0&&o.push(`Result: ${e.success?"passed":"failed"}`);for(let[s,r]of Object.entries(e))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof r=="string"&&r.length<=80)o.push(`${s}: ${r}`);else if(Array.isArray(r)){let i=r.length,a=r.filter(u=>u?.passed===!0).length,c=r.some(u=>u?.passed!==void 0);o.push(c?`${s}: ${a}/${i} passed${i-a?`, ${i-a} failed`:""}`:`${s}: ${i} items`)}if(o.length>=4)break}return o}async run(t,e={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let o=e.cwd||process.cwd();ae({path:A(o,".env")});let s=e.config||{};if(!s||Object.keys(s).length===0)try{let p=A(o,".zibby.config.js");at(p)&&(s=(await import(p)).default||{})}catch{}process.env.EXECUTION_ID&&!s.agent?.strictMode&&(s.agent={...s.agent,strictMode:!0});let r=e.agentType;if(!r){let p=s?.agent;p?.provider?r=p.provider:p?.gemini?r="gemini":p?.claude?r="claude":p?.cursor?r="cursor":p?.codex?r="codex":r=process.env.AGENT_TYPE||"cursor"}let i=e.contextConfig||t?.config?.contextConfig||t?.config?.context||s?.context||{};if(this.stateSchema){let p=this.stateSchema.safeParse(e);if(!p.success){let w=p.error.issues.map(O=>`${O.path.join(".")}: ${O.message}`);throw console.error("\u274C Initial state validation failed:"),w.forEach(O=>console.error(` - ${O}`)),new Error(`State validation failed: ${w.join(", ")}`)}y.step("State validated against schema")}let a=de(),c=e.sessionPath||a;c||pe();let{sessionPath:u,sessionTimestamp:h,sessionId:l}=me({cwd:o,config:s,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:e.sessionTimestamp}});y.step(`Session ${l}`);let S=await H.loadContext(e.specPath||"",o,i);Object.keys(S).length>0&&y.step(`Context loaded: ${Object.keys(S).join(", ")}`);let I=e.outputPath;!I&&e.specPath&&(t?.calculateOutputPath?I=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let f=new U({...e,config:s,agentType:r,outputPath:I,sessionPath:u,sessionTimestamp:h,context:S,resolvedTools:this.resolvedToolsMap||{}}),b=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:v}=await Promise.resolve().then(()=>(tt(),vt)),P=new Set;for(let[,p]of this.nodes)for(let w of p.config?.skills||[])P.add(w);for(let p of P){let w=v(p);if(typeof w?.middleware=="function")try{let O=await w.middleware();typeof O=="function"&&b.set(p,O)}catch{}}let d=this.entryPoint,m=[];for(;d&&d!=="END";){let p=A(u,Nt);if(at(p)){console.warn(`
37
- \u{1F6D1} Studio stop requested \u2014 ending workflow.`);try{ie(p)}catch{}if(t&&typeof t.cleanup=="function")try{await t.cleanup()}catch{}return y.step("Workflow stopped by Studio"),{success:!0,state:f.getAll(),executionLog:m,stoppedByStudio:!0}}let w=this.nodes.get(d);if(!w)throw new Error(`Node '${d}' not found in graph`);let O=JSON.stringify({sessionPath:u,sessionTimestamp:h,currentNode:d,createdAt:new Date().toISOString(),config:f.get("config")}),Dt=A(u,C);Rt(Dt,O,"utf-8");let ct=f.get("config")?.paths?.output||G,Ft=A(o,ct,C);Mt(A(o,ct),{recursive:!0});try{Rt(Ft,O,"utf-8")}catch{}let lt=e.onPipelineProgress;if(typeof lt=="function")try{lt({cwd:o,sessionPath:u,sessionId:l,outputBase:f.get("config")?.paths?.output||G,currentNode:d})}catch{}let jt=(this.resolvedToolsMap||{})[d]||null;f.set("_currentNodeTools",jt);let Ut=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Ut[d]||{}),y.nodeStart(d);let ut=Date.now(),L=this.nodePrompts.get(d);if(!this._invokeAgent){let N=await Promise.resolve().then(()=>(st(),ot));this._invokeAgent=N.invokeAgent}let dt=this._invokeAgent,pt={state:f,invokeAgent:async(N={},k={})=>{let E=k.prompt||"";if(L)try{E=ce.compile(L,{noEscape:!0})(N)}catch(T){throw console.error(`\u274C Template rendering failed for node '${d}':`,T.message),new Error(`Template rendering failed: ${T.message}`,{cause:T})}else if(!E)throw new Error(`No prompt template configured for node '${d}' and no prompt provided in options`);return dt(E,{state:f.getAll(),images:k.images||[]},{model:k.model||f.get("model"),workspace:f.get("workspace"),schema:k.schema,...k})},_coreInvokeAgent:dt,agent:t,nodeId:d,promptTemplate:L,getPromptTemplate:()=>L,...f.getAll()};try{let N=(w.config?.skills||[]).map(B=>b.get(B)).filter(Boolean),k=[...this.middleware,...N],E;k.length>0?E=await this._composeMiddleware(k,d,async()=>w.execute(pt,f),f.getAll(),f):E=await w.execute(pt,f);let T=Date.now()-ut;if(m.push({node:d,success:E.success,duration:T,timestamp:new Date().toISOString()}),!E.success){if(String(E.error||"").includes("Stopped from Zibby Studio")){if(y.step("Workflow stopped by Studio"),f.set("stoppedByStudio",!0),t&&typeof t.cleanup=="function")try{await t.cleanup()}catch{}return{success:!0,state:f.getAll(),executionLog:m,stoppedByStudio:!0}}f.append("errors",{node:d,error:E.error});let ft=w.config?.retries||0,ht=`${d}_retries`,F=f.getAll()[ht]||0;if(F<ft){y.stepInfo(`Retrying (attempt ${F+1}/${ft})`),f.update({[ht]:F+1,[`${d}_raw`]:E.raw});continue}throw y.nodeFailed(d,E.error,{duration:T}),new Error(`Node '${d}' failed after ${F} attempts: ${E.error}`)}f.update({[d]:E.output});let Yt=this._summarizeNodeOutput(d,E.output);y.nodeComplete(d,{duration:T,details:Yt});let D=this.edges.get(d);if(!D)d="END";else if(D.conditional){let B=D.routes(f.getAll());y.route(d,B),d=B}else d=D}catch(N){throw y.isInsideNode&&y.nodeFailed(d,N.message,{duration:Date.now()-ut}),f.set("failed",!0),f.set("failedAt",d),N}}y.graphComplete();let $={success:!0,state:f.getAll(),executionLog:m};return t&&typeof t.onComplete=="function"&&await t.onComplete($),$}};export{Bt as WorkflowGraph,pe as clearInheritedSessionEnvForFreshRun,he as generateWorkflowSessionId,de as readStudioPinnedSessionPathFromEnv,me as resolveWorkflowSession,ue as shouldTrustInheritedSessionEnv,fe as syncProcessEnvToSession};
35
+ `);console.log(`[zibby:session] stack (${i}):
36
+ ${h}`)}}function ge(){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 Se(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let t=process.env.ZIBBY_SESSION_PATH;if(!(t==null||String(t).trim()===""))try{return Zt(String(t).trim())}catch{return String(t).trim()}}function _e(){ge()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function we({sessionPath:i,sessionId:t}){i&&typeof i=="string"&&(process.env.ZIBBY_SESSION_PATH=i),t!=null&&String(t).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(t).trim())}function ye(i={}){let t=xt.map(r=>process.env[r]).find(Boolean),e=Math.random().toString(36).slice(2,6),s=t||`${Date.now()}_${e}`,o=i.paths?.sessionPrefix;return o?`${o}_${s}`:s}function Ee({cwd:i=process.cwd(),config:t={},initialState:e={},traceFrom:s="resolveWorkflowSession"}={}){let o=e.sessionPath,r=e.sessionTimestamp,n="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let d=Zt(String(process.env.ZIBBY_SESSION_PATH));d&&(o=d,n="ZIBBY_SESSION_PATH")}catch{}let a;if(o)a=String(o).split(/[/\\]/).filter(Boolean).pop(),r==null&&(r=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,n="ZIBBY_SESSION_ID";else{let l=t.sessionId!=null?String(t.sessionId).trim():"";l&&l!=="last"?(a=l,n="config.sessionId"):(a=ye(t),n="generated")}r=r??Date.now();let h=t.paths?.output||V;o=R(i,h,Tt,a)}let c=!pt(o);return c&&Yt(o,{recursive:!0}),(c||n!=="initialState.sessionPath")&&me({traceFrom:s,sessionId:a,sessionPath:o,idSource:n,mkdirFresh:c}),we({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:r}}var jt=class{constructor(t={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(t.middleware)?[...t.middleware]:[],t.nodeMiddleware&&this.middleware.push(t.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=t.stateSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=t.invokeAgent||null,this._compiledPrompts=new Map}setStateSchema(t){return this.stateSchema=t,this}getStateSchema(){return this.stateSchema}addNode(t,e,s={}){let o=e instanceof F?e:new F(e);return o.name=t,this.nodes.set(t,o),s.prompt&&this.nodePrompts.set(t,s.prompt),Object.keys(s).length>0&&this.nodeOptions.set(t,s),this}addConditionalNode(t,e){return this.nodes.set(t,new z({...e,name:t})),this}addEdge(t,e){return this.edges.set(t,e),this}setNodeType(t,e){return this.nodeTypeMap.set(t,e),this}addConditionalEdges(t,e,{labels:s}={}){return this.edges.set(t,{conditional:!0,routes:e,labels:s}),typeof e=="function"&&this.conditionalCodeMap.set(t,e.toString()),this}setEntryPoint(t){return this.entryPoint=t,this}use(t){return typeof t=="function"&&this.middleware.push(t),this}_composeMiddleware(t,e,s,o,r){let n=s;for(let a=t.length-1;a>=0;a--){let c=t[a],d=n;n=()=>c(e,d,o,r)}return n()}serialize(){let t=[],e={};for(let[r,n]of this.nodes){let a=this.nodeTypeMap.get(r)||r;t.push({id:r,type:a,data:{nodeType:a,label:r}});let c={};n._isCustomCode&&typeof n.execute=="function"&&(c.customCode=n.execute.toString());let d=this.nodePrompts.get(r);if(d&&(c.prompt=d),typeof n.customExecute=="function"&&(c.executeCode=n.customExecute.toString()),n.outputSchema)try{if(typeof n.outputSchema._def<"u"){let l=Ft(n.outputSchema,{target:"openApi3"});c.outputSchema={jsonSchema:l,variables:this._flattenJsonSchemaToVariables(l)}}else c.outputSchema={schema:n.outputSchema}}catch(l){console.warn(`[workflow] failed to convert schema for ${r}:`,l.message)}let h=(this.resolvedToolsMap||{})[r];h?.toolIds&&(c.tools=h.toolIds),Object.keys(c).length>0&&(e[r]=c)}let s=[];for(let[r,n]of this.edges)if(typeof n=="string")s.push({source:r,target:n});else if(n.conditional){let a=this.conditionalCodeMap.get(r)||n.routes.toString(),c=this._inferConditionalTargets(n.routes),d=n.labels||{};for(let h of c){let l={source:r,target:h,data:{conditionalCode:a}};d[h]&&(l.label=d[h]),s.push(l)}}let o=null;if(this.stateSchema)try{o=Ft(this.stateSchema,{target:"openApi3"})}catch{o=this.stateSchema}return{nodes:t,edges:s,nodeConfigs:e,stateSchema:o}}_inferConditionalTargets(t){let e=t.toString(),s=new Set,o=/return\s+['"]([^'"]+)['"]/g,r;for(;(r=o.exec(e))!==null;)s.add(r[1]);return[...s]}_flattenJsonSchemaToVariables(t,e=""){let s=t;if(t.$ref&&t.definitions){let o=t.$ref.replace("#/definitions/","");s=t.definitions[o]||t}return this._flattenSchema(s,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let s=[],o=t.properties||{},r=t.required||[];for(let[n,a]of Object.entries(o)){let c=e?`${e}.${n}`:n;s.push({path:c,type:a.type||"unknown",label:a.description||this._formatLabel(n),optional:!r.includes(n)}),a.type==="object"&&a.properties&&s.push(...this._flattenSchema(a,c)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&s.push(...this._flattenSchema(a.items,`${c}[]`))}return s}_formatLabel(t){return t.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}_summarizeNodeOutput(t,e){if(!e||typeof e!="object")return[];let s=[];e.success!==void 0&&s.push(`Result: ${e.success?"passed":"failed"}`);for(let[o,r]of Object.entries(e))if(!(o==="success"||o==="raw"||o==="nextNode")){if(typeof r=="string"&&r.length<=80)s.push(`${o}: ${r}`);else if(Array.isArray(r)){let n=r.length,a=r.filter(d=>d?.passed===!0).length,c=r.some(d=>d?.passed!==void 0);s.push(c?`${o}: ${a}/${n} passed${n-a?`, ${n-a} failed`:""}`:`${o}: ${n} items`)}if(s.length>=4)break}return s}async run(t,e={},s={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let o=new AbortController;s.signal&&(s.signal.aborted?o.abort():s.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let r=s.strategyAbortTimeoutMs??e.config?.strategyAbortTimeoutMs??5e3,n=e.cwd||process.cwd();fe({path:R(n,".env")});let a=e.config||{};if(!a||Object.keys(a).length===0)try{let f=R(n,".zibby.config.js");pt(f)&&(a=(await import(f)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let c=e.agentType;if(!c){let f=a?.agent;f?.provider?c=f.provider:f?.gemini?c="gemini":f?.claude?c="claude":f?.cursor?c="cursor":f?.codex?c="codex":c=process.env.AGENT_TYPE||"cursor"}let d=e.contextConfig||t?.config?.contextConfig||t?.config?.context||a?.context||{};if(this.stateSchema){let f=this.stateSchema.safeParse(e);if(!f.success){let N=f.error.issues.map(I=>`${I.path.join(".")}: ${I.message}`);throw console.error("\u274C Initial state validation failed:"),N.forEach(I=>console.error(` - ${I}`)),new Error(`State validation failed: ${N.join(", ")}`)}w.step("State validated against schema")}let h=Se(),l=e.sessionPath||h;l||_e();let{sessionPath:m,sessionTimestamp:E,sessionId:x}=Ee({cwd:n,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:e.sessionTimestamp}});w.step(`Session ${x}`);let P=await q.loadContext(e.specPath||"",n,d);Object.keys(P).length>0&&w.step(`Context loaded: ${Object.keys(P).join(", ")}`);let T=e.outputPath;!T&&e.specPath&&(t?.calculateOutputPath?T=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let p=new H({...e,config:a,agentType:c,outputPath:T,sessionPath:m,sessionTimestamp:E,context:P,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),$=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(nt(),Ct)),O=new Set;for(let[,f]of this.nodes)for(let N of f.config?.skills||[])O.add(N);for(let f of O){let N=y(f);if(typeof N?.middleware=="function")try{let I=await N.middleware();typeof I=="function"&&$.set(f,I)}catch{}}let u=this.entryPoint,W=[],ft=a?.recursionLimit??100,Ut=0;try{for(;u&&u!=="END";){if(++Ut>ft)throw new Error(`Workflow exceeded recursion limit (${ft}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let N=R(m,At);if(pt(N)){try{pe(N)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
37
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),w.step("Workflow stopped externally"),{success:!0,state:p.getAll(),executionLog:W,stoppedExternally:!0};let I=this.nodes.get(u);if(!I)throw new Error(`Node '${u}' not found in graph`);let ht=JSON.stringify({sessionPath:m,sessionTimestamp:E,currentNode:u,createdAt:new Date().toISOString(),config:p.get("config")}),Gt=R(m,L);Dt(Gt,ht,"utf-8");let mt=p.get("config")?.paths?.output||V,Ht=R(n,mt,L);Yt(R(n,mt),{recursive:!0});try{Dt(Ht,ht,"utf-8")}catch{}let gt=e.onPipelineProgress;if(typeof gt=="function")try{gt({cwd:n,sessionPath:m,sessionId:x,outputBase:p.get("config")?.paths?.output||V,currentNode:u})}catch{}let Jt=(this.resolvedToolsMap||{})[u]||null;p.set("_currentNodeTools",Jt);let Kt=p.get("nodeConfigs")||{};p.set("_currentNodeConfig",Kt[u]||{}),w.nodeStart(u);let St=Date.now(),Z=this.nodePrompts.get(u);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(ct(),at));this._invokeAgent=k.invokeAgent}let Vt=this._invokeAgent,_t=async(k,v,S={})=>{let b=Vt(k,v,{...S,signal:o.signal});return b.catch(()=>{}),o.signal.aborted?b:Promise.race([b,new Promise((B,M)=>{let A=()=>{setTimeout(()=>{let j=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${r}ms`);j.name="AbortError",M(j)},r)};o.signal.addEventListener("abort",A,{once:!0})})])},wt={state:p,invokeAgent:async(k={},v={})=>{let S=v.prompt||"";if(Z){let b=this._compiledPrompts.get(u);b||(b=he.compile(Z,{noEscape:!0}),this._compiledPrompts.set(u,b));try{S=b(k)}catch(B){throw console.error(`\u274C Template rendering failed for node '${u}':`,B.message),new Error(`Template rendering failed: ${B.message}`,{cause:B})}}else if(!S)throw new Error(`No prompt template configured for node '${u}' and no prompt provided in options`);return _t(S,{state:p.getAll(),images:v.images||[]},{model:v.model||p.get("model"),workspace:p.get("workspace"),schema:v.schema,...v,signal:o.signal})},_coreInvokeAgent:_t,agent:t,nodeId:u,promptTemplate:Z,getPromptTemplate:()=>Z,...p.getAll()};try{let k=(I.config?.skills||[]).map(A=>$.get(A)).filter(Boolean),v=[...this.middleware,...k],S;v.length>0?S=await this._composeMiddleware(v,u,async()=>I.execute(wt,p),p.getAll(),p):S=await I.execute(wt,p);let b=Date.now()-St;if(W.push({node:u,success:S.success,duration:b,timestamp:new Date().toISOString()}),!S.success){if(o.signal.aborted)return w.step("Workflow stopped externally"),{success:!0,state:p.getAll(),executionLog:W,stoppedExternally:!0};p.append("errors",{node:u,error:S.error});let A=I.config?.retries||0,j=`${u}_retries`,U=p.getAll()[j]||0;if(U<A){w.stepInfo(`Retrying (attempt ${U+1}/${A})`),p.update({[j]:U+1,[`${u}_raw`]:S.raw});continue}throw w.nodeFailed(u,S.error,{duration:b}),new Error(`Node '${u}' failed after ${U} attempts: ${S.error}`)}p.update({[u]:S.output});let B=this._summarizeNodeOutput(u,S.output);w.nodeComplete(u,{duration:b,details:B});let M=this.edges.get(u);if(!M)u="END";else if(M.conditional){let A=M.routes(p.getAll());w.route(u,A),u=A}else u=M}catch(k){throw w.isInsideNode&&w.nodeFailed(u,k.message,{duration:Date.now()-St}),p.set("failed",!0),p.set("failedAt",u),k}}w.graphComplete();let f={success:!0,state:p.getAll(),executionLog:W};return t&&typeof t.onComplete=="function"&&await t.onComplete(f),f}finally{if(t&&typeof t.cleanup=="function")try{await t.cleanup()}catch(f){console.warn(`[workflow] agent.cleanup() failed: ${f.message}`)}}}};export{jt as WorkflowGraph,_e as clearInheritedSessionEnvForFreshRun,ye as generateWorkflowSessionId,Se as readPinnedSessionPathFromEnv,Ee as resolveWorkflowSession,ge as shouldTrustInheritedSessionEnv,we as syncProcessEnvToSession};
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ export { WorkflowState } from "./state.js";
2
2
  export { ContextLoader } from "./context-loader.js";
3
3
  export { AgentStrategy } from "./agents/base.js";
4
4
  export { setLogger } from "./logger.js";
5
- export { WorkflowGraph, generateWorkflowSessionId, resolveWorkflowSession, shouldTrustInheritedSessionEnv, readStudioPinnedSessionPathFromEnv, clearInheritedSessionEnvForFreshRun, syncProcessEnvToSession } from "./graph.js";
5
+ export { WorkflowGraph, generateWorkflowSessionId, resolveWorkflowSession, shouldTrustInheritedSessionEnv, readPinnedSessionPathFromEnv, clearInheritedSessionEnvForFreshRun, syncProcessEnvToSession } from "./graph.js";
6
6
  export { Node, ConditionalNode } from "./node.js";
7
7
  export { OutputParser, SchemaTypes } from "./output-parser.js";
8
8
  export { compileGraph, validateGraphConfig, extractSteps, CompilationError } from "./graph-compiler.js";
@@ -11,5 +11,5 @@ export { registerSkill, getSkill, hasSkill, getAllSkills, listSkillIds, clearSki
11
11
  export { resolveNodeTools, getResolvedToolDefinitions, NODE_DEFAULT_TOOLS } from "./tool-resolver.js";
12
12
  export { registerStrategy, listStrategies, getAgentStrategy, invokeAgent } from "./strategy-registry.js";
13
13
  export { generateWorkflowCode, generateNodeConfigsJson } from "./code-generator.js";
14
- export { SKILLS, DEFAULT_OUTPUT_BASE, SESSIONS_DIR, SESSION_INFO_FILE, STUDIO_STOP_REQUEST_FILE, RESULT_FILE, RAW_OUTPUT_FILE, EVENTS_FILE, CI_ENV_VARS } from "./constants.js";
14
+ export { SKILLS, DEFAULT_OUTPUT_BASE, SESSIONS_DIR, SESSION_INFO_FILE, STOP_REQUEST_FILE, RESULT_FILE, RAW_OUTPUT_FILE, EVENTS_FILE, CI_ENV_VARS } from "./constants.js";
15
15
  export { timeline, Timeline, WORKFLOW_GRAPH_LOG_MARKER_PREFIX } from "./timeline.js";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- var _t=Object.defineProperty;var ie=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var te=(o,e)=>()=>(o&&(e=o(o=0)),e);var be=(o,e)=>{for(var t in e)_t(o,t,{get:e[t],enumerable:!0})};function Nt(o){G.impl={...Re,...o}}var Pe,Re,G,_,L=te(()=>{Pe=()=>{},Re={debug:Pe,info:Pe,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},G={impl:Re};_={debug:(...o)=>G.impl.debug?.(...o),info:(...o)=>G.impl.info?.(...o),warn:(...o)=>G.impl.warn?.(...o),error:(...o)=>G.impl.error?.(...o)}});var fe,he=te(()=>{fe=class{constructor(e,t,s=0){this.name=e,this.description=t,this.priority=s}async invoke(e,t={}){throw new Error(`${this.constructor.name}.invoke() must be implemented`)}canHandle(e){throw new Error(`${this.constructor.name}.canHandle() must be implemented`)}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var Ve={};be(Ve,{clearSkills:()=>He,getAllSkills:()=>Ye,getSkill:()=>F,hasSkill:()=>Ze,listSkillIds:()=>Je,registerSkill:()=>Ge});function Ge(o){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");D.set(o.id,Object.freeze({...o}))}function F(o){return D.get(o)||null}function Ze(o){return D.has(o)}function Ye(){return new Map(D)}function Je(){return Array.from(D.keys())}function He(){D.clear()}var D,J=te(()=>{D=new Map});var H={};be(H,{getAgentStrategy:()=>ge,invokeAgent:()=>qe,listStrategies:()=>ze,registerStrategy:()=>Ke});function Ke(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=P.findIndex(t=>t.getName()===o.getName());e>=0?P[e]=o:P.push(o)}function ze(){return P.map(o=>o.getName())}function ge(o={}){let{state:e={},preferredAgent:t=null}=o,s=t||e.agentType||process.env.AGENT_TYPE;if(!s){let n=P.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${n}`)}_.debug(`[workflow] agent selection: requested=${s}`);let i=P.find(n=>n.getName()===s);if(!i){let n=P.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${s}'. Available: ${n}`)}if(!i.canHandle(o))throw new Error(`Agent '${s}' is not available in this environment. Check credentials/environment.`);return _.debug(`[workflow] using agent: ${i.getName()}`),i}async function qe(o,e={},t={}){let s=ge(e),i=e.state?.config||t.config||{},n=i.models||{},r=t.nodeName&&n[t.nodeName]||null,a=n.default||null,c=i.agent?.[s.name]?.model||null,d=r||a||c||t.model||null,h={...t,model:d,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:i},u=o,l=h.skills||[];if(l.length>0&&!t.skipPromptFragments){let p=l.map(S=>{let y=F(S)?.promptFragment;return typeof y=="function"?y():y}).filter(Boolean);p.length>0&&(u+=`
1
+ var kt=Object.defineProperty;var de=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var ne=(o,e)=>()=>(o&&(e=o(o=0)),e);var Fe=(o,e)=>{for(var t in e)kt(o,t,{get:e[t],enumerable:!0})};function At(o){K.impl={...De,...o}}var Me,De,K,_,j=ne(()=>{Me=()=>{},De={debug:Me,info:Me,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},K={impl:De};_={debug:(...o)=>K.impl.debug?.(...o),info:(...o)=>K.impl.info?.(...o),warn:(...o)=>K.impl.warn?.(...o),error:(...o)=>K.impl.error?.(...o)}});var Se,we=ne(()=>{Se=class{constructor(e,t,s=0){this.name=e,this.description=t,this.priority=s}async invoke(e,t={}){throw new Error(`${this.constructor.name}.invoke() must be implemented`)}canHandle(e){throw new Error(`${this.constructor.name}.canHandle() must be implemented`)}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var et={};Fe(et,{clearSkills:()=>Qe,getAllSkills:()=>qe,getSkill:()=>U,hasSkill:()=>ze,listSkillIds:()=>Xe,registerSkill:()=>Ve});function Ve(o){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");G.set(o.id,Object.freeze({...o}))}function U(o){return G.get(o)||null}function ze(o){return G.has(o)}function qe(){return new Map(G)}function Xe(){return Array.from(G.keys())}function Qe(){G.clear()}var ye,G,q=ne(()=>{ye=Symbol.for("@zibby/agent-workflow.skills");globalThis[ye]||(globalThis[ye]=new Map);G=globalThis[ye]});var X={};Fe(X,{getAgentStrategy:()=>Ee,invokeAgent:()=>rt,listStrategies:()=>ot,registerStrategy:()=>tt});function tt(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=W.findIndex(t=>t.getName()===o.getName());e>=0?W[e]=o:W.push(o)}function ot(){return W.map(o=>o.getName())}function Ee(o={}){let{state:e={},preferredAgent:t=null}=o,s=t||e.agentType||process.env.AGENT_TYPE;if(!s){let i=W.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}_.debug(`[workflow] agent selection: requested=${s}`);let n=W.find(i=>i.getName()===s);if(!n){let i=W.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${s}'. Available: ${i}`)}if(!n.canHandle(o))throw new Error(`Agent '${s}' is not available in this environment. Check credentials/environment.`);return _.debug(`[workflow] using agent: ${n.getName()}`),n}async function rt(o,e={},t={}){let s=Ee(e),n=e.state?.config||t.config||{},i=n.models||{},r=t.nodeName&&i[t.nodeName]||null,a=i.default||null,c=n.agent?.[s.name]?.model||null,l=r||a||c||t.model||null,h={...t,model:l,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:n},u=o,d=h.skills||[];if(d.length>0&&!t.skipPromptFragments){let m=d.map(S=>{let w=U(S)?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);m.length>0&&(u+=`
2
2
 
3
- ${p.join(`
3
+ ${m.join(`
4
4
 
5
5
  `)}`)}let g=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return g&&(u+=`
6
6
 
@@ -9,46 +9,46 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
9
9
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
10
10
 
11
11
  ${g}
12
- `),_.debug(`[workflow] prompt length: ${u.length} chars`),s.invoke(u,h)}var me,P,B=te(()=>{he();L();J();me=Symbol.for("@zibby/agent-workflow.strategies");globalThis[me]||(globalThis[me]=[]);P=globalThis[me]});var $t=new Set(["__proto__","constructor","prototype"]);function ae(o){if($t.has(o))throw new Error(`Invalid state key: "${o}"`)}var j=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){ae(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let s of t)ae(s);this._history.push({...this._state});for(let s of t)this._state[s]=e[s]}append(e,t){ae(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};var U=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 s=e.match(/\{[\s\S]*\}/);return s?this.validate(JSON.parse(s[0])):this.validate({result:e.trim()})}validate(e){let t=[];for(let[s,i]of Object.entries(this.schema)){if(i.required&&!(s in e)&&t.push(`Missing required field: ${s}`),s in e&&i.type){let n=typeof e[s];n!==i.type&&t.push(`Field '${s}' expected ${i.type}, got ${n}`)}if(i.validate&&s in e){let n=i.validate(e[s]);n&&t.push(`Field '${s}': ${n}`)}}if(t.length>0)throw new Error(`Output validation failed:
12
+ `),_.debug(`[workflow] prompt length: ${u.length} chars`),s.invoke(u,h)}var _e,W,Y=ne(()=>{we();j();q();_e=Symbol.for("@zibby/agent-workflow.strategies");globalThis[_e]||(globalThis[_e]=[]);W=globalThis[_e]});var xt=new Set(["__proto__","constructor","prototype"]);function ue(o){if(xt.has(o))throw new Error(`Invalid state key: "${o}"`)}var J=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){ue(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let s of t)ue(s);this._history.push({...this._state});for(let s of t)this._state[s]=e[s]}append(e,t){ue(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())}};var H=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 s=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(n=>n[0]);for(let n of s)try{return this.validate(JSON.parse(n))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[s,n]of Object.entries(this.schema)){if(n.required&&!(s in e)&&t.push(`Missing required field: ${s}`),s in e&&n.type){let i=typeof e[s];i!==n.type&&t.push(`Field '${s}' expected ${n.type}, got ${i}`)}if(n.validate&&s in e){let i=n.validate(e[s]);i&&t.push(`Field '${s}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
13
13
  ${t.join(`
14
- `)}`);return e}},Et={string:(o=!0)=>({type:"string",required:o}),number:(o=!0)=>({type:"number",required:o}),boolean:(o=!0)=>({type:"boolean",required:o}),array:(o=!0)=>({type:"object",required:o,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(o,e=!0)=>({type:"string",required:e,validate:t=>o.includes(t)?null:`must be one of: ${o.join(", ")}`})};L();import{writeFileSync as Se,readFileSync as Xe,existsSync as Qe,mkdirSync as Ot}from"node:fs";import{join as we,dirname as At}from"node:path";import E from"chalk";var Ue="__WORKFLOW_GRAPH_LOG__",Z=E.gray("\u2502"),It=E.gray("\u250C"),We=E.gray("\u2514"),ce=E.green("\u25C6"),Le=E.hex("#c084fc")("\u25C6"),De=E.hex("#2dd4bf")("\u25C6"),de=E.red("\u25C6"),Fe=`${Z} `,Be=2;function Me(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function je(o,e){return(t,s,i)=>{if(typeof t!="string")return o(t,s,i);let n=process.stdout.columns||120,r="";for(let a=0;a<t.length;a++){let c=t[a];e.lineStart&&(r+=Fe,e.col=Be,e.lineStart=!1),c===`
15
- `?(r+=c,e.lineStart=!0,e.col=0,e.inEsc=!1):c==="\x1B"?(e.inEsc=!0,r+=c):e.inEsc?(r+=c,(c>="A"&&c<="Z"||c>="a"&&c<="z")&&(e.inEsc=!1)):(e.col++,r+=c,e.col>=n&&(r+=`
16
- ${Fe}`,e.col=Be))}return o(r,s,i)}}var oe=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let e=String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase(),t=String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1";this._emitWorkflowGraphMarkers=t||e==="studio"}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=je(this._origStdoutWrite,e),process.stderr.write=je(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
14
+ `)}`);return e}},bt={string:(o=!0)=>({type:"string",required:o}),number:(o=!0)=>({type:"number",required:o}),boolean:(o=!0)=>({type:"boolean",required:o}),array:(o=!0)=>({type:"object",required:o,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(o,e=!0)=>({type:"string",required:e,validate:t=>o.includes(t)?null:`must be one of: ${o.join(", ")}`})};j();import{writeFileSync as $e,readFileSync as st,existsSync as nt,mkdirSync as Lt}from"node:fs";import{join as Te,dirname as Bt}from"node:path";import $ from"chalk";var Ke="__WORKFLOW_GRAPH_LOG__",V=$.gray("\u2502"),Ot=$.gray("\u250C"),je=$.gray("\u2514"),pe=$.green("\u25C6"),Ge=$.hex("#c084fc")("\u25C6"),Ue=$.hex("#2dd4bf")("\u25C6"),fe=$.red("\u25C6"),Ye=`${V} `,Ze=2;function Je(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function He(o,e){return(t,s,n)=>{if(typeof t!="string")return o(t,s,n);let i=process.stdout.columns||120,r="";for(let a=0;a<t.length;a++){let c=t[a];e.lineStart&&(r+=Ye,e.col=Ze,e.lineStart=!1),c===`
15
+ `?(r+=c,e.lineStart=!0,e.col=0,e.inEsc=!1):c==="\x1B"?(e.inEsc=!0,r+=c):e.inEsc?(r+=c,(c>="A"&&c<="Z"||c>="a"&&c<="z")&&(e.inEsc=!1)):(e.col++,r+=c,e.col>=i&&(r+=`
16
+ ${Ye}`,e.col=Ze))}return o(r,s,n)}}var ie=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=He(this._origStdoutWrite,e),process.stderr.write=He(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
17
17
  `),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
18
18
  `),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
19
- `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Ue}${JSON.stringify(e)}
19
+ `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Ke}${JSON.stringify(e)}
20
20
  `;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
21
21
  `),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
22
22
  `)):process.stdout.write.bind(process.stdout)(`${e} ${t}
23
- `)}step(e){this._origStdoutWrite?this._writeDot(ce,e):process.stdout.write.bind(process.stdout)(`${Z} ${ce} ${e}
24
- `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Le,e):process.stdout.write.bind(process.stdout)(`${Z} ${Le} ${e}
25
- `)}stepMemory(e){let t=E.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(De,t):process.stdout.write.bind(process.stdout)(`${Z} ${De} ${t}
26
- `)}stepFail(e){this._origStdoutWrite?this._writeDot(de,E.red(e)):process.stdout.write.bind(process.stdout)(`${Z} ${de} ${E.red(e)}
27
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${It} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:s,details:i}=t;if(i)for(let r of i)this._rawWrite(`${ce} ${r}`);let n=s?E.dim(` ${Me(s)}`):"";this._rawWrite(`${We} ${E.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,s={}){this._stopIntercepting();let{duration:i}=s,n=i?E.dim(` ${Me(i)}`):"";this._rawWrite(`${de} ${E.red(t)}`),this._rawWrite(`${We} ${E.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(E.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){this._rawWrite(E.green.bold("\u2713 Workflow completed"))}},N=new oe;var Y=".zibby/output",le="sessions",b=".session-info.json",ue=".zibby-studio-stop",Tt="result.json",vt="raw_stream_output.txt",kt="events.json",xt={BROWSER:"browser",JIRA:"jira",GITHUB:"github",SLACK:"slack",MEMORY:"memory",CHAT_MEMORY:"chat-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder"},pe=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var R=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode)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 U(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){let s=()=>t&&typeof t.getAll=="function"?t.getAll():e,i=u=>t&&typeof t.get=="function"?t.get(u):e?.[u];if(typeof this.customExecute=="function"){_.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let u=await this.customExecute(e);return typeof u=="object"&&u!==null&&u.success===!1?{success:!1,error:u.error||"Node execution failed",raw:u.raw||null}:this.isZodSchema?(_.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(u),raw:null}):{success:!0,output:u,raw:null}}catch(u){return _.error(`[workflow] node '${this.name}' failed: ${u.message}`),u.name==="ZodError"&&_.error(`Schema errors: ${JSON.stringify(u.errors,null,2)}`),{success:!1,error:u.message,raw:null}}}let n=typeof this.prompt=="function"?this.prompt(s()):this.prompt,r=i("_skillHints");r&&(n=`${r}
23
+ `)}step(e){this._origStdoutWrite?this._writeDot(pe,e):process.stdout.write.bind(process.stdout)(`${V} ${pe} ${e}
24
+ `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Ge,e):process.stdout.write.bind(process.stdout)(`${V} ${Ge} ${e}
25
+ `)}stepMemory(e){let t=$.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(Ue,t):process.stdout.write.bind(process.stdout)(`${V} ${Ue} ${t}
26
+ `)}stepFail(e){this._origStdoutWrite?this._writeDot(fe,$.red(e)):process.stdout.write.bind(process.stdout)(`${V} ${fe} ${$.red(e)}
27
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Ot} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:s,details:n}=t;if(n)for(let r of n)this._rawWrite(`${pe} ${r}`);let i=s?$.dim(` ${Je(s)}`):"";this._rawWrite(`${je} ${$.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,s={}){this._stopIntercepting();let{duration:n}=s,i=n?$.dim(` ${Je(n)}`):"";this._rawWrite(`${fe} ${$.red(t)}`),this._rawWrite(`${je} ${$.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite($.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){this._rawWrite($.green.bold("\u2713 Workflow completed"))}},T=new ie;var z=".zibby/output",he="sessions",R=".session-info.json",me=".zibby-stop",Ct="result.json",Pt="raw_stream_output.txt",Rt="events.json",Wt={BROWSER:"browser",JIRA:"jira",GITHUB:"github",SLACK:"slack",MEMORY:"memory",CHAT_MEMORY:"chat-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder"},ge=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];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)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 H(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){let s=()=>t&&typeof t.getAll=="function"?t.getAll():e,n=u=>t&&typeof t.get=="function"?t.get(u):e?.[u];if(typeof this.customExecute=="function"){_.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let u=await this.customExecute(e);return typeof u=="object"&&u!==null&&u.success===!1?{success:!1,error:u.error||"Node execution failed",raw:u.raw||null}:this.isZodSchema?(_.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(u),raw:null}):{success:!0,output:u,raw:null}}catch(u){return _.error(`[workflow] node '${this.name}' failed: ${u.message}`),u.name==="ZodError"&&_.error(`Schema errors: ${JSON.stringify(u.issues||u.errors,null,2)}`),{success:!1,error:u.message,raw:null}}}let i=typeof this.prompt=="function"?this.prompt(s()):this.prompt,r=n("_skillHints");r&&(i=`${r}
28
28
 
29
- ${n}`);let a=s(),c=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let u=we(d,b);if(Qe(u)){let g=JSON.parse(Xe(u,"utf-8"));g.currentNode=this.name,Se(u,JSON.stringify(g,null,2),"utf-8")}let l=we(d,"..",b);if(Qe(l))try{let g=JSON.parse(Xe(l,"utf-8"));g.currentNode=this.name,Se(l,JSON.stringify(g,null,2),"utf-8")}catch{}}}catch(u){_.debug(`[workflow] could not update session info: ${u.message}`)}let h=null;for(let u=0;u<=this.retries;u++)try{_.debug(`[workflow] node '${this.name}' attempt ${u}`);let l=s().config||{},g=l.agents||{},p=this.config.agent??g[this.name]??null,S={state:s()};p&&(S.preferredAgent=p);let y={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:d,config:l,nodeName:this.name,timeout:this.config?.timeout||3e5},$=e?._coreInvokeAgent;$||($=(await Promise.resolve().then(()=>(B(),H))).invokeAgent);let f=await $(n,S,y),w,k;if(typeof f=="string"?(w=f,k=null):f.structured?(w=f.raw||JSON.stringify(f.structured,null,2),k=f.structured):(w=f.raw||JSON.stringify(f,null,2),k=f.extracted||null),d)try{let m=we(d,this.name,"raw_stream_output.txt");Ot(At(m),{recursive:!0}),Se(m,typeof w=="string"?w:JSON.stringify(w),"utf-8")}catch(m){_.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&k){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(k,null,2)}`);let m=k;if(typeof this.onComplete=="function")try{m=await this.onComplete(s(),k)}catch(I){_.warn(`[workflow] onComplete hook failed: ${I.message}`)}return{success:!0,output:m,raw:w}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(s(),{raw:w}),raw:w}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(w);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),N.step("Output parsed"),{success:!0,output:m,raw:w}}return{success:!0,output:w,raw:w}}catch(l){h=l,u<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${u+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}},V=class extends R{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,t){let s=t&&typeof t.getAll=="function"?t.getAll():e;return{success:!0,output:{nextNode:this.condition(s)},raw:null}}};import{existsSync as et,readFileSync as Ct}from"node:fs";import{join as ye,dirname as tt}from"node:path";var K=class{static async loadContext(e,t,s={}){let i={},n=s.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=tt(ye(t,e));for(let c of n){let d=await this.findAndMergeContextFiles(c,a,t);if(d){let h=c.replace(/\.[^.]+$/,"").toLowerCase();i[h]=d}}}let r=s.discovery||{};for(let[a,c]of Object.entries(r))try{let d=ye(t,c);et(d)&&(i[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${c}': ${d.message}`)}return i}static async findAndMergeContextFiles(e,t,s){let i=[],n=t;for(;n.startsWith(s);){let r=ye(n,e);if(et(r))try{i.unshift(await this.loadFile(r))}catch(c){console.warn(`[workflow] could not load ${e} from ${r}: ${c.message}`)}let a=tt(n);if(a===n)break;n=a}return i.length===0?null:i.every(r=>typeof r=="string")?i.join(`
29
+ ${i}`);let a=s(),c=a.cwd||process.cwd(),l=a.sessionPath;try{if(l){let u=Te(l,R);if(nt(u)){let g=JSON.parse(st(u,"utf-8"));g.currentNode=this.name,$e(u,JSON.stringify(g,null,2),"utf-8")}let d=Te(l,"..",R);if(nt(d))try{let g=JSON.parse(st(d,"utf-8"));g.currentNode=this.name,$e(d,JSON.stringify(g,null,2),"utf-8")}catch{}}}catch(u){_.debug(`[workflow] could not update session info: ${u.message}`)}let h=null;for(let u=0;u<=this.retries;u++)try{_.debug(`[workflow] node '${this.name}' attempt ${u}`);let d=s().config||{},g=d.agents||{},m=this.config.agent??g[this.name]??null,S={state:s()};m&&(S.preferredAgent=m);let w={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:l,config:d,nodeName:this.name,timeout:this.config?.timeout||3e5},f=e?._coreInvokeAgent;f||(f=(await Promise.resolve().then(()=>(Y(),X))).invokeAgent);let I=await f(i,S,w),E,A;if(typeof I=="string"?(E=I,A=null):I.structured?(E=I.raw||JSON.stringify(I.structured,null,2),A=I.structured):(E=I.raw||JSON.stringify(I,null,2),A=I.extracted||null),l)try{let p=Te(l,this.name,"raw_stream_output.txt");Lt(Bt(p),{recursive:!0}),$e(p,typeof E=="string"?E:JSON.stringify(E),"utf-8")}catch(p){_.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&A){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(A,null,2)}`);let p=A;if(typeof this.onComplete=="function")try{p=await this.onComplete(s(),A)}catch(F){_.warn(`[workflow] onComplete hook failed: ${F.message}`)}return{success:!0,output:p,raw:E}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(s(),{raw:E}),raw:E}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(E);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),T.step("Output parsed"),{success:!0,output:p,raw:E}}return{success:!0,output:E,raw:E}}catch(d){h=d,u<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${u+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}},Q=class extends L{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,t){let s=t&&typeof t.getAll=="function"?t.getAll():e;return{success:!0,output:{nextNode:this.condition(s)},raw:null}}};import{existsSync as it,readFileSync as Ft}from"node:fs";import{join as Ie,dirname as at}from"node:path";var ee=class{static async loadContext(e,t,s={}){let n={},i=s.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=at(Ie(t,e));for(let c of i){let l=await this.findAndMergeContextFiles(c,a,t);if(l){let h=c.replace(/\.[^.]+$/,"").toLowerCase();n[h]=l}}}let r=s.discovery||{};for(let[a,c]of Object.entries(r))try{let l=Ie(t,c);it(l)&&(n[a]=await this.loadFile(l))}catch(l){console.warn(`[workflow] could not load context '${a}' from '${c}': ${l.message}`)}return n}static async findAndMergeContextFiles(e,t,s){let n=[],i=t;for(;i.startsWith(s);){let r=Ie(i,e);if(it(r))try{n.unshift(await this.loadFile(r))}catch(c){console.warn(`[workflow] could not load ${e} from ${r}: ${c.message}`)}let a=at(i);if(a===i)break;i=a}return n.length===0?null:n.every(r=>typeof r=="string")?n.join(`
30
30
 
31
31
  ---
32
32
 
33
- `):i.every(r=>typeof r=="object")?Object.assign({},...i):i[i.length-1]}static async loadFile(e){let t=Ct(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:s}=await import("url"),i=await import(s(e).href);return i.default||i}return t}};import{mkdirSync as rt,existsSync as _e,writeFileSync as ot,unlinkSync as bt}from"node:fs";import{join as W,resolve as nt}from"node:path";import{config as Pt}from"dotenv";import{zodToJsonSchema as st}from"zod-to-json-schema";import Rt from"handlebars";function Wt({traceFrom:o,sessionId:e,sessionPath:t,idSource:s,mkdirFresh:i}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let r=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${o} pid=${process.pid} ppid=${r} sessionId=${e} source=${s} mkdir=${i?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let h=(new Error("session trace").stack||"").split(`
33
+ `):n.every(r=>typeof r=="object")?Object.assign({},...n):n[n.length-1]}static async loadFile(e){let t=Ft(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:s}=await import("url"),n=await import(s(e).href);return n.default||n}return t}};import{mkdirSync as dt,existsSync as Ne,writeFileSync as ct,unlinkSync as Mt}from"node:fs";import{join as B,resolve as ut}from"node:path";import{config as Dt}from"dotenv";import{zodToJsonSchema as lt}from"zod-to-json-schema";import jt from"handlebars";function Gt({traceFrom:o,sessionId:e,sessionPath:t,idSource:s,mkdirFresh:n}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let r=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${o} pid=${process.pid} ppid=${r} sessionId=${e} source=${s} mkdir=${n?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let h=(new Error("session trace").stack||"").split(`
34
34
  `).slice(2,14).join(`
35
35
  `);console.log(`[zibby:session] stack (${o}):
36
- ${h}`)}}function it(){return process.env.ZIBBY_RUN_SOURCE==="studio"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function at(){if(process.env.ZIBBY_RUN_SOURCE!=="studio")return;let o=process.env.ZIBBY_SESSION_PATH;if(!(o==null||String(o).trim()===""))try{return nt(String(o).trim())}catch{return String(o).trim()}}function ct(){it()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function dt({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function lt(o={}){let e=pe.map(n=>process.env[n]).find(Boolean),t=Math.random().toString(36).slice(2,6),s=e||`${Date.now()}_${t}`,i=o.paths?.sessionPrefix;return i?`${i}_${s}`:s}function ut({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:s="resolveWorkflowSession"}={}){let i=t.sessionPath,n=t.sessionTimestamp,r="initialState.sessionPath";if(!i&&process.env.ZIBBY_SESSION_PATH)try{let d=nt(String(process.env.ZIBBY_SESSION_PATH));d&&(i=d,r="ZIBBY_SESSION_PATH")}catch{}let a;if(i)a=String(i).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=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 u=e.sessionId!=null?String(e.sessionId).trim():"";u&&u!=="last"?(a=u,r="config.sessionId"):(a=lt(e),r="generated")}n=n??Date.now();let h=e.paths?.output||Y;i=W(o,h,le,a)}let c=!_e(i);return c&&rt(i,{recursive:!0}),(c||r!=="initialState.sessionPath")&&Wt({traceFrom:s,sessionId:a,sessionPath:i,idSource:r,mkdirFresh:c}),dt({sessionPath:i,sessionId:a}),{sessionPath:i,sessionId:a,sessionTimestamp:n}}var z=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.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null}setStateSchema(e){return this.stateSchema=e,this}getStateSchema(){return this.stateSchema}addNode(e,t,s={}){let i=t instanceof R?t:new R(t);return i.name=e,this.nodes.set(e,i),s.prompt&&this.nodePrompts.set(e,s.prompt),Object.keys(s).length>0&&this.nodeOptions.set(e,s),this}addConditionalNode(e,t){return this.nodes.set(e,new V({...t,name:e})),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:s}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:s}),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,s,i,n){let r=s;for(let a=e.length-1;a>=0;a--){let c=e[a],d=r;r=()=>c(t,d,i,n)}return r()}serialize(){let e=[],t={};for(let[n,r]of this.nodes){let a=this.nodeTypeMap.get(n)||n;e.push({id:n,type:a,data:{nodeType:a,label:n}});let c={};r._isCustomCode&&typeof r.execute=="function"&&(c.customCode=r.execute.toString());let d=this.nodePrompts.get(n);if(d&&(c.prompt=d),typeof r.customExecute=="function"&&(c.executeCode=r.customExecute.toString()),r.outputSchema)try{if(typeof r.outputSchema._def<"u"){let u=st(r.outputSchema,{target:"openApi3"});c.outputSchema={jsonSchema:u,variables:this._flattenJsonSchemaToVariables(u)}}else c.outputSchema={schema:r.outputSchema}}catch(u){console.warn(`[workflow] failed to convert schema for ${n}:`,u.message)}let h=(this.resolvedToolsMap||{})[n];h?.toolIds&&(c.tools=h.toolIds),Object.keys(c).length>0&&(t[n]=c)}let s=[];for(let[n,r]of this.edges)if(typeof r=="string")s.push({source:n,target:r});else if(r.conditional){let a=this.conditionalCodeMap.get(n)||r.routes.toString(),c=this._inferConditionalTargets(r.routes),d=r.labels||{};for(let h of c){let u={source:n,target:h,data:{conditionalCode:a}};d[h]&&(u.label=d[h]),s.push(u)}}let i=null;if(this.stateSchema)try{i=st(this.stateSchema,{target:"openApi3"})}catch{i=this.stateSchema}return{nodes:e,edges:s,nodeConfigs:t,stateSchema:i}}_inferConditionalTargets(e){let t=e.toString(),s=new Set,i=/return\s+['"]([^'"]+)['"]/g,n;for(;(n=i.exec(t))!==null;)s.add(n[1]);return[...s]}_flattenJsonSchemaToVariables(e,t=""){let s=e;if(e.$ref&&e.definitions){let i=e.$ref.replace("#/definitions/","");s=e.definitions[i]||e}return this._flattenSchema(s,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let s=[],i=e.properties||{},n=e.required||[];for(let[r,a]of Object.entries(i)){let c=t?`${t}.${r}`:r;s.push({path:c,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!n.includes(r)}),a.type==="object"&&a.properties&&s.push(...this._flattenSchema(a,c)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&s.push(...this._flattenSchema(a.items,`${c}[]`))}return s}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let s=[];t.success!==void 0&&s.push(`Result: ${t.success?"passed":"failed"}`);for(let[i,n]of Object.entries(t))if(!(i==="success"||i==="raw"||i==="nextNode")){if(typeof n=="string"&&n.length<=80)s.push(`${i}: ${n}`);else if(Array.isArray(n)){let r=n.length,a=n.filter(d=>d?.passed===!0).length,c=n.some(d=>d?.passed!==void 0);s.push(c?`${i}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${i}: ${r} items`)}if(s.length>=4)break}return s}async run(e,t={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let s=t.cwd||process.cwd();Pt({path:W(s,".env")});let i=t.config||{};if(!i||Object.keys(i).length===0)try{let m=W(s,".zibby.config.js");_e(m)&&(i=(await import(m)).default||{})}catch{}process.env.EXECUTION_ID&&!i.agent?.strictMode&&(i.agent={...i.agent,strictMode:!0});let n=t.agentType;if(!n){let m=i?.agent;m?.provider?n=m.provider:m?.gemini?n="gemini":m?.claude?n="claude":m?.cursor?n="cursor":m?.codex?n="codex":n=process.env.AGENT_TYPE||"cursor"}let r=t.contextConfig||e?.config?.contextConfig||e?.config?.context||i?.context||{};if(this.stateSchema){let m=this.stateSchema.safeParse(t);if(!m.success){let I=m.error.issues.map(x=>`${x.path.join(".")}: ${x.message}`);throw console.error("\u274C Initial state validation failed:"),I.forEach(x=>console.error(` - ${x}`)),new Error(`State validation failed: ${I.join(", ")}`)}N.step("State validated against schema")}let a=at(),c=t.sessionPath||a;c||ct();let{sessionPath:d,sessionTimestamp:h,sessionId:u}=ut({cwd:s,config:i,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});N.step(`Session ${u}`);let l=await K.loadContext(t.specPath||"",s,r);Object.keys(l).length>0&&N.step(`Context loaded: ${Object.keys(l).join(", ")}`);let g=t.outputPath;!g&&t.specPath&&(e?.calculateOutputPath?g=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let p=new j({...t,config:i,agentType:n,outputPath:g,sessionPath:d,sessionTimestamp:h,context:l,resolvedTools:this.resolvedToolsMap||{}}),S=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(J(),Ve)),$=new Set;for(let[,m]of this.nodes)for(let I of m.config?.skills||[])$.add(I);for(let m of $){let I=y(m);if(typeof I?.middleware=="function")try{let x=await I.middleware();typeof x=="function"&&S.set(m,x)}catch{}}let f=this.entryPoint,w=[];for(;f&&f!=="END";){let m=W(d,ue);if(_e(m)){console.warn(`
37
- \u{1F6D1} Studio stop requested \u2014 ending workflow.`);try{bt(m)}catch{}if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return N.step("Workflow stopped by Studio"),{success:!0,state:p.getAll(),executionLog:w,stoppedByStudio:!0}}let I=this.nodes.get(f);if(!I)throw new Error(`Node '${f}' not found in graph`);let x=JSON.stringify({sessionPath:d,sessionTimestamp:h,currentNode:f,createdAt:new Date().toISOString(),config:p.get("config")}),mt=W(d,b);ot(mt,x,"utf-8");let Te=p.get("config")?.paths?.output||Y,gt=W(s,Te,b);rt(W(s,Te),{recursive:!0});try{ot(gt,x,"utf-8")}catch{}let ve=t.onPipelineProgress;if(typeof ve=="function")try{ve({cwd:s,sessionPath:d,sessionId:u,outputBase:p.get("config")?.paths?.output||Y,currentNode:f})}catch{}let St=(this.resolvedToolsMap||{})[f]||null;p.set("_currentNodeTools",St);let wt=p.get("nodeConfigs")||{};p.set("_currentNodeConfig",wt[f]||{}),N.nodeStart(f);let ke=Date.now(),X=this.nodePrompts.get(f);if(!this._invokeAgent){let O=await Promise.resolve().then(()=>(B(),H));this._invokeAgent=O.invokeAgent}let xe=this._invokeAgent,Oe={state:p,invokeAgent:async(O={},A={})=>{let T=A.prompt||"";if(X)try{T=Rt.compile(X,{noEscape:!0})(O)}catch(C){throw console.error(`\u274C Template rendering failed for node '${f}':`,C.message),new Error(`Template rendering failed: ${C.message}`,{cause:C})}else if(!T)throw new Error(`No prompt template configured for node '${f}' and no prompt provided in options`);return xe(T,{state:p.getAll(),images:A.images||[]},{model:A.model||p.get("model"),workspace:p.get("workspace"),schema:A.schema,...A})},_coreInvokeAgent:xe,agent:e,nodeId:f,promptTemplate:X,getPromptTemplate:()=>X,...p.getAll()};try{let O=(I.config?.skills||[]).map(M=>S.get(M)).filter(Boolean),A=[...this.middleware,...O],T;A.length>0?T=await this._composeMiddleware(A,f,async()=>I.execute(Oe,p),p.getAll(),p):T=await I.execute(Oe,p);let C=Date.now()-ke;if(w.push({node:f,success:T.success,duration:C,timestamp:new Date().toISOString()}),!T.success){if(String(T.error||"").includes("Stopped from Zibby Studio")){if(N.step("Workflow stopped by Studio"),p.set("stoppedByStudio",!0),e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return{success:!0,state:p.getAll(),executionLog:w,stoppedByStudio:!0}}p.append("errors",{node:f,error:T.error});let Ae=I.config?.retries||0,Ce=`${f}_retries`,ee=p.getAll()[Ce]||0;if(ee<Ae){N.stepInfo(`Retrying (attempt ${ee+1}/${Ae})`),p.update({[Ce]:ee+1,[`${f}_raw`]:T.raw});continue}throw N.nodeFailed(f,T.error,{duration:C}),new Error(`Node '${f}' failed after ${ee} attempts: ${T.error}`)}p.update({[f]:T.output});let yt=this._summarizeNodeOutput(f,T.output);N.nodeComplete(f,{duration:C,details:yt});let Q=this.edges.get(f);if(!Q)f="END";else if(Q.conditional){let M=Q.routes(p.getAll());N.route(f,M),f=M}else f=Q}catch(O){throw N.isInsideNode&&N.nodeFailed(f,O.message,{duration:Date.now()-ke}),p.set("failed",!0),p.set("failedAt",f),O}}N.graphComplete();let k={success:!0,state:p.getAll(),executionLog:w};return e&&typeof e.onComplete=="function"&&await e.onComplete(k),k}};var q=new Map;function pt(o,e){q.set(o,e)}function $e(o){return q.get(o)}function se(o){return q.has(o)}function Lt(){return Array.from(q.keys())}function Ee(o){let e=q.get(o);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}pt("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let s=t?._coreInvokeAgent;s||(s=(await Promise.resolve().then(()=>(B(),H))).invokeAgent);let i=e.extraPromptInstructions||"Execute the task based on the current state.",n=Dt(i,t),r=await s(n,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:r,nodeId:o},raw:typeof r=="string"?r:r.raw}}})});function Dt(o,e){let t=/@([\w.]+)/g,s=new Set,i;for(;(i=t.exec(o))!==null;)s.add(i[1]);if(s.size===0)return o;let n=[],r=new Set;for(let a of s){let c=a.split(".")[0];if(r.has(c))continue;let d=a.split(".").reduce((l,g)=>l?.[g],e);if(d===void 0)continue;let h=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),u=a.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase());n.push(`## ${u}
38
- ${h}`),a.includes(".")||r.add(c)}return n.length===0?o:`${o}
36
+ ${h}`)}}function pt(){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 ft(){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 ut(String(e).trim())}catch{return String(e).trim()}}function ht(){pt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function mt({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function gt(o={}){let e=ge.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),s=e||`${Date.now()}_${t}`,n=o.paths?.sessionPrefix;return n?`${n}_${s}`:s}function St({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:s="resolveWorkflowSession"}={}){let n=t.sessionPath,i=t.sessionTimestamp,r="initialState.sessionPath";if(!n&&process.env.ZIBBY_SESSION_PATH)try{let l=ut(String(process.env.ZIBBY_SESSION_PATH));l&&(n=l,r="ZIBBY_SESSION_PATH")}catch{}let a;if(n)a=String(n).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let l=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(l)a=l,r="ZIBBY_SESSION_ID";else{let u=e.sessionId!=null?String(e.sessionId).trim():"";u&&u!=="last"?(a=u,r="config.sessionId"):(a=gt(e),r="generated")}i=i??Date.now();let h=e.paths?.output||z;n=B(o,h,he,a)}let c=!Ne(n);return c&&dt(n,{recursive:!0}),(c||r!=="initialState.sessionPath")&&Gt({traceFrom:s,sessionId:a,sessionPath:n,idSource:r,mkdirFresh:c}),mt({sessionPath:n,sessionId:a}),{sessionPath:n,sessionId:a,sessionTimestamp:i}}var te=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setStateSchema(e){return this.stateSchema=e,this}getStateSchema(){return this.stateSchema}addNode(e,t,s={}){let n=t instanceof L?t:new L(t);return n.name=e,this.nodes.set(e,n),s.prompt&&this.nodePrompts.set(e,s.prompt),Object.keys(s).length>0&&this.nodeOptions.set(e,s),this}addConditionalNode(e,t){return this.nodes.set(e,new Q({...t,name:e})),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:s}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:s}),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,s,n,i){let r=s;for(let a=e.length-1;a>=0;a--){let c=e[a],l=r;r=()=>c(t,l,n,i)}return r()}serialize(){let e=[],t={};for(let[i,r]of this.nodes){let a=this.nodeTypeMap.get(i)||i;e.push({id:i,type:a,data:{nodeType:a,label:i}});let c={};r._isCustomCode&&typeof r.execute=="function"&&(c.customCode=r.execute.toString());let l=this.nodePrompts.get(i);if(l&&(c.prompt=l),typeof r.customExecute=="function"&&(c.executeCode=r.customExecute.toString()),r.outputSchema)try{if(typeof r.outputSchema._def<"u"){let u=lt(r.outputSchema,{target:"openApi3"});c.outputSchema={jsonSchema:u,variables:this._flattenJsonSchemaToVariables(u)}}else c.outputSchema={schema:r.outputSchema}}catch(u){console.warn(`[workflow] failed to convert schema for ${i}:`,u.message)}let h=(this.resolvedToolsMap||{})[i];h?.toolIds&&(c.tools=h.toolIds),Object.keys(c).length>0&&(t[i]=c)}let s=[];for(let[i,r]of this.edges)if(typeof r=="string")s.push({source:i,target:r});else if(r.conditional){let a=this.conditionalCodeMap.get(i)||r.routes.toString(),c=this._inferConditionalTargets(r.routes),l=r.labels||{};for(let h of c){let u={source:i,target:h,data:{conditionalCode:a}};l[h]&&(u.label=l[h]),s.push(u)}}let n=null;if(this.stateSchema)try{n=lt(this.stateSchema,{target:"openApi3"})}catch{n=this.stateSchema}return{nodes:e,edges:s,nodeConfigs:t,stateSchema:n}}_inferConditionalTargets(e){let t=e.toString(),s=new Set,n=/return\s+['"]([^'"]+)['"]/g,i;for(;(i=n.exec(t))!==null;)s.add(i[1]);return[...s]}_flattenJsonSchemaToVariables(e,t=""){let s=e;if(e.$ref&&e.definitions){let n=e.$ref.replace("#/definitions/","");s=e.definitions[n]||e}return this._flattenSchema(s,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let s=[],n=e.properties||{},i=e.required||[];for(let[r,a]of Object.entries(n)){let c=t?`${t}.${r}`:r;s.push({path:c,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!i.includes(r)}),a.type==="object"&&a.properties&&s.push(...this._flattenSchema(a,c)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&s.push(...this._flattenSchema(a.items,`${c}[]`))}return s}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let s=[];t.success!==void 0&&s.push(`Result: ${t.success?"passed":"failed"}`);for(let[n,i]of Object.entries(t))if(!(n==="success"||n==="raw"||n==="nextNode")){if(typeof i=="string"&&i.length<=80)s.push(`${n}: ${i}`);else if(Array.isArray(i)){let r=i.length,a=i.filter(l=>l?.passed===!0).length,c=i.some(l=>l?.passed!==void 0);s.push(c?`${n}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${n}: ${r} items`)}if(s.length>=4)break}return s}async run(e,t={},s={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let n=new AbortController;s.signal&&(s.signal.aborted?n.abort():s.signal.addEventListener("abort",()=>n.abort(),{once:!0}));let i=s.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();Dt({path:B(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let y=B(r,".zibby.config.js");Ne(y)&&(a=(await import(y)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let c=t.agentType;if(!c){let y=a?.agent;y?.provider?c=y.provider:y?.gemini?c="gemini":y?.claude?c="claude":y?.cursor?c="cursor":y?.codex?c="codex":c=process.env.AGENT_TYPE||"cursor"}let l=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{};if(this.stateSchema){let y=this.stateSchema.safeParse(t);if(!y.success){let x=y.error.issues.map(v=>`${v.path.join(".")}: ${v.message}`);throw console.error("\u274C Initial state validation failed:"),x.forEach(v=>console.error(` - ${v}`)),new Error(`State validation failed: ${x.join(", ")}`)}T.step("State validated against schema")}let h=ft(),u=t.sessionPath||h;u||ht();let{sessionPath:d,sessionTimestamp:g,sessionId:m}=St({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:u,sessionTimestamp:t.sessionTimestamp}});T.step(`Session ${m}`);let S=await ee.loadContext(t.specPath||"",r,l);Object.keys(S).length>0&&T.step(`Context loaded: ${Object.keys(S).join(", ")}`);let w=t.outputPath;!w&&t.specPath&&(e?.calculateOutputPath?w=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new J({...t,config:a,agentType:c,outputPath:w,sessionPath:d,sessionTimestamp:g,context:S,resolvedTools:this.resolvedToolsMap||{},_signal:n.signal}),I=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:E}=await Promise.resolve().then(()=>(q(),et)),A=new Set;for(let[,y]of this.nodes)for(let x of y.config?.skills||[])A.add(x);for(let y of A){let x=E(y);if(typeof x?.middleware=="function")try{let v=await x.middleware();typeof v=="function"&&I.set(y,v)}catch{}}let p=this.entryPoint,F=[],Oe=a?.recursionLimit??100,Et=0;try{for(;p&&p!=="END";){if(++Et>Oe)throw new Error(`Workflow exceeded recursion limit (${Oe}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let x=B(d,me);if(Ne(x)){try{Mt(x)}catch{}n.abort()}if(n.signal.aborted)return console.warn(`
37
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),T.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:F,stoppedExternally:!0};let v=this.nodes.get(p);if(!v)throw new Error(`Node '${p}' not found in graph`);let Ce=JSON.stringify({sessionPath:d,sessionTimestamp:g,currentNode:p,createdAt:new Date().toISOString(),config:f.get("config")}),$t=B(d,R);ct($t,Ce,"utf-8");let Pe=f.get("config")?.paths?.output||z,Tt=B(r,Pe,R);dt(B(r,Pe),{recursive:!0});try{ct(Tt,Ce,"utf-8")}catch{}let Re=t.onPipelineProgress;if(typeof Re=="function")try{Re({cwd:r,sessionPath:d,sessionId:m,outputBase:f.get("config")?.paths?.output||z,currentNode:p})}catch{}let It=(this.resolvedToolsMap||{})[p]||null;f.set("_currentNodeTools",It);let Nt=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Nt[p]||{}),T.nodeStart(p);let We=Date.now(),re=this.nodePrompts.get(p);if(!this._invokeAgent){let O=await Promise.resolve().then(()=>(Y(),X));this._invokeAgent=O.invokeAgent}let vt=this._invokeAgent,Le=async(O,C,N={})=>{let k=vt(O,C,{...N,signal:n.signal});return k.catch(()=>{}),n.signal.aborted?k:Promise.race([k,new Promise((M,D)=>{let P=()=>{setTimeout(()=>{let Z=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);Z.name="AbortError",D(Z)},i)};n.signal.addEventListener("abort",P,{once:!0})})])},Be={state:f,invokeAgent:async(O={},C={})=>{let N=C.prompt||"";if(re){let k=this._compiledPrompts.get(p);k||(k=jt.compile(re,{noEscape:!0}),this._compiledPrompts.set(p,k));try{N=k(O)}catch(M){throw console.error(`\u274C Template rendering failed for node '${p}':`,M.message),new Error(`Template rendering failed: ${M.message}`,{cause:M})}}else if(!N)throw new Error(`No prompt template configured for node '${p}' and no prompt provided in options`);return Le(N,{state:f.getAll(),images:C.images||[]},{model:C.model||f.get("model"),workspace:f.get("workspace"),schema:C.schema,...C,signal:n.signal})},_coreInvokeAgent:Le,agent:e,nodeId:p,promptTemplate:re,getPromptTemplate:()=>re,...f.getAll()};try{let O=(v.config?.skills||[]).map(P=>I.get(P)).filter(Boolean),C=[...this.middleware,...O],N;C.length>0?N=await this._composeMiddleware(C,p,async()=>v.execute(Be,f),f.getAll(),f):N=await v.execute(Be,f);let k=Date.now()-We;if(F.push({node:p,success:N.success,duration:k,timestamp:new Date().toISOString()}),!N.success){if(n.signal.aborted)return T.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:F,stoppedExternally:!0};f.append("errors",{node:p,error:N.error});let P=v.config?.retries||0,Z=`${p}_retries`,se=f.getAll()[Z]||0;if(se<P){T.stepInfo(`Retrying (attempt ${se+1}/${P})`),f.update({[Z]:se+1,[`${p}_raw`]:N.raw});continue}throw T.nodeFailed(p,N.error,{duration:k}),new Error(`Node '${p}' failed after ${se} attempts: ${N.error}`)}f.update({[p]:N.output});let M=this._summarizeNodeOutput(p,N.output);T.nodeComplete(p,{duration:k,details:M});let D=this.edges.get(p);if(!D)p="END";else if(D.conditional){let P=D.routes(f.getAll());T.route(p,P),p=P}else p=D}catch(O){throw T.isInsideNode&&T.nodeFailed(p,O.message,{duration:Date.now()-We}),f.set("failed",!0),f.set("failedAt",p),O}}T.graphComplete();let y={success:!0,state:f.getAll(),executionLog:F};return e&&typeof e.onComplete=="function"&&await e.onComplete(y),y}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(y){console.warn(`[workflow] agent.cleanup() failed: ${y.message}`)}}}};var ve=Symbol.for("@zibby/agent-workflow.nodes");globalThis[ve]||(globalThis[ve]=new Map);var oe=globalThis[ve];function wt(o,e){oe.set(o,e)}function ke(o){return oe.get(o)}function ae(o){return oe.has(o)}function Ut(){return Array.from(oe.keys())}function xe(o){let e=oe.get(o);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}wt("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let s=t?._coreInvokeAgent;s||(s=(await Promise.resolve().then(()=>(Y(),X))).invokeAgent);let n=e.extraPromptInstructions||"Execute the task based on the current state.",i=Yt(n,t),r=await s(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:r,nodeId:o},raw:typeof r=="string"?r:r.raw}}})});function Yt(o,e){let t=/@([\w.]+)/g,s=new Set,n;for(;(n=t.exec(o))!==null;)s.add(n[1]);if(s.size===0)return o;let i=[],r=new Set;for(let a of s){let c=a.split(".")[0];if(r.has(c))continue;let l=a.split(".").reduce((d,g)=>d?.[g],e);if(l===void 0)continue;let h=typeof l=="string"?l:l?.raw??JSON.stringify(l,null,2),u=a.replace(/_/g," ").replace(/\b\w/g,d=>d.toUpperCase());i.push(`## ${u}
38
+ ${h}`),a.includes(".")||r.add(c)}return i.length===0?o:`${o}
39
39
 
40
40
  ---
41
41
  # Referenced Context
42
42
 
43
- ${n.join(`
43
+ ${i.join(`
44
44
 
45
- `)}`}J();L();var re={};function Ie(o,e){if(Array.isArray(e))return Ne(e);let t=re[o];return!t||t.length===0?null:Ne(t)}function Ne(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},s=[];for(let i of o){let n=F(i);if(!n){_.warn(`[workflow] unknown skill "${i}" \u2014 skipping`);continue}s.push(i);for(let r of n.tools||[])e.push({name:r.name,description:r.description,input_schema:r.input_schema||{type:"object",properties:{}}});if(!t[n.serverName])if(typeof n.resolve=="function"){let r=n.resolve();r&&(t[n.serverName]={...r,toolPrefix:i})}else{let r={};for(let a of n.envKeys||[]){let c=process.env[a];c&&(r[a]=c)}t[n.serverName]={command:n.command,args:[...n.args||[]],env:r,toolPrefix:i}}}return s.length===0?null:{toolIds:s,claudeTools:e,mcpServers:t}}L();function Ft(o,e={}){let{nodes:t,edges:s,nodeConfigs:i={}}=o;if(!Array.isArray(t)||t.length===0)throw new v("Graph must have at least one node");if(!Array.isArray(s))throw new v("Graph edges must be an array");let n=new z(e);e.stateSchema&&n.setStateSchema(e.stateSchema);let r=new Set,a=new Map,c={};for(let l of t){let g=ne(l);a.set(l.id,{...l,resolvedType:g}),g==="decision"&&r.add(l.id)}for(let[l,g]of a){if(r.has(l))continue;let p=g.resolvedType,S=i[l]||{},y=Ie(p,S.tools);y&&(c[l]=y);let $={};S.prompt&&($.prompt=S.prompt);let f=se(p);if(_.debug(`[workflow] compiler: node "${l}" type="${p}" registered=${f}`),S.customCode&&!f)n.addNode(l,ft(l,S.customCode,S),$),n.setNodeType(l,p);else if(f){let w=$e(p);w.factory?n.addNode(l,w.create(l,{...S,resolvedTools:y}),$):n.addNode(l,w,$),n.setNodeType(l,p)}else if(S.executeCode)n.addNode(l,ft(l,S.executeCode,S),$),n.setNodeType(l,p);else throw new v(`Unknown node type "${p}" for node "${l}". Did you forget to register it?`)}n.resolvedToolsMap=c;let d=new Set;for(let l of s)r.has(l.target)||d.add(l.target);let h=t.find(l=>!r.has(l.id)&&!d.has(l.id));if(!h)throw new v("Could not determine entry point: no node without incoming edges found");n.setEntryPoint(h.id);let u=jt(s,"source");for(let l of s)if(!r.has(l.source))if(r.has(l.target)){let g=l.target,p=u.get(g)||[];if(p.length===0)throw new v(`Decision node "${g}" has no outgoing edges`);let S=Ut(g,p,r);n.addConditionalEdges(l.source,S)}else n.addEdge(l.source,l.target);return n}function Bt(o){let e=[];if(!o||typeof o!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(o.nodes)||o.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(o.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=o.nodeConfigs||{};for(let a of o.nodes){let c=ne(a);if(c==="decision"||se(c))continue;let d=t[a.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${c}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let s=new Set(o.nodes.map(a=>a.id));for(let a of o.edges)s.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),s.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let i=new Set(o.nodes.filter(a=>ne(a)==="decision").map(a=>a.id)),n=new Set;for(let a of o.edges)i.has(a.target)||n.add(a.target);let r=o.nodes.filter(a=>!i.has(a.id)&&!n.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 i){let c=o.edges.filter(h=>h.source===a);c.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),c.some(h=>h.data?.conditionalCode||h.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Mt(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>ne(e)!=="decision").map(e=>e.id)}function ne(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function jt(o,e){let t=new Map;for(let s of o){let i=s[e];t.has(i)||t.set(i,[]),t.get(i).push(s)}return t}function Ut(o,e,t){let s=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!s)throw new v(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let i=s.data?.conditionalCode||s.conditionalCode,n=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),r;try{let c=new Function(`return (${i})`)();r=d=>{let h=c(d);return n.has(h)||_.warn(`[workflow] conditional route from "${o}" returned "${h}" which is not in valid targets: ${[...n].join(", ")}`),h}}catch(a){throw new v(`Failed to compile conditionalCode for "${o}": ${a.message}`)}return r}function ft(o,e,t={}){let s;try{s=new Function("invokeAgent","require","console",`return (${e})`)}catch(r){throw new v(`Failed to compile customCode for node "${o}": ${r.message}`)}let i=s(async(...r)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(B(),H));return a(...r)},typeof ie<"u"?ie:void 0,console),n=null;return t.outputSchema&&(n=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:n,execute:async r=>{try{let a=await i(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 v=class extends Error{constructor(e){super(e),this.name="CompilationError"}};J();he();B();function Gt(o,e={}){let{nodes:t,edges:s,nodeConfigs:i={}}=o,n=new Set,r=[],a=new Map;for(let y of t){let $=y.data?.nodeType||y.type;a.set(y.id,$),$==="decision"?n.add(y.id):r.push({id:y.id,nodeType:$,label:y.data?.label||y.id})}let c=r.some(y=>{let $=i[y.id]||{};return!$.customCode&&!$.executeCode}),{toolsPerNode:d,toolIdsByVar:h}=qt(r,i),{simpleEdges:u,conditionalEdges:l}=Xt(s,n),g=Qt(r,s,n),p=[],S=e.workflowType||"workflow";return p.push(Yt(e)),p.push(Jt(S,{usesRegisteredNodes:c})),p.push(Ht(h)),p.push(Vt(S)),p.push(Kt(r,i)),p.push(zt(r,g,u,l,d,S)),p.filter(Boolean).join(`
46
- `)}function Zt(o){let e={};for(let[t,s]of Object.entries(o)){let{tools:i,...n}=s;Object.keys(n).length>0&&(e[t]=n)}return e}function Yt(o){let e=o.workflowType||"workflow";return["// Generated workflow",`// ${o.projectId?`Project: ${o.projectId} | `:""}Type: ${e} | Version: ${o.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
47
- `)}function Jt(o,{usesRegisteredNodes:e=!0}={}){let t=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return e&&t.push("// import './register-nodes.js'; // register custom node types here"),t.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),t.join(`
48
- `)}function Ht(o){if(o.size===0)return"";let e=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];for(let[t,s]of o)e.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(s)}); // ${s.join(", ")}`);return e.push(""),e.join(`
49
- `)}function Vt(o){return["// \u2500\u2500 Node Configs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","const __filename = fileURLToPath(import.meta.url);","const __dirname = dirname(__filename);",`const configPath = join(__dirname, 'workflow-${o}.config.json');`,"const nodeConfigs = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')) : {};",""].join(`
50
- `)}function Kt(o,e){let t=["// \u2500\u2500 Node Implementations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",""];for(let s of o){let i=ht(s.id),n=e[s.id]?.customCode;if(n)t.push(`// @custom \u2014 modified from default "${s.nodeType}" template`),t.push(`const ${i}_execute = ${n};`);else{let r=Ee(s.nodeType);r?(t.push(`// Default "${s.nodeType}" implementation`),t.push(`const ${i}_execute = ${r};`)):(t.push(`// No template for "${s.nodeType}" \u2014 passthrough`),t.push(`const ${i}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}t.push("")}return t.join(`
51
- `)}function zt(o,e,t,s,i,n){let r=["// \u2500\u2500 Graph Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];r.push("export function buildGraph(options = {}) {"),r.push(" const graph = new WorkflowGraph(options);",""),r.push(" // Nodes");for(let c of o){let d=ht(c.id);r.push(` graph.addNode('${c.id}', { name: '${c.id}', execute: ${d}_execute });`),r.push(` graph.setNodeType('${c.id}', '${c.nodeType}');`)}r.push("",` graph.setEntryPoint('${e}');`,""),(t.length>0||s.length>0)&&r.push(" // Edges");for(let c of t)r.push(` graph.addEdge('${c.source}', '${c.target}');`);for(let c of s){let d=c.code.split(`
45
+ `)}`}q();j();var ce={};function Ae(o,e){if(Array.isArray(e))return be(e);let t=ce[o];return!t||t.length===0?null:be(t)}function be(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},s=[];for(let n of o){let i=U(n);if(!i){_.warn(`[workflow] unknown skill "${n}" \u2014 skipping`);continue}s.push(n);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:n})}else{let r={};for(let a of i.envKeys||[]){let c=process.env[a];c&&(r[a]=c)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:r,toolPrefix:n}}}return s.length===0?null:{toolIds:s,claudeTools:e,mcpServers:t}}j();function Zt(o,e={}){let{nodes:t,edges:s,nodeConfigs:n={}}=o;if(!Array.isArray(t)||t.length===0)throw new b("Graph must have at least one node");if(!Array.isArray(s))throw new b("Graph edges must be an array");let i=new te(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let r=new Set,a=new Map,c={};for(let d of t){let g=le(d);a.set(d.id,{...d,resolvedType:g}),g==="decision"&&r.add(d.id)}for(let[d,g]of a){if(r.has(d))continue;let m=g.resolvedType,S=n[d]||{},w=Ae(m,S.tools);w&&(c[d]=w);let f={};S.prompt&&(f.prompt=S.prompt);let I=ae(m);if(_.debug(`[workflow] compiler: node "${d}" type="${m}" registered=${I}`),S.customCode&&!I)i.addNode(d,yt(d,S.customCode,S),f),i.setNodeType(d,m);else if(I){let E=ke(m);E.factory?i.addNode(d,E.create(d,{...S,resolvedTools:w}),f):i.addNode(d,E,f),i.setNodeType(d,m)}else if(S.executeCode)i.addNode(d,yt(d,S.executeCode,S),f),i.setNodeType(d,m);else throw new b(`Unknown node type "${m}" for node "${d}". Did you forget to register it?`)}i.resolvedToolsMap=c;let l=new Set;for(let d of s)r.has(d.target)||l.add(d.target);let h=t.find(d=>!r.has(d.id)&&!l.has(d.id));if(!h)throw new b("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(h.id);let u=Kt(s,"source");for(let d of s)if(!r.has(d.source))if(r.has(d.target)){let g=d.target,m=u.get(g)||[];if(m.length===0)throw new b(`Decision node "${g}" has no outgoing edges`);let S=Vt(g,m,r);i.addConditionalEdges(d.source,S)}else i.addEdge(d.source,d.target);return i}function Jt(o){let e=[];if(!o||typeof o!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(o.nodes)||o.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(o.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=o.nodeConfigs||{};for(let a of o.nodes){let c=le(a);if(c==="decision"||ae(c))continue;let l=t[a.id]||{};l.customCode||l.executeCode||e.push(`Unknown node type "${c}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let s=new Set(o.nodes.map(a=>a.id));for(let a of o.edges)s.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),s.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let n=new Set(o.nodes.filter(a=>le(a)==="decision").map(a=>a.id)),i=new Set;for(let a of o.edges)n.has(a.target)||i.add(a.target);let r=o.nodes.filter(a=>!n.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 n){let c=o.edges.filter(h=>h.source===a);c.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),c.some(h=>h.data?.conditionalCode||h.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Ht(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>le(e)!=="decision").map(e=>e.id)}function le(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function Kt(o,e){let t=new Map;for(let s of o){let n=s[e];t.has(n)||t.set(n,[]),t.get(n).push(s)}return t}function Vt(o,e,t){let s=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!s)throw new b(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let n=s.data?.conditionalCode||s.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),r;try{let c=new Function(`return (${n})`)();r=l=>{let h=c(l);return i.has(h)||_.warn(`[workflow] conditional route from "${o}" returned "${h}" which is not in valid targets: ${[...i].join(", ")}`),h}}catch(a){throw new b(`Failed to compile conditionalCode for "${o}": ${a.message}`)}return r}function yt(o,e,t={}){let s;try{s=new Function("invokeAgent","require","console",`return (${e})`)}catch(r){throw new b(`Failed to compile customCode for node "${o}": ${r.message}`)}let n=s(async(...r)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(Y(),X));return a(...r)},typeof de<"u"?de:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:i,execute:async r=>{try{let a=await n(r);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var b=class extends Error{constructor(e){super(e),this.name="CompilationError"}};q();we();Y();function zt(o,e={}){let{nodes:t,edges:s,nodeConfigs:n={}}=o,i=new Set,r=[],a=new Map;for(let w of t){let f=w.data?.nodeType||w.type;a.set(w.id,f),f==="decision"?i.add(w.id):r.push({id:w.id,nodeType:f,label:w.data?.label||w.id})}let c=r.some(w=>{let f=n[w.id]||{};return!f.customCode&&!f.executeCode}),{toolsPerNode:l,toolIdsByVar:h}=so(r,n),{simpleEdges:u,conditionalEdges:d}=no(s,i),g=io(r,s,i),m=[],S=e.workflowType||"workflow";return m.push(Xt(e)),m.push(Qt(S,{usesRegisteredNodes:c})),m.push(eo(h)),m.push(to(S)),m.push(oo(r,n)),m.push(ro(r,g,u,d,l,S)),m.filter(Boolean).join(`
46
+ `)}function qt(o){let e={};for(let[t,s]of Object.entries(o)){let{tools:n,...i}=s;Object.keys(i).length>0&&(e[t]=i)}return e}function Xt(o){let e=o.workflowType||"workflow";return["// Generated workflow",`// ${o.projectId?`Project: ${o.projectId} | `:""}Type: ${e} | Version: ${o.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
47
+ `)}function Qt(o,{usesRegisteredNodes:e=!0}={}){let t=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return e&&t.push("// import './register-nodes.js'; // register custom node types here"),t.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),t.join(`
48
+ `)}function eo(o){if(o.size===0)return"";let e=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];for(let[t,s]of o)e.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(s)}); // ${s.join(", ")}`);return e.push(""),e.join(`
49
+ `)}function to(o){return["// \u2500\u2500 Node Configs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","const __filename = fileURLToPath(import.meta.url);","const __dirname = dirname(__filename);",`const configPath = join(__dirname, 'workflow-${o}.config.json');`,"const nodeConfigs = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')) : {};",""].join(`
50
+ `)}function oo(o,e){let t=["// \u2500\u2500 Node Implementations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",""];for(let s of o){let n=_t(s.id),i=e[s.id]?.customCode;if(i)t.push(`// @custom \u2014 modified from default "${s.nodeType}" template`),t.push(`const ${n}_execute = ${i};`);else{let r=xe(s.nodeType);r?(t.push(`// Default "${s.nodeType}" implementation`),t.push(`const ${n}_execute = ${r};`)):(t.push(`// No template for "${s.nodeType}" \u2014 passthrough`),t.push(`const ${n}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}t.push("")}return t.join(`
51
+ `)}function ro(o,e,t,s,n,i){let r=["// \u2500\u2500 Graph Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];r.push("export function buildGraph(options = {}) {"),r.push(" const graph = new WorkflowGraph(options);",""),r.push(" // Nodes");for(let c of o){let l=_t(c.id);r.push(` graph.addNode('${c.id}', { name: '${c.id}', execute: ${l}_execute });`),r.push(` graph.setNodeType('${c.id}', '${c.nodeType}');`)}r.push("",` graph.setEntryPoint('${e}');`,""),(t.length>0||s.length>0)&&r.push(" // Edges");for(let c of t)r.push(` graph.addEdge('${c.source}', '${c.target}');`);for(let c of s){let l=c.code.split(`
52
52
  `).map((h,u)=>u===0?h:` ${h}`).join(`
53
- `);r.push(` graph.addConditionalEdges('${c.source}', ${d});`)}let a=[];for(let c of o){let d=i.get(c.id);d&&a.push(` '${c.id}': ${d},`)}return a.length>0&&r.push(""," graph.resolvedToolsMap = {",...a," };"),r.push(""," return graph;","}",""),r.push("export { nodeConfigs };",""),r.join(`
54
- `)}function qt(o,e){let t=new Map,s=new Map;for(let i of o){let n=e[i.id]?.tools,r;if(Array.isArray(n)&&n.length>0)r=[...n].sort();else{let a=re[i.nodeType];a?.length>0&&(r=[...a].sort())}if(r){let a=`${r.map(c=>c.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;t.set(i.id,a),s.has(a)||s.set(a,r)}}return{toolsPerNode:t,toolIdsByVar:s}}function Xt(o,e){let t=[],s=[],i=new Map,n=new Set;for(let r of o)i.has(r.source)||i.set(r.source,[]),i.get(r.source).push(r);for(let r of o)if(!e.has(r.source))if(e.has(r.target)){if(n.has(r.target))continue;n.add(r.target);let c=(i.get(r.target)||[]).find(d=>d.data?.conditionalCode||d.conditionalCode);c&&s.push({source:r.source,code:c.data?.conditionalCode||c.conditionalCode})}else t.push({source:r.source,target:r.target});return{simpleEdges:t,conditionalEdges:s}}function Qt(o,e,t){let s=new Set;for(let n of e)t.has(n.target)||s.add(n.target);let i=o.find(n=>!s.has(n.id));return i?i.id:o[0]?.id}function ht(o){return o.replace(/[^a-zA-Z0-9]/g,"_")}L();export{fe as AgentStrategy,pe as CI_ENV_VARS,v as CompilationError,V as ConditionalNode,K as ContextLoader,Y as DEFAULT_OUTPUT_BASE,kt as EVENTS_FILE,re as NODE_DEFAULT_TOOLS,R as Node,U as OutputParser,vt as RAW_OUTPUT_FILE,Tt as RESULT_FILE,le as SESSIONS_DIR,b as SESSION_INFO_FILE,xt as SKILLS,ue as STUDIO_STOP_REQUEST_FILE,Et as SchemaTypes,oe as Timeline,Ue as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,z as WorkflowGraph,j as WorkflowState,ct as clearInheritedSessionEnvForFreshRun,He as clearSkills,Ft as compileGraph,Mt as extractSteps,Zt as generateNodeConfigsJson,Gt as generateWorkflowCode,lt as generateWorkflowSessionId,ge as getAgentStrategy,Ye as getAllSkills,$e as getNodeImpl,Ee as getNodeTemplate,Ne as getResolvedToolDefinitions,F as getSkill,se as hasNode,Ze as hasSkill,qe as invokeAgent,Lt as listNodeTypes,Je as listSkillIds,ze as listStrategies,at as readStudioPinnedSessionPathFromEnv,pt as registerNode,Ge as registerSkill,Ke as registerStrategy,Ie as resolveNodeTools,ut as resolveWorkflowSession,Nt as setLogger,it as shouldTrustInheritedSessionEnv,dt as syncProcessEnvToSession,N as timeline,Bt as validateGraphConfig};
53
+ `);r.push(` graph.addConditionalEdges('${c.source}', ${l});`)}let a=[];for(let c of o){let l=n.get(c.id);l&&a.push(` '${c.id}': ${l},`)}return a.length>0&&r.push(""," graph.resolvedToolsMap = {",...a," };"),r.push(""," return graph;","}",""),r.push("export { nodeConfigs };",""),r.join(`
54
+ `)}function so(o,e){let t=new Map,s=new Map;for(let n of o){let i=e[n.id]?.tools,r;if(Array.isArray(i)&&i.length>0)r=[...i].sort();else{let a=ce[n.nodeType];a?.length>0&&(r=[...a].sort())}if(r){let a=`${r.map(c=>c.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;t.set(n.id,a),s.has(a)||s.set(a,r)}}return{toolsPerNode:t,toolIdsByVar:s}}function no(o,e){let t=[],s=[],n=new Map,i=new Set;for(let r of o)n.has(r.source)||n.set(r.source,[]),n.get(r.source).push(r);for(let r of o)if(!e.has(r.source))if(e.has(r.target)){if(i.has(r.target))continue;i.add(r.target);let c=(n.get(r.target)||[]).find(l=>l.data?.conditionalCode||l.conditionalCode);c&&s.push({source:r.source,code:c.data?.conditionalCode||c.conditionalCode})}else t.push({source:r.source,target:r.target});return{simpleEdges:t,conditionalEdges:s}}function io(o,e,t){let s=new Set;for(let i of e)t.has(i.target)||s.add(i.target);let n=o.find(i=>!s.has(i.id));return n?n.id:o[0]?.id}function _t(o){return o.replace(/[^a-zA-Z0-9]/g,"_")}j();export{Se as AgentStrategy,ge as CI_ENV_VARS,b as CompilationError,Q as ConditionalNode,ee as ContextLoader,z as DEFAULT_OUTPUT_BASE,Rt as EVENTS_FILE,ce as NODE_DEFAULT_TOOLS,L as Node,H as OutputParser,Pt as RAW_OUTPUT_FILE,Ct as RESULT_FILE,he as SESSIONS_DIR,R as SESSION_INFO_FILE,Wt as SKILLS,me as STOP_REQUEST_FILE,bt as SchemaTypes,ie as Timeline,Ke as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,te as WorkflowGraph,J as WorkflowState,ht as clearInheritedSessionEnvForFreshRun,Qe as clearSkills,Zt as compileGraph,Ht as extractSteps,qt as generateNodeConfigsJson,zt as generateWorkflowCode,gt as generateWorkflowSessionId,Ee as getAgentStrategy,qe as getAllSkills,ke as getNodeImpl,xe as getNodeTemplate,be as getResolvedToolDefinitions,U as getSkill,ae as hasNode,ze as hasSkill,rt as invokeAgent,Ut as listNodeTypes,Xe as listSkillIds,ot as listStrategies,ft as readPinnedSessionPathFromEnv,wt as registerNode,Ve as registerSkill,tt as registerStrategy,Ae as resolveNodeTools,St as resolveWorkflowSession,At as setLogger,pt as shouldTrustInheritedSessionEnv,mt as syncProcessEnvToSession,T as timeline,Jt as validateGraphConfig};
@@ -1,5 +1,5 @@
1
1
  export function registerNode(type: any, impl: any): void;
2
2
  export function getNodeImpl(type: any): any;
3
- export function hasNode(type: any): boolean;
3
+ export function hasNode(type: any): any;
4
4
  export function listNodeTypes(): any[];
5
5
  export function getNodeTemplate(type: any): any;