@zibby/agent-workflow 0.4.37 → 0.4.39

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