@zibby/agent-workflow 0.1.3 → 0.2.0

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