@zibby/agent-workflow 0.4.20 → 0.4.21

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