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