@zibby/agent-workflow 0.6.5 → 0.6.6

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.
@@ -38,7 +38,7 @@ ${i}`);let a=o(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Re(d,K);
38
38
  `):r.every(s=>typeof s=="object")?Object.assign({},...r):r[r.length-1]}static async loadFile(e){let t=Pn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),r=await import(o(e).href);return r.default||r}return t}};import{mkdirSync as Pt,existsSync as De,writeFileSync as xt,unlinkSync as Nn}from"node:fs";import{join as Z,resolve as Nt}from"node:path";import{config as Cn}from"dotenv";import{zodToJsonSchema as Ot}from"zod-to-json-schema";import{z as we}from"zod";import Rn from"handlebars";function Bn({traceFrom:n,sessionId:e,sessionPath:t,idSource:o,mkdirFresh:r}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${n} pid=${process.pid} ppid=${s} sessionId=${e} source=${o} mkdir=${r?"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(`
39
39
  `).slice(2,14).join(`
40
40
  `);console.log(`[zibby:session] stack (${n}):
41
- ${h}`)}}function Mn(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function jn(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Nt(String(e).trim())}catch{return String(e).trim()}}function Dn(){Mn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Ln({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Wn(n={}){let e=it.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,r=n.paths?.sessionPrefix;return r?`${r}_${o}`:o}function Un({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let r=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!r&&process.env.ZIBBY_SESSION_PATH)try{let d=Nt(String(process.env.ZIBBY_SESSION_PATH));d&&(r=d,s="ZIBBY_SESSION_PATH")}catch{}let a;if(r)a=String(r).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,s="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,s="config.sessionId"):(a=Wn(e),s="generated")}i=i??Date.now();let h=e.paths?.output||ge;r=Z(n,h,rt,a)}let u=!De(r);return u&&Pt(r,{recursive:!0}),(u||s!=="initialState.sessionPath")&&Bn({traceFrom:o,sessionId:a,sessionPath:r,idSource:s,mkdirFresh:u}),Ln({sessionPath:r,sessionId:a}),{sessionPath:r,sessionId:a,sessionTimestamp:i}}var _e=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,o={}){if(!(t instanceof W)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async d=>{let h=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof s.input=="function"?l=s.input(h):s.input&&typeof s.input=="object"?l=s.input:l={},At(s.workflow,{input:l,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(h):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:h?._signal,parentAgent:d?.agent})}},u=new W(a);return u.name=e,this.nodes.set(e,u),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let r=!(t instanceof W)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof W?t:new W(r?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),o.prompt?this.nodePrompts.set(e,o.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addEdge(e,t){let o=this.edges.get(e);return o===void 0?this.edges.set(e,t):typeof o=="string"?o!==t&&this.edges.set(e,[o,t]):Array.isArray(o)?o.includes(t)||o.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:o}={}){let r=this.edges.get(e);return r!==void 0&&!r.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(r)?r.join(", "):r}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:o}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,o=i=>{t.set(i,1);for(let s of this._simpleTargets(i)){if(!s||s==="END")continue;let a=t.get(s)||0;a===1?e.add(`${i}->${s}`):a===0&&o(s)}t.set(i,2)};this.entryPoint&&o(this.entryPoint);let r=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||r.set(s,(r.get(s)||0)+1);return{backEdges:e,joinDegree:r}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,r,i){let s=o;for(let a=e.length-1;a>=0;a--){let u=e[a],d=s;s=()=>u(t,d,r,i)}return s()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let S=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:S,data:{nodeType:S,label:l}});let g={};c._isCustomCode&&typeof c.execute=="function"&&(g.customCode=c.execute.toString());let E=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;E&&(g.description=E);let A=this.nodePrompts.get(l);if(A)g.prompt=A;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(g.prompt=p,g.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(g.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(g.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof we?.toJSONSchema=="function")try{p=we.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Ot(c.outputSchema,{target:"openApi3"})}catch{}g.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else g.outputSchema={schema:c.outputSchema};let $=(this.resolvedToolsMap||{})[l];$?.toolIds&&(g.tools=$.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(g.skills=[...f]);let m=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;m&&m.length>0&&(g.plugins=m.map(p=>p&&typeof p=="object"?{...p}:p));let w=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;w&&w.length>0&&(g.stores=w.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(g).length>0&&(t[l]=g)}let o=[];for(let[l,c]of this.edges)if(typeof c=="string")o.push({source:l,target:c});else if(Array.isArray(c))for(let S of c)o.push({source:l,target:S});else if(c.conditional){let S=this.conditionalCodeMap.get(l)||c.routes.toString(),g=this._inferConditionalTargets(c.routes,c.labels),E=c.labels||{},A=this.nodes.get(l),$=A?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!A,f=l;if(!$){let m=`${l}__branch`;e.push({id:m,type:"decision",data:{nodeType:"decision",label:m}}),o.push({source:l,target:m}),f=m}for(let m of g){let w={source:f,target:m,data:{conditionalCode:S}};E[m]&&(w.label=E[m]),o.push(w)}}let r=l=>{if(!l)return null;if(typeof we?.toJSONSchema=="function")try{return we.toJSONSchema(l)}catch{}try{return Ot(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let i=0;for(let l of o)if(l.target==="END"){i+=1;let c=`END__${i}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:l,target:c})}let s=this._topoOrderNodes(e,o),a=this._runtimeSchema(),u=r(a||this.stateSchema),d=r(this.inputSchema),h=r(this.contextSchema);return{nodes:s,edges:o,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:h}}_topoOrderNodes(e,t){let o=new Map(e.map((l,c)=>[l.id,c])),r=new Map(e.map(l=>[l.id,l])),i=new Map(e.map(l=>[l.id,0])),s=new Map(e.map(l=>[l.id,[]]));for(let l of t)s.has(l.source)&&i.has(l.target)&&(s.get(l.source).push(l.target),i.set(l.target,i.get(l.target)+1));let a=new Set,u=new Set(o.keys()),d=[...u].filter(l=>i.get(l)===0),h=[];for(;h.length<e.length;){let l;if(d.length>0){if(d.sort((c,S)=>o.get(c)-o.get(S)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,S)=>o.get(c)-o.get(S))[0];a.add(l),u.delete(l),h.push(r.get(l));for(let c of s.get(l)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return h}_inferConditionalTargets(e,t){let o=e.toString(),r=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(o))!==null;){let d=s[2]!==void 0?s[2]:s[3];d!==void 0&&d!==""&&r.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let u=new Set;for(let d of r)a.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=d.exec(o))!==null;)u.add(h[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let r=e.$ref.replace("#/definitions/","");o=e.definitions[r]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],r=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(r)){let u=t?`${t}.${s}`:s;o.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${u}[]`))}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[r,i]of Object.entries(t))if(!(r==="success"||r==="raw"||r==="nextNode")){if(typeof i=="string"&&i.length<=80)o.push(`${r}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(d=>d?.passed===!0).length,u=i.some(d=>d?.passed!==void 0);o.push(u?`${r}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${r}: ${s} items`)}if(o.length>=4)break}return o}async run(e,t={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(_){let y=new Error(`agent.normalizeInput() rejected the trigger input: ${_?.message||_}`);throw y.cause=_,y.code=_?.code||"NORMALIZE_INPUT_FAILED",y}let r=new AbortController;o.signal&&(o.signal.aborted?r.abort():o.signal.addEventListener("abort",()=>r.abort(),{once:!0}));let i=o.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();Cn({path:Z(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let _=Z(s,".zibby.config.js");De(_)&&(a=(await import(_)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let _=a?.agent;_?.provider?u=_.provider:_?.gemini?u="gemini":_?.claude?u="claude":_?.cursor?u="cursor":_?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},h=this._runtimeSchema();if(h){let _=h.safeParse(t);if(!_.success){let y=_.error.issues.map(B=>`${B.path.join(".")}: ${B.message}`);throw console.error("\u274C Initial state validation failed:"),y.forEach(B=>console.error(` - ${B}`)),new Error(`State validation failed: ${y.join(", ")}`)}O.step("State validated against schema")}let l=jn(),c=t.sessionPath||l;c||Dn();let{sessionPath:S,sessionTimestamp:g,sessionId:E}=Un({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${E}`);let A=await Se.loadContext(t.specPath||"",s,d);Object.keys(A).length>0&&O.step(`Context loaded: ${Object.keys(A).join(", ")}`);let $=t.outputPath;!$&&t.specPath&&(e?.calculateOutputPath?$=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new pe({...t,config:a,agentType:u,outputPath:$,sessionPath:S,sessionTimestamp:g,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:r.signal}),m=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:w}=await Promise.resolve().then(()=>(me(),ct)),p=a.skills&&typeof a.skills=="object"?a.skills:{},b=Object.values(p).filter(_=>_&&typeof _=="object"&&typeof _.id=="string"),v=_=>{for(let y of b)if(y.id===_)return y;return w(_)},P=new Set;for(let[,_]of this.nodes)for(let y of _.config?.skills||[])P.add(y);for(let _ of P){let y=v(_);if(typeof y?.middleware=="function")try{let B=await y.middleware();typeof B=="function"&&m.set(_,B)}catch{}}let{backEdges:X,joinDegree:jt}=this._analyzeFlow(),Ie=new Map,Q=[],Ee=(_,y,B)=>{if(!_||_==="END")return;let D=jt.get(_)||0;if(B&&D>1&&!X.has(`${y}->${_}`)){let ee=(Ie.get(_)||0)+1;if(ee<D){Ie.set(_,ee);return}Ie.set(_,0)}Q.includes(_)||Q.push(_)};this.entryPoint&&Q.push(this.entryPoint);let ce=[],Fe=a?.recursionLimit??100,Dt=0;try{for(;Q.length>0;){let y=Q.pop();if(!y||y==="END")continue;if(++Dt>Fe)throw new Error(`Workflow exceeded recursion limit (${Fe}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let B=Z(S,st);if(De(B)){try{Nn(B)}catch{}r.abort()}if(r.signal.aborted)return console.warn(`
41
+ ${h}`)}}function Mn(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function jn(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Nt(String(e).trim())}catch{return String(e).trim()}}function Dn(){Mn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Ln({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Wn(n={}){let e=it.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,r=n.paths?.sessionPrefix;return r?`${r}_${o}`:o}function Un({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let r=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!r&&process.env.ZIBBY_SESSION_PATH)try{let d=Nt(String(process.env.ZIBBY_SESSION_PATH));d&&(r=d,s="ZIBBY_SESSION_PATH")}catch{}let a;if(r)a=String(r).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,s="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,s="config.sessionId"):(a=Wn(e),s="generated")}i=i??Date.now();let h=e.paths?.output||ge;r=Z(n,h,rt,a)}let u=!De(r);return u&&Pt(r,{recursive:!0}),(u||s!=="initialState.sessionPath")&&Bn({traceFrom:o,sessionId:a,sessionPath:r,idSource:s,mkdirFresh:u}),Ln({sessionPath:r,sessionId:a}),{sessionPath:r,sessionId:a,sessionTimestamp:i}}var _e=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,o={}){if(!(t instanceof W)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async d=>{let h=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof s.input=="function"?l=s.input(h):s.input&&typeof s.input=="object"?l=s.input:l={},At(s.workflow,{input:l,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(h):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:h?._signal,parentAgent:d?.agent})}},u=new W(a);return u.name=e,this.nodes.set(e,u),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let r=!(t instanceof W)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof W?t:new W(r?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),o.prompt?this.nodePrompts.set(e,o.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addEdge(e,t){let o=this.edges.get(e);return o===void 0?this.edges.set(e,t):typeof o=="string"?o!==t&&this.edges.set(e,[o,t]):Array.isArray(o)?o.includes(t)||o.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:o}={}){let r=this.edges.get(e);return r!==void 0&&!r.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(r)?r.join(", "):r}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:o}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,o=i=>{t.set(i,1);for(let s of this._simpleTargets(i)){if(!s||s==="END")continue;let a=t.get(s)||0;a===1?e.add(`${i}->${s}`):a===0&&o(s)}t.set(i,2)};this.entryPoint&&o(this.entryPoint);let r=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||r.set(s,(r.get(s)||0)+1);return{backEdges:e,joinDegree:r}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,r,i){let s=o;for(let a=e.length-1;a>=0;a--){let u=e[a],d=s;s=()=>u(t,d,r,i)}return s()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let S=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:S,data:{nodeType:S,label:l}});let g={};c._isCustomCode&&typeof c.execute=="function"&&(g.customCode=c.execute.toString());let E=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;E&&(g.description=E);let A=this.nodePrompts.get(l);if(A)g.prompt=A;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(g.prompt=p,g.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(g.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(g.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(g.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof we?.toJSONSchema=="function")try{p=we.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Ot(c.outputSchema,{target:"openApi3"})}catch{}g.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else g.outputSchema={schema:c.outputSchema};let $=(this.resolvedToolsMap||{})[l];$?.toolIds&&(g.tools=$.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(g.skills=[...f]);let m=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;m&&m.length>0&&(g.plugins=m.map(p=>p&&typeof p=="object"?{...p}:p));let w=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;w&&w.length>0&&(g.stores=w.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(g).length>0&&(t[l]=g)}let o=[];for(let[l,c]of this.edges)if(typeof c=="string")o.push({source:l,target:c});else if(Array.isArray(c))for(let S of c)o.push({source:l,target:S});else if(c.conditional){let S=this.conditionalCodeMap.get(l)||c.routes.toString(),g=this._inferConditionalTargets(c.routes,c.labels),E=c.labels||{},A=this.nodes.get(l),$=A?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!A,f=l;if(!$){let m=`${l}__branch`;e.push({id:m,type:"decision",data:{nodeType:"decision",label:m}}),o.push({source:l,target:m}),f=m}for(let m of g){let w={source:f,target:m,data:{conditionalCode:S}};E[m]&&(w.label=E[m]),o.push(w)}}let r=l=>{if(!l)return null;if(typeof we?.toJSONSchema=="function")try{return we.toJSONSchema(l)}catch{}try{return Ot(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let i=0;for(let l of o)if(l.target==="END"){i+=1;let c=`END__${i}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:l,target:c})}let s=this._topoOrderNodes(e,o),a=this._runtimeSchema(),u=r(a||this.stateSchema),d=r(this.inputSchema),h=r(this.contextSchema);return{nodes:s,edges:o,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:h}}_topoOrderNodes(e,t){let o=new Map(e.map((l,c)=>[l.id,c])),r=new Map(e.map(l=>[l.id,l])),i=new Map(e.map(l=>[l.id,0])),s=new Map(e.map(l=>[l.id,[]]));for(let l of t)s.has(l.source)&&i.has(l.target)&&(s.get(l.source).push(l.target),i.set(l.target,i.get(l.target)+1));let a=new Set,u=new Set(o.keys()),d=[...u].filter(l=>i.get(l)===0),h=[];for(;h.length<e.length;){let l;if(d.length>0){if(d.sort((c,S)=>o.get(c)-o.get(S)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,S)=>o.get(c)-o.get(S))[0];a.add(l),u.delete(l),h.push(r.get(l));for(let c of s.get(l)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return h}_inferConditionalTargets(e,t){let o=e.toString(),r=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(o))!==null;){let d=s[2]!==void 0?s[2]:s[3];d!==void 0&&d!==""&&r.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let u=new Set;for(let d of r)a.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=d.exec(o))!==null;)u.add(h[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let r=e.$ref.replace("#/definitions/","");o=e.definitions[r]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],r=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(r)){let u=t?`${t}.${s}`:s;o.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${u}[]`))}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[r,i]of Object.entries(t))if(!(r==="success"||r==="raw"||r==="nextNode")){if(typeof i=="string"&&i.length<=80)o.push(`${r}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(d=>d?.passed===!0).length,u=i.some(d=>d?.passed!==void 0);o.push(u?`${r}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${r}: ${s} items`)}if(o.length>=4)break}return o}async run(e,t={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(_){let y=new Error(`agent.normalizeInput() rejected the trigger input: ${_?.message||_}`);throw y.cause=_,y.code=_?.code||"NORMALIZE_INPUT_FAILED",y}let r=new AbortController;o.signal&&(o.signal.aborted?r.abort():o.signal.addEventListener("abort",()=>r.abort(),{once:!0}));let i=o.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();Cn({path:Z(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let _=Z(s,".zibby.config.js");De(_)&&(a=(await import(_)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let _=a?.agent;_?.provider?u=_.provider:_?.gemini?u="gemini":_?.claude?u="claude":_?.cursor?u="cursor":_?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},h=this._runtimeSchema();if(h){let _=h.safeParse(t);if(!_.success){let y=_.error.issues.map(B=>`${B.path.join(".")}: ${B.message}`);throw console.error("\u274C Initial state validation failed:"),y.forEach(B=>console.error(` - ${B}`)),new Error(`State validation failed: ${y.join(", ")}`)}O.step("State validated against schema")}let l=jn(),c=t.sessionPath||l;c||Dn();let{sessionPath:S,sessionTimestamp:g,sessionId:E}=Un({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${E}`);let A=await Se.loadContext(t.specPath||"",s,d);Object.keys(A).length>0&&O.step(`Context loaded: ${Object.keys(A).join(", ")}`);let $=t.outputPath;!$&&t.specPath&&(e?.calculateOutputPath?$=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new pe({...t,config:a,agentType:u,outputPath:$,sessionPath:S,sessionTimestamp:g,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:r.signal}),m=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:w}=await Promise.resolve().then(()=>(me(),ct)),p=a.skills&&typeof a.skills=="object"?a.skills:{},b=Object.values(p).filter(_=>_&&typeof _=="object"&&typeof _.id=="string"),v=_=>{for(let y of b)if(y.id===_)return y;return w(_)},P=new Set;for(let[,_]of this.nodes)for(let y of _.config?.skills||[])P.add(y);for(let _ of P){let y=v(_);if(typeof y?.middleware=="function")try{let B=await y.middleware();typeof B=="function"&&m.set(_,B)}catch{}}let{backEdges:X,joinDegree:jt}=this._analyzeFlow(),Ie=new Map,Q=[],Ee=(_,y,B)=>{if(!_||_==="END")return;let D=jt.get(_)||0;if(B&&D>1&&!X.has(`${y}->${_}`)){let ee=(Ie.get(_)||0)+1;if(ee<D){Ie.set(_,ee);return}Ie.set(_,0)}Q.includes(_)||Q.push(_)};this.entryPoint&&Q.push(this.entryPoint);let ce=[],Fe=a?.recursionLimit??100,Dt=0;try{for(;Q.length>0;){let y=Q.pop();if(!y||y==="END")continue;if(++Dt>Fe)throw new Error(`Workflow exceeded recursion limit (${Fe}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let B=Z(S,st);if(De(B)){try{Nn(B)}catch{}r.abort()}if(r.signal.aborted)return console.warn(`
42
42
  \u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ce,stoppedExternally:!0};let D=this.nodes.get(y);if(!D)throw new Error(`Node '${y}' not found in graph`);let ee=JSON.stringify({sessionPath:S,sessionTimestamp:g,currentNode:y,createdAt:new Date().toISOString(),config:f.get("config")}),Lt=Z(S,K);xt(Lt,ee,"utf-8");let Ge=f.get("config")?.paths?.output||ge,Wt=Z(s,Ge,K);Pt(Z(s,Ge),{recursive:!0});try{xt(Wt,ee,"utf-8")}catch{}let He=t.onPipelineProgress;if(typeof He=="function")try{He({cwd:s,sessionPath:S,sessionId:E,outputBase:f.get("config")?.paths?.output||ge,currentNode:y})}catch{}let Ut=(this.resolvedToolsMap||{})[y]||null;f.set("_currentNodeTools",Ut);let Ft=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Ft[y]||{}),O.nodeStart(y);let Je=Date.now(),le=this.nodePrompts.get(y);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(ie(),se));this._invokeAgent=k.invokeAgent}let Gt=this._invokeAgent,$e={},Ht=D.config?.skills||[];for(let k of Ht){let C=v(k);if(typeof C?.invokeAgentOptions=="function")try{let T=C.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:y});T&&typeof T=="object"&&($e={...$e,...T})}catch(T){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${T.message}`)}}let ze=async(k,C,T={})=>{let M=Gt(k,C,{...$e,...T,signal:r.signal});return M.catch(()=>{}),r.signal.aborted?M:Promise.race([M,new Promise((q,L)=>{let R=()=>{setTimeout(()=>{let te=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);te.name="AbortError",L(te)},i)};r.signal.addEventListener("abort",R,{once:!0})})])},Jt=async(k={},C={})=>{let T=C.prompt||"";if(le){let M=this._compiledPrompts.get(y);M||(M=Rn.compile(le,{noEscape:!0}),this._compiledPrompts.set(y,M));try{T=M(k)}catch(q){throw console.error(`\u274C Template rendering failed for node '${y}':`,q.message),new Error(`Template rendering failed: ${q.message}`,{cause:q})}}else if(!T)throw new Error(`No prompt template configured for node '${y}' and no prompt provided in options`);return ze(T,{state:f.getAll(),images:C.images||[]},{model:C.model||f.get("model"),workspace:f.get("workspace"),schema:C.schema,...C,signal:r.signal})},Ye=f.getAll(),zt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of zt)Object.prototype.hasOwnProperty.call(Ye,k)&&console.warn(`[workflow] node "${y}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ze={...Ye,state:f,invokeAgent:Jt,_coreInvokeAgent:ze,agent:e,nodeId:y,promptTemplate:le,getPromptTemplate:()=>le};try{let k=(D.config?.skills||[]).map(R=>m.get(R)).filter(Boolean),C=[...this.middleware,...k],T;T=await ht(e,r.signal,async()=>C.length>0?this._composeMiddleware(C,y,async()=>D.execute(Ze,f),f.getAll(),f):D.execute(Ze,f));let M=Date.now()-Je;if(ce.push({node:y,success:T.success,duration:M,timestamp:new Date().toISOString()}),!T.success){if(r.signal.aborted)return O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ce,stoppedExternally:!0};f.append("errors",{node:y,error:T.error});let R=D.config?.retries||0,te=`${y}_retries`,ue=f.getAll()[te]||0;if(ue<R){O.stepInfo(`Retrying (attempt ${ue+1}/${R})`),f.update({[te]:ue+1,[`${y}_raw`]:T.raw});continue}throw O.nodeFailed(y,T.error,{duration:M}),new Error(`Node '${y}' failed after ${ue} attempts: ${T.error}`)}f.update({[y]:T.output});let q=this._summarizeNodeOutput(y,T.output);O.nodeComplete(y,{duration:M,details:q});let L=this.edges.get(y);if(L)if(L.conditional){let R=L.routes(f.getAll());O.route(y,R),Ee(R,y,!1)}else if(Array.isArray(L))for(let R=L.length-1;R>=0;R--)Ee(L[R],y,!0);else Ee(L,y,!0)}catch(k){throw O.isInsideNode&&O.nodeFailed(y,k.message,{duration:Date.now()-Je}),f.set("failed",!0),f.set("failedAt",y),k}}O.graphComplete();let _={success:!0,state:f.getAll(),executionLog:ce};return e&&typeof e.onComplete=="function"&&await e.onComplete(_),_}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(_){console.warn(`[workflow] agent.cleanup() failed: ${_.message}`)}}}};var Le=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Le]||(globalThis[Le]=new Map);var We=globalThis[Le];function Fn(n,e){We.set(n,e)}function Ct(n){return We.get(n)}function Ue(n){return We.has(n)}Fn("ai_agent",{name:"ai_agent",factory:!0,create:(n,e={})=>({name:n,_isCustomCode:!0,execute:async t=>{let o=t?._coreInvokeAgent;o||(o=(await Promise.resolve().then(()=>(ie(),se))).invokeAgent);let r=e.extraPromptInstructions||"Execute the task based on the current state.",i=Gn(r,t),s=await o(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:s,nodeId:n},raw:typeof s=="string"?s:s.raw}}})});function Gn(n,e){let t=/@([\w.]+)/g,o=new Set,r;for(;(r=t.exec(n))!==null;)o.add(r[1]);if(o.size===0)return n;let i=[],s=new Set;for(let a of o){let u=a.split(".")[0];if(s.has(u))continue;let d=a.split(".").reduce((c,S)=>c?.[S],e);if(d===void 0)continue;let h=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),l=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${l}
43
43
  ${h}`),a.includes(".")||s.add(u)}return i.length===0?n:`${n}
44
44
 
package/dist/graph.js CHANGED
@@ -1,20 +1,20 @@
1
- var jt=Object.defineProperty;var ae=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Fe=(r,e)=>{for(var t in e)jt(r,t,{get:e[t],enumerable:!0})};var Ge,Lt,ue,b,ee=ae(()=>{Ge=()=>{},Lt={debug:Ge,info:Ge,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},ue={impl:Lt},b={debug:(...r)=>ue.impl.debug?.(...r),info:(...r)=>ue.impl.info?.(...r),warn:(...r)=>ue.impl.warn?.(...r),error:(...r)=>ue.impl.error?.(...r)}});var et=ae(()=>{});var tt={};Fe(tt,{clearSkills:()=>Yt,getAllSkills:()=>Jt,getSkill:()=>$e,getSkillSource:()=>Ht,hasSkill:()=>Gt,listSkillIds:()=>zt,registerSkill:()=>Ft});function Ft(r,e={}){if(!r||typeof r.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:n=!1}=e,s=r.id;if(U.has(s)&&!n){let i=ne.get(s);if(!(i===t)){let a=i||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${s}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}U.set(s,Object.freeze({...r})),t===void 0?ne.delete(s):ne.set(s,t)}function $e(r){return U.get(r)||null}function Gt(r){return U.has(r)}function Ht(r){return ne.get(r)||null}function Jt(){return new Map(U)}function zt(){return Array.from(U.keys())}function Yt(){U.clear(),ne.clear()}var be,Ee,U,ne,ve=ae(()=>{be=Symbol.for("@zibby/agent-workflow.skills"),Ee=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[be]||(globalThis[be]=new Map);globalThis[Ee]||(globalThis[Ee]=new Map);U=globalThis[be],ne=globalThis[Ee]});var Te={};Fe(Te,{getAgentStrategy:()=>rt,invokeAgent:()=>Vt,listStrategies:()=>qt,registerStrategy:()=>Zt,resolveInvocationModel:()=>nt});function Zt(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=F.findIndex(t=>t.getName()===r.getName());e>=0?F[e]=r:F.push(r)}function qt(){return F.map(r=>r.getName())}function nt({config:r={},options:e={},strategyName:t,envModel:n,nodeConfigModel:s}={}){let i=r.models||{},o=typeof s=="string"&&s.trim()&&s.trim()!=="auto"?s.trim():null,a=e.nodeName&&i[e.nodeName]||null,u=i.default||null,d=r.agent?.[t]?.model||null,m=(typeof n=="string"?n.trim():"")||null;return o||a||u||d||e.model||m||null}function rt(r={}){let{state:e={},preferredAgent:t=null}=r,n=t||e.agentType||process.env.AGENT_TYPE;if(!n){let i=F.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}b.debug(`[workflow] agent selection: requested=${n}`);let s=F.find(i=>i.getName()===n);if(!s){let i=F.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${i}`)}if(!s.canHandle(r))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return b.debug(`[workflow] using agent: ${s.getName()}`),s}async function Vt(r,e={},t={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:n},i=rt(s),o=n.config||t.config||{},a=n._currentNodeConfig||{},u=typeof a.agent=="string"?a.agent.trim():"",d=!u||u===i.name?a.model:null,m=nt({config:o,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:d}),c={...t,model:m,workspace:n.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],extraMcpServers:t.extraMcpServers||n.extraMcpServers||e.extraMcpServers||[],plugins:t.plugins||e.plugins||[],config:o},l=r,I=c.skills||[];if(I.length>0&&!t.skipPromptFragments){let A=t.connectedIntegrations;if(!A){let p=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof p=="string"&&p.trim()!==""){A={};for(let _ of p.split(",").map(E=>E.trim()).filter(Boolean))A[_]=!0}}let $=p=>{let _=p&&p.requiresIntegration;return!_||!A?!0:(Array.isArray(_)?_:[_]).some(P=>A[P]===!0)},f=i.name==="assistant",g=p=>p?.inProcessOnly!==!0||f,y=I.map(p=>{let _=$e(p);if(!$(_)||!g(_))return null;let E=_?.promptFragment;return typeof E=="function"?E():E}).filter(Boolean);y.length>0&&(l+=`
1
+ var jt=Object.defineProperty;var ae=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Fe=(r,e)=>{for(var t in e)jt(r,t,{get:e[t],enumerable:!0})};var Ge,Lt,ue,b,ee=ae(()=>{Ge=()=>{},Lt={debug:Ge,info:Ge,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},ue={impl:Lt},b={debug:(...r)=>ue.impl.debug?.(...r),info:(...r)=>ue.impl.info?.(...r),warn:(...r)=>ue.impl.warn?.(...r),error:(...r)=>ue.impl.error?.(...r)}});var et=ae(()=>{});var tt={};Fe(tt,{clearSkills:()=>Yt,getAllSkills:()=>Jt,getSkill:()=>$e,getSkillSource:()=>Ht,hasSkill:()=>Gt,listSkillIds:()=>zt,registerSkill:()=>Ft});function Ft(r,e={}){if(!r||typeof r.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:n=!1}=e,s=r.id;if(U.has(s)&&!n){let i=ne.get(s);if(!(i===t)){let a=i||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${s}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}U.set(s,Object.freeze({...r})),t===void 0?ne.delete(s):ne.set(s,t)}function $e(r){return U.get(r)||null}function Gt(r){return U.has(r)}function Ht(r){return ne.get(r)||null}function Jt(){return new Map(U)}function zt(){return Array.from(U.keys())}function Yt(){U.clear(),ne.clear()}var be,Ee,U,ne,ve=ae(()=>{be=Symbol.for("@zibby/agent-workflow.skills"),Ee=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[be]||(globalThis[be]=new Map);globalThis[Ee]||(globalThis[Ee]=new Map);U=globalThis[be],ne=globalThis[Ee]});var Te={};Fe(Te,{getAgentStrategy:()=>rt,invokeAgent:()=>Vt,listStrategies:()=>qt,registerStrategy:()=>Zt,resolveInvocationModel:()=>nt});function Zt(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=F.findIndex(t=>t.getName()===r.getName());e>=0?F[e]=r:F.push(r)}function qt(){return F.map(r=>r.getName())}function nt({config:r={},options:e={},strategyName:t,envModel:n,nodeConfigModel:s}={}){let i=r.models||{},o=typeof s=="string"&&s.trim()&&s.trim()!=="auto"?s.trim():null,a=e.nodeName&&i[e.nodeName]||null,u=i.default||null,d=r.agent?.[t]?.model||null,m=(typeof n=="string"?n.trim():"")||null;return o||a||u||d||e.model||m||null}function rt(r={}){let{state:e={},preferredAgent:t=null}=r,n=t||e.agentType||process.env.AGENT_TYPE;if(!n){let i=F.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}b.debug(`[workflow] agent selection: requested=${n}`);let s=F.find(i=>i.getName()===n);if(!s){let i=F.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${i}`)}if(!s.canHandle(r))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return b.debug(`[workflow] using agent: ${s.getName()}`),s}async function Vt(r,e={},t={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:n},i=rt(s),o=n.config||t.config||{},a=n._currentNodeConfig||{},u=typeof a.agent=="string"?a.agent.trim():"",d=!u||u===i.name?a.model:null,m=nt({config:o,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:d}),l={...t,model:m,workspace:n.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],extraMcpServers:t.extraMcpServers||n.extraMcpServers||e.extraMcpServers||[],plugins:t.plugins||e.plugins||[],config:o},c=r,I=l.skills||[];if(I.length>0&&!t.skipPromptFragments){let A=t.connectedIntegrations;if(!A){let p=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof p=="string"&&p.trim()!==""){A={};for(let _ of p.split(",").map(E=>E.trim()).filter(Boolean))A[_]=!0}}let $=p=>{let _=p&&p.requiresIntegration;return!_||!A?!0:(Array.isArray(_)?_:[_]).some(P=>A[P]===!0)},f=i.name==="assistant",g=p=>p?.inProcessOnly!==!0||f,y=I.map(p=>{let _=$e(p);if(!$(_)||!g(_))return null;let E=_?.promptFragment;return typeof E=="function"?E():E}).filter(Boolean);y.length>0&&(c+=`
2
2
 
3
3
  ${y.join(`
4
4
 
5
5
  `)}`)}let w=n._currentNodeConfig?.stores;if(Array.isArray(w)&&w.length>0&&typeof w[0]=="object"){let A=w.length<=8,$=w.map(f=>{let g=f?.id??f?.storeId??"",y=(f?.name??"").toString().trim()||g,p=f?.type?` \xB7 ${f.type}`:"",_=(f?.description||"").toString().replace(/\s+/g," ").trim(),E=`- ${y} \xB7 ${_||"(no description)"}${p} (id: ${g})`;if(A&&f?.schema&&typeof f.schema=="object"){let P=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);P.length&&(E+=`
6
- fields: ${P.join(", ")}`)}return E});l+=`
6
+ fields: ${P.join(", ")}`)}return E});c+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
9
9
  ${$.join(`
10
- `)}`}let v=n._currentNodeConfig?.extraPromptInstructions?.trim();return v&&(l+=`
10
+ `)}`}let v=n._currentNodeConfig?.extraPromptInstructions?.trim();return v&&(c+=`
11
11
 
12
12
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
13
13
  PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
14
14
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
15
15
 
16
16
  ${v}
17
- `),b.debug(`[workflow] prompt length: ${l.length} chars`),i.invoke(l,c)}var Ae,F,ke=ae(()=>{et();ee();ve();Ae=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ae]||(globalThis[Ae]=[]);F=globalThis[Ae]});var Dt=new Set(["__proto__","constructor","prototype"]);function Se(r){if(Dt.has(r))throw new Error(`Invalid state key: "${r}"`)}var ce=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){Se(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let n of t)Se(n);this._history.push({...this._state});for(let n of t)this._state[n]=e[n]}append(e,t){Se(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import G from"handlebars";var le=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 n=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of n)try{return this.validate(JSON.parse(s))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[n,s]of Object.entries(this.schema)){if(s.required&&!(n in e)&&t.push(`Missing required field: ${n}`),n in e&&s.type){let i=typeof e[n];i!==s.type&&t.push(`Field '${n}' expected ${s.type}, got ${i}`)}if(s.validate&&n in e){let i=s.validate(e[n]);i&&t.push(`Field '${n}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
17
+ `),b.debug(`[workflow] prompt length: ${c.length} chars`),i.invoke(c,l)}var Ae,F,ke=ae(()=>{et();ee();ve();Ae=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ae]||(globalThis[Ae]=[]);F=globalThis[Ae]});var Dt=new Set(["__proto__","constructor","prototype"]);function Se(r){if(Dt.has(r))throw new Error(`Invalid state key: "${r}"`)}var ce=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){Se(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let n of t)Se(n);this._history.push({...this._state});for(let n of t)this._state[n]=e[n]}append(e,t){Se(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import G from"handlebars";var le=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 n=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of n)try{return this.validate(JSON.parse(s))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[n,s]of Object.entries(this.schema)){if(s.required&&!(n in e)&&t.push(`Missing required field: ${n}`),n in e&&s.type){let i=typeof e[n];i!==s.type&&t.push(`Field '${n}' expected ${s.type}, got ${i}`)}if(s.validate&&n in e){let i=s.validate(e[n]);i&&t.push(`Field '${n}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
18
18
  ${t.join(`
19
19
  `)}`);return e}};ee();import{writeFileSync as xe,readFileSync as st,existsSync as ot,mkdirSync as Kt}from"node:fs";import{join as Oe,dirname as Xt}from"node:path";import x from"chalk";var Wt="__WORKFLOW_GRAPH_LOG__",te=x.gray("\u2502"),Ut=x.gray("\u250C"),He=x.gray("\u2514"),we=x.green("\u25C6"),Je=x.hex("#c084fc")("\u25C6"),ze=x.hex("#2dd4bf")("\u25C6"),_e=x.red("\u25C6"),Ye=`${te} `,Ze=2;function qe(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function Ve(r,e){return(t,n,s)=>{if(typeof t!="string")return r(t,n,s);let i=process.stdout.columns||120,o="";for(let a=0;a<t.length;a++){let u=t[a];e.lineStart&&(o+=Ye,e.col=Ze,e.lineStart=!1),u===`
20
20
  `?(o+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,o+=u):e.inEsc?(o+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,o+=u,e.col>=i&&(o+=`
@@ -29,14 +29,14 @@ ${Ye}`,e.col=Ze))}return r(o,n,s)}}var Ie=class{constructor(){this._currentNode=
29
29
  `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Je,e):process.stdout.write.bind(process.stdout)(`${te} ${Je} ${e}
30
30
  `)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(ze,t):process.stdout.write.bind(process.stdout)(`${te} ${ze} ${t}
31
31
  `)}stepFail(e){this._origStdoutWrite?this._writeDot(_e,x.red(e)):process.stdout.write.bind(process.stdout)(`${te} ${_e} ${x.red(e)}
32
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Ut} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:n,details:s}=t;if(s)for(let o of s)this._rawWrite(`${we} ${o}`);let i=n?x.dim(` ${qe(n)}`):"";this._rawWrite(`${He} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,n={}){this._stopIntercepting();let{duration:s}=n,i=s?x.dim(` ${qe(s)}`):"";this._rawWrite(`${_e} ${x.red(t)}`),this._rawWrite(`${He} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},O=new Ie;var pe=".zibby/output",Ke="sessions",Z=".session-info.json",Xe=".zibby-stop";var Dn=Object.freeze(["codebase-memory","code-scan","artifact"]),Qe=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];G.helpers.inc||G.registerHelper("inc",r=>Number(r)+1);G.helpers.json||G.registerHelper("json",r=>JSON.stringify(r,null,2));G.helpers.eq||G.registerHelper("eq",(r,e)=>r===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new le(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return b.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let n=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=c=>t&&typeof t.get=="function"?t.get(c):e?.[c];if(typeof this.customExecute=="function"){b.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(e);return typeof c=="object"&&c!==null&&c.success===!1?{success:!1,error:c.error||"Node execution failed",raw:c.raw||null}:this.isZodSchema?(b.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(c),raw:null}):{success:!0,output:c,raw:null}}catch(c){return b.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&b.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=G.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(n())):i=this.prompt;let o=s("_skillHints");o&&(i=`${o}
32
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Ut} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:n,details:s}=t;if(s)for(let o of s)this._rawWrite(`${we} ${o}`);let i=n?x.dim(` ${qe(n)}`):"";this._rawWrite(`${He} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,n={}){this._stopIntercepting();let{duration:s}=n,i=s?x.dim(` ${qe(s)}`):"";this._rawWrite(`${_e} ${x.red(t)}`),this._rawWrite(`${He} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},O=new Ie;var pe=".zibby/output",Ke="sessions",Z=".session-info.json",Xe=".zibby-stop";var Dn=Object.freeze(["codebase-memory","code-scan","artifact"]),Qe=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];G.helpers.inc||G.registerHelper("inc",r=>Number(r)+1);G.helpers.json||G.registerHelper("json",r=>JSON.stringify(r,null,2));G.helpers.eq||G.registerHelper("eq",(r,e)=>r===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new le(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return b.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let n=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){b.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(b.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 b.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&b.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=G.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(n())):i=this.prompt;let o=s("_skillHints");o&&(i=`${o}
33
33
 
34
- ${i}`);let a=n(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let c=Oe(d,Z);if(ot(c)){let I=JSON.parse(st(c,"utf-8"));I.currentNode=this.name,xe(c,JSON.stringify(I,null,2),"utf-8")}let l=Oe(d,"..",Z);if(ot(l))try{let I=JSON.parse(st(l,"utf-8"));I.currentNode=this.name,xe(l,JSON.stringify(I,null,2),"utf-8")}catch{}}}catch(c){b.debug(`[workflow] could not update session info: ${c.message}`)}let m=null;for(let c=0;c<=this.retries;c++)try{b.debug(`[workflow] node '${this.name}' attempt ${c}`);let l=n().config||{},I=l.agents||{},w=this.config.agent??I[this.name]??null,v={state:n()};w&&(v.preferredAgent=w);let A={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:d,config:l,nodeName:this.name,timeout:this.config?.timeout||3e5},$=e?._coreInvokeAgent;$||($=(await Promise.resolve().then(()=>(ke(),Te))).invokeAgent);let f=await $(i,v,A),g,y;if(typeof f=="string"?(g=f,y=null):f.structured?(g=f.raw||JSON.stringify(f.structured,null,2),y=f.structured):(g=f.raw||JSON.stringify(f,null,2),y=f.extracted||null),d)try{let p=Oe(d,this.name,"raw_stream_output.txt");Kt(Xt(p),{recursive:!0}),xe(p,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(p){b.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&y){b.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let p=y;if(typeof this.onComplete=="function")try{p=await this.onComplete(n(),y)}catch(_){b.warn(`[workflow] onComplete hook failed: ${_.message}`)}return{success:!0,output:p,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:g}),raw:g}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(g);return b.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),O.step("Output parsed"),{success:!0,output:p,raw:g}}return{success:!0,output:g,raw:g}}catch(l){m=l,c<this.retries&&b.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:m.message,raw:null}}};ee();ee();import{mkdirSync as tn,existsSync as J,statSync as gt,readdirSync as mt,rmSync as nn}from"node:fs";import{spawn as dt}from"node:child_process";import{join as W}from"node:path";import{pathToFileURL as rn}from"node:url";import{AsyncLocalStorage as sn}from"node:async_hooks";import{AsyncLocalStorage as Qt}from"node:async_hooks";var re=new Qt;function q(){let r=re.getStore();return r||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function it(r,e){let t=re.getStore()||q(),n=Object.freeze({executionId:r.executionId,parentExecutionId:r.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(r.executionId!==t.executionId?1:0),conversationId:r.conversationId!==void 0?r.conversationId:t.conversationId??null,dispatchMode:r.dispatchMode??null,agent:r.agent!==void 0?r.agent:t.agent??null,signal:r.signal!==void 0?r.signal:t.signal??null});return re.run(n,e)}function at(r,e,t){let n=re.getStore()||q(),s=Object.freeze({...n,agent:r??n.agent??null,signal:e??n.signal??null});return re.run(s,t)}var Pe=new Map,Ne=new Map,ct=new Map;function lt(r,e,t={}){if(!r||typeof r!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Pe.set(r,e),Ne.set(r,"ready"),ct.set(r,{...t,cachedAt:Date.now()})}function ut(r,e){Ne.set(r,"failed"),ct.set(r,{error:e?.message||String(e),failedAt:Date.now()}),Pe.delete(r)}function pt(r){return Ne.get(r)==="ready"?Pe.get(r):null}var de=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function on(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}},ft=new sn,ht=Promise.resolve();async function an(r,e){let t=r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(([o,a])=>typeof o=="string"&&o&&typeof a=="string"):[];if(t.length===0)return e();let n=ft.getStore()===!0,s=null;if(!n){let o=ht;ht=new Promise(a=>{s=a}),await o}let i=new Map;try{for(let[o,a]of t)i.set(o,Object.prototype.hasOwnProperty.call(process.env,o)?process.env[o]:void 0),process.env[o]=a;return b.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await ft.run(!0,e)}finally{for(let[o,a]of i)a===void 0?delete process.env[o]:process.env[o]=a;s&&s()}}function cn(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=r||e,n=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!n||!s)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:s}}async function ln({apiBase:r,authToken:e,body:t}){let n;try{n=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(i){throw new N("network",`begin fetch failed: ${i.message}`)}let s=null;try{s=await n.json()}catch{}if(!n.ok){if(n.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(n.status===429){let i=s?.quotaInfo||{},o=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw o.code="SUBGRAPH_QUOTA_EXCEEDED",o.status=429,o.quotaInfo=i,o}if(n.status===400&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new N("begin-status",`begin returned ${n.status}`)}return s?.data||s}async function H({apiBase:r,authToken:e,payload:t}){try{let n=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});n.ok||b.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){b.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function un(r,e){let t=W(e,".ready"),n=W(e,"graph.mjs");if(J(t)&&J(n))return;tn(e,{recursive:!0});let s=W(e,".lock"),i=!1;try{let{openSync:o,closeSync:a}=await import("node:fs"),u=o(s,"wx");a(u),i=!0}catch(o){if(o.code!=="EEXIST")throw o}if(!i){let o=Date.now()+3e4;for(;Date.now()<o;){if(J(t)&&J(n))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let m=dt("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),c=dt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});m.stdout.pipe(c.stdin);let l,I,w=()=>{if(l!==void 0&&I!==void 0){if(l!==0)return d(new Error(`curl exited ${l}`));if(I!==0)return d(new Error(`tar exited ${I}`));u()}};m.on("close",v=>{l=v,w()}),c.on("close",v=>{I=v,w()}),m.on("error",d),c.on("error",d)});let{writeFileSync:o,unlinkSync:a}=await import("node:fs");o(t,"");try{a(s)}catch{}}catch(o){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new N("bundle-extract-failed",o.message)}}async function pn(r){let e=W(r,"graph.mjs");if(!J(e))throw new N("entry-missing",`graph.mjs missing under ${r}`);let t;try{t=await import(rn(e).href)}catch(s){throw new N("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let n=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!n)throw new N("entry-class-missing","no buildGraph() class export found");return n}async function yt(r,e={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=q(),n;try{n=cn()}catch(p){throw p}b.debug(`[in-process subgraph] begin '${r}' parent=${t.executionId||"<root>"}`);let s=await ln({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:r,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:o,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:m,bundleReady:c,nodeConfigs:l}=s,I=on();if(o&&o!==I)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new N("runtime-mismatch",`${I} vs ${o}`);if(!c||!a)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new N("no-bundle","workflow bundle not built yet");let w=pt(r);if(!w){let p=W(de,`${m}@${d||"0"}`);try{await un(a,p);try{fn()}catch{}}catch(_){throw _.fallback&&await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason}}}),_}try{w=await pn(p),lt(r,w,{workflowUuid:m,version:d,runtimeTag:o,cacheDir:p})}catch(_){throw ut(r,_),await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason||"IMPORT_FAILED"}}}),_.fallback?_:new N("import-failed",_.message)}}let v=Date.now(),A=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,$=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,f={...e.input||{},...$?{nodeConfigs:l}:{}},g,y;try{g=await an(A,async()=>{let _=await(typeof w=="function"&&w.prototype?.buildGraph?new w:w).buildGraph();return it({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>_.run(e.parentAgent,f,{signal:e.signal}))}),y=g&&typeof g=="object"&&"state"in g?g.state:g}catch(p){throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-v}}),p}if(g&&typeof g=="object"&&g.stoppedExternally){await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",finalState:y,durationMs:Date.now()-v}});let p=new Error(`Sub-graph '${r}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:y,durationMs:Date.now()-v}}),{finalState:y,executionId:i}}function dn(r){let e=0,t=[r];for(;t.length;){let n=t.pop(),s;try{s=gt(n)}catch{continue}if(s.isDirectory()){let i;try{i=mt(n)}catch{continue}for(let o of i)t.push(W(n,o))}else e+=s.size}return e}function fn({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!J(de))return{evicted:0,freedBytes:0};let e=mt(de),t=[],n=0;for(let a of e){let u=W(de,a),d;try{d=gt(u)}catch{continue}let m=d.isDirectory()?dn(u):d.size;n+=m,t.push({name:a,full:u,size:m,mtimeMs:d.mtimeMs})}if(n<=r)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let s=Math.floor(r*.7),i=0,o=0;for(let a of t){if(n-i<=s)break;if(!J(W(a.full,".lock")))try{nn(a.full,{recursive:!0,force:!0}),i+=a.size,o+=1}catch(u){b.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return o>0&&b.info(`[sub-graph cache] evicted ${o} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:o,freedBytes:i,totalBytes:n-i}}catch(e){return b.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var hn=2e3,gn=600*1e3,mn=new Set(["completed","failed","canceled","timeout"]);function yn(){let r=process.env.PROGRESS_API_URL;if(!r)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return r.replace(/\/executions\/?$/,"")}function Sn(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function wn(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function _n(){return process.env.EXECUTION_ID||null}function St(r,e){return e==null?r:typeof e=="function"?e(r):typeof e=="string"?e.split(".").reduce((t,n)=>t==null?t:t[n],r):r}async function wt(r,e={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=q();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=n)throw new Error(`dispatchSubgraph('${r}'): sub-graph depth ${t.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{b.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:y}=await yt(r,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=St(y,e.output);return b.info(`[sub-graph] '${r}' completed in-process`),p}catch(y){if(y instanceof N||y?.fallback)b.info(`[sub-graph] in-process fallback for '${r}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let s=yn(),i=Sn(),o=wn(),a=_n(),u=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(r)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};b.info(`[sub-graph] dispatching '${r}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let m=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(d)});if(!m.ok){let y=null,p="";try{y=await m.json(),p=y?.error||y?.message||JSON.stringify(y)}catch{p=await m.text().catch(()=>"")}if(m.status===429){let E=y?.quotaInfo||{},P=new Error(`Sub-graph '${r}' blocked by execution quota (${E.used??"?"}/${E.limit??"?"} on plan ${E.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw P.code="SUBGRAPH_QUOTA_EXCEEDED",P.status=429,P.subgraph=r,P.quotaInfo=E,P}if(m.status===400){let E=new Error(`Sub-graph '${r}' rejected input: ${p}`);throw E.code="SUBGRAPH_INVALID_INPUT",E.status=400,E.subgraph=r,E.validationErrors=y?.validationErrors||null,E.missing=y?.missing||null,E}let _=new Error(`Sub-graph '${r}' trigger rejected (${m.status}): ${p}`);throw _.code="SUBGRAPH_TRIGGER_FAILED",_.status=m.status,_.subgraph=r,_}let c=await m.json(),l=c?.data?.jobId||c?.jobId;if(!l)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(e.async)return b.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${l} (not waiting)`),{jobId:l,status:"accepted",workflow:r};let I=Number.isFinite(e.timeoutMs)?e.timeoutMs:gn,w=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:hn,v=`${s}/executions/${encodeURIComponent(l)}`,A=Date.now()+I,$="accepted",f=0;for(;Date.now()<A;){await new Promise(E=>setTimeout(E,w)),f+=1;let y=await fetch(v,{headers:{Authorization:`Bearer ${o}`}});if(!y.ok){if(y.status>=500){b.warn(`[sub-graph] status poll for ${l} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${l}: ${y.status}`)}let p=await y.json(),_=p?.data||p?.execution||p;if($=_?.status||$,mn.has($)){if($!=="completed"){let V=new Error(`Sub-graph '${r}' (${l}) ended in status '${$}'`);throw V.subgraphJobId=l,V.subgraphStatus=$,V}let E=_?.finalState||_?.state||{},P=St(E,e.output);return b.info(`[sub-graph] '${r}' (${l}) completed after ${f} polls`),P}}let g=new Error(`Sub-graph '${r}' (${l}) timed out after ${Math.round(I/1e3)}s (last status: ${$})`);throw g.subgraphJobId=l,g.subgraphStatus=$,g}import{existsSync as _t,readFileSync as In}from"node:fs";import{join as Re,dirname as It}from"node:path";var fe=class{static async loadContext(e,t,n={}){let s={},i=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=It(Re(t,e));for(let u of i){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let m=u.replace(/\.[^.]+$/,"").toLowerCase();s[m]=d}}}let o=n.discovery||{};for(let[a,u]of Object.entries(o))try{let d=Re(t,u);_t(d)&&(s[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return s}static async findAndMergeContextFiles(e,t,n){let s=[],i=t;for(;i.startsWith(n);){let o=Re(i,e);if(_t(o))try{s.unshift(await this.loadFile(o))}catch(u){console.warn(`[workflow] could not load ${e} from ${o}: ${u.message}`)}let a=It(i);if(a===i)break;i=a}return s.length===0?null:s.every(o=>typeof o=="string")?s.join(`
34
+ ${i}`);let a=n(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Oe(d,Z);if(ot(l)){let I=JSON.parse(st(l,"utf-8"));I.currentNode=this.name,xe(l,JSON.stringify(I,null,2),"utf-8")}let c=Oe(d,"..",Z);if(ot(c))try{let I=JSON.parse(st(c,"utf-8"));I.currentNode=this.name,xe(c,JSON.stringify(I,null,2),"utf-8")}catch{}}}catch(l){b.debug(`[workflow] could not update session info: ${l.message}`)}let m=null;for(let l=0;l<=this.retries;l++)try{b.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=n().config||{},I=c.agents||{},w=this.config.agent??I[this.name]??null,v={state:n()};w&&(v.preferredAgent=w);let A={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},$=e?._coreInvokeAgent;$||($=(await Promise.resolve().then(()=>(ke(),Te))).invokeAgent);let f=await $(i,v,A),g,y;if(typeof f=="string"?(g=f,y=null):f.structured?(g=f.raw||JSON.stringify(f.structured,null,2),y=f.structured):(g=f.raw||JSON.stringify(f,null,2),y=f.extracted||null),d)try{let p=Oe(d,this.name,"raw_stream_output.txt");Kt(Xt(p),{recursive:!0}),xe(p,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(p){b.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&y){b.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let p=y;if(typeof this.onComplete=="function")try{p=await this.onComplete(n(),y)}catch(_){b.warn(`[workflow] onComplete hook failed: ${_.message}`)}return{success:!0,output:p,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:g}),raw:g}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(g);return b.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),O.step("Output parsed"),{success:!0,output:p,raw:g}}return{success:!0,output:g,raw:g}}catch(c){m=c,l<this.retries&&b.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:m.message,raw:null}}};ee();ee();import{mkdirSync as tn,existsSync as J,statSync as gt,readdirSync as mt,rmSync as nn}from"node:fs";import{spawn as dt}from"node:child_process";import{join as W}from"node:path";import{pathToFileURL as rn}from"node:url";import{AsyncLocalStorage as sn}from"node:async_hooks";import{AsyncLocalStorage as Qt}from"node:async_hooks";var re=new Qt;function q(){let r=re.getStore();return r||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function it(r,e){let t=re.getStore()||q(),n=Object.freeze({executionId:r.executionId,parentExecutionId:r.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(r.executionId!==t.executionId?1:0),conversationId:r.conversationId!==void 0?r.conversationId:t.conversationId??null,dispatchMode:r.dispatchMode??null,agent:r.agent!==void 0?r.agent:t.agent??null,signal:r.signal!==void 0?r.signal:t.signal??null});return re.run(n,e)}function at(r,e,t){let n=re.getStore()||q(),s=Object.freeze({...n,agent:r??n.agent??null,signal:e??n.signal??null});return re.run(s,t)}var Pe=new Map,Ne=new Map,ct=new Map;function lt(r,e,t={}){if(!r||typeof r!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Pe.set(r,e),Ne.set(r,"ready"),ct.set(r,{...t,cachedAt:Date.now()})}function ut(r,e){Ne.set(r,"failed"),ct.set(r,{error:e?.message||String(e),failedAt:Date.now()}),Pe.delete(r)}function pt(r){return Ne.get(r)==="ready"?Pe.get(r):null}var de=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function on(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}},ft=new sn,ht=Promise.resolve();async function an(r,e){let t=r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(([o,a])=>typeof o=="string"&&o&&typeof a=="string"):[];if(t.length===0)return e();let n=ft.getStore()===!0,s=null;if(!n){let o=ht;ht=new Promise(a=>{s=a}),await o}let i=new Map;try{for(let[o,a]of t)i.set(o,Object.prototype.hasOwnProperty.call(process.env,o)?process.env[o]:void 0),process.env[o]=a;return b.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await ft.run(!0,e)}finally{for(let[o,a]of i)a===void 0?delete process.env[o]:process.env[o]=a;s&&s()}}function cn(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=r||e,n=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!n||!s)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:s}}async function ln({apiBase:r,authToken:e,body:t}){let n;try{n=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(i){throw new N("network",`begin fetch failed: ${i.message}`)}let s=null;try{s=await n.json()}catch{}if(!n.ok){if(n.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(n.status===429){let i=s?.quotaInfo||{},o=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw o.code="SUBGRAPH_QUOTA_EXCEEDED",o.status=429,o.quotaInfo=i,o}if(n.status===400&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new N("begin-status",`begin returned ${n.status}`)}return s?.data||s}async function H({apiBase:r,authToken:e,payload:t}){try{let n=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});n.ok||b.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){b.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function un(r,e){let t=W(e,".ready"),n=W(e,"graph.mjs");if(J(t)&&J(n))return;tn(e,{recursive:!0});let s=W(e,".lock"),i=!1;try{let{openSync:o,closeSync:a}=await import("node:fs"),u=o(s,"wx");a(u),i=!0}catch(o){if(o.code!=="EEXIST")throw o}if(!i){let o=Date.now()+3e4;for(;Date.now()<o;){if(J(t)&&J(n))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let m=dt("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),l=dt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});m.stdout.pipe(l.stdin);let c,I,w=()=>{if(c!==void 0&&I!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(I!==0)return d(new Error(`tar exited ${I}`));u()}};m.on("close",v=>{c=v,w()}),l.on("close",v=>{I=v,w()}),m.on("error",d),l.on("error",d)});let{writeFileSync:o,unlinkSync:a}=await import("node:fs");o(t,"");try{a(s)}catch{}}catch(o){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new N("bundle-extract-failed",o.message)}}async function pn(r){let e=W(r,"graph.mjs");if(!J(e))throw new N("entry-missing",`graph.mjs missing under ${r}`);let t;try{t=await import(rn(e).href)}catch(s){throw new N("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let n=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!n)throw new N("entry-class-missing","no buildGraph() class export found");return n}async function yt(r,e={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=q(),n;try{n=cn()}catch(p){throw p}b.debug(`[in-process subgraph] begin '${r}' parent=${t.executionId||"<root>"}`);let s=await ln({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:r,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:o,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:m,bundleReady:l,nodeConfigs:c}=s,I=on();if(o&&o!==I)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new N("runtime-mismatch",`${I} vs ${o}`);if(!l||!a)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new N("no-bundle","workflow bundle not built yet");let w=pt(r);if(!w){let p=W(de,`${m}@${d||"0"}`);try{await un(a,p);try{fn()}catch{}}catch(_){throw _.fallback&&await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason}}}),_}try{w=await pn(p),lt(r,w,{workflowUuid:m,version:d,runtimeTag:o,cacheDir:p})}catch(_){throw ut(r,_),await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason||"IMPORT_FAILED"}}}),_.fallback?_:new N("import-failed",_.message)}}let v=Date.now(),A=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,$=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...$?{nodeConfigs:c}:{}},g,y;try{g=await an(A,async()=>{let _=await(typeof w=="function"&&w.prototype?.buildGraph?new w:w).buildGraph();return it({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>_.run(e.parentAgent,f,{signal:e.signal}))}),y=g&&typeof g=="object"&&"state"in g?g.state:g}catch(p){throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-v}}),p}if(g&&typeof g=="object"&&g.stoppedExternally){await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",finalState:y,durationMs:Date.now()-v}});let p=new Error(`Sub-graph '${r}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:y,durationMs:Date.now()-v}}),{finalState:y,executionId:i}}function dn(r){let e=0,t=[r];for(;t.length;){let n=t.pop(),s;try{s=gt(n)}catch{continue}if(s.isDirectory()){let i;try{i=mt(n)}catch{continue}for(let o of i)t.push(W(n,o))}else e+=s.size}return e}function fn({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!J(de))return{evicted:0,freedBytes:0};let e=mt(de),t=[],n=0;for(let a of e){let u=W(de,a),d;try{d=gt(u)}catch{continue}let m=d.isDirectory()?dn(u):d.size;n+=m,t.push({name:a,full:u,size:m,mtimeMs:d.mtimeMs})}if(n<=r)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let s=Math.floor(r*.7),i=0,o=0;for(let a of t){if(n-i<=s)break;if(!J(W(a.full,".lock")))try{nn(a.full,{recursive:!0,force:!0}),i+=a.size,o+=1}catch(u){b.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return o>0&&b.info(`[sub-graph cache] evicted ${o} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:o,freedBytes:i,totalBytes:n-i}}catch(e){return b.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var hn=2e3,gn=600*1e3,mn=new Set(["completed","failed","canceled","timeout"]);function yn(){let r=process.env.PROGRESS_API_URL;if(!r)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return r.replace(/\/executions\/?$/,"")}function Sn(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function wn(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function _n(){return process.env.EXECUTION_ID||null}function St(r,e){return e==null?r:typeof e=="function"?e(r):typeof e=="string"?e.split(".").reduce((t,n)=>t==null?t:t[n],r):r}async function wt(r,e={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=q();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=n)throw new Error(`dispatchSubgraph('${r}'): sub-graph depth ${t.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{b.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:y}=await yt(r,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=St(y,e.output);return b.info(`[sub-graph] '${r}' completed in-process`),p}catch(y){if(y instanceof N||y?.fallback)b.info(`[sub-graph] in-process fallback for '${r}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let s=yn(),i=Sn(),o=wn(),a=_n(),u=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(r)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};b.info(`[sub-graph] dispatching '${r}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let m=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(d)});if(!m.ok){let y=null,p="";try{y=await m.json(),p=y?.error||y?.message||JSON.stringify(y)}catch{p=await m.text().catch(()=>"")}if(m.status===429){let E=y?.quotaInfo||{},P=new Error(`Sub-graph '${r}' blocked by execution quota (${E.used??"?"}/${E.limit??"?"} on plan ${E.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw P.code="SUBGRAPH_QUOTA_EXCEEDED",P.status=429,P.subgraph=r,P.quotaInfo=E,P}if(m.status===400){let E=new Error(`Sub-graph '${r}' rejected input: ${p}`);throw E.code="SUBGRAPH_INVALID_INPUT",E.status=400,E.subgraph=r,E.validationErrors=y?.validationErrors||null,E.missing=y?.missing||null,E}let _=new Error(`Sub-graph '${r}' trigger rejected (${m.status}): ${p}`);throw _.code="SUBGRAPH_TRIGGER_FAILED",_.status=m.status,_.subgraph=r,_}let l=await m.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return b.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:r};let I=Number.isFinite(e.timeoutMs)?e.timeoutMs:gn,w=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:hn,v=`${s}/executions/${encodeURIComponent(c)}`,A=Date.now()+I,$="accepted",f=0;for(;Date.now()<A;){await new Promise(E=>setTimeout(E,w)),f+=1;let y=await fetch(v,{headers:{Authorization:`Bearer ${o}`}});if(!y.ok){if(y.status>=500){b.warn(`[sub-graph] status poll for ${c} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${y.status}`)}let p=await y.json(),_=p?.data||p?.execution||p;if($=_?.status||$,mn.has($)){if($!=="completed"){let V=new Error(`Sub-graph '${r}' (${c}) ended in status '${$}'`);throw V.subgraphJobId=c,V.subgraphStatus=$,V}let E=_?.finalState||_?.state||{},P=St(E,e.output);return b.info(`[sub-graph] '${r}' (${c}) completed after ${f} polls`),P}}let g=new Error(`Sub-graph '${r}' (${c}) timed out after ${Math.round(I/1e3)}s (last status: ${$})`);throw g.subgraphJobId=c,g.subgraphStatus=$,g}import{existsSync as _t,readFileSync as In}from"node:fs";import{join as Re,dirname as It}from"node:path";var fe=class{static async loadContext(e,t,n={}){let s={},i=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=It(Re(t,e));for(let u of i){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let m=u.replace(/\.[^.]+$/,"").toLowerCase();s[m]=d}}}let o=n.discovery||{};for(let[a,u]of Object.entries(o))try{let d=Re(t,u);_t(d)&&(s[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return s}static async findAndMergeContextFiles(e,t,n){let s=[],i=t;for(;i.startsWith(n);){let o=Re(i,e);if(_t(o))try{s.unshift(await this.loadFile(o))}catch(u){console.warn(`[workflow] could not load ${e} from ${o}: ${u.message}`)}let a=It(i);if(a===i)break;i=a}return s.length===0?null:s.every(o=>typeof o=="string")?s.join(`
35
35
 
36
36
  ---
37
37
 
38
38
  `):s.every(o=>typeof o=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=In(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:n}=await import("url"),s=await import(n(e).href);return s.default||s}return t}};import{mkdirSync as vt,existsSync as Be,writeFileSync as bt,unlinkSync as bn}from"node:fs";import{join as z,resolve as At}from"node:path";import{config as En}from"dotenv";import{zodToJsonSchema as Et}from"zod-to-json-schema";import{z as he}from"zod";import $n from"handlebars";function vn({traceFrom:r,sessionId:e,sessionPath:t,idSource:n,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let o=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${r} pid=${process.pid} ppid=${o} sessionId=${e} source=${n} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let m=(new Error("session trace").stack||"").split(`
39
39
  `).slice(2,14).join(`
40
40
  `);console.log(`[zibby:session] stack (${r}):
41
- ${m}`)}}function An(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Tn(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return At(String(e).trim())}catch{return String(e).trim()}}function kn(){An()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function xn({sessionPath:r,sessionId:e}){r&&typeof r=="string"&&(process.env.ZIBBY_SESSION_PATH=r),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function On(r={}){let e=Qe.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,s=r.paths?.sessionPrefix;return s?`${s}_${n}`:n}function Pn({cwd:r=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,o="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let d=At(String(process.env.ZIBBY_SESSION_PATH));d&&(s=d,o="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,o="ZIBBY_SESSION_ID";else{let c=e.sessionId!=null?String(e.sessionId).trim():"";c&&c!=="last"?(a=c,o="config.sessionId"):(a=On(e),o="generated")}i=i??Date.now();let m=e.paths?.output||pe;s=z(r,m,Ke,a)}let u=!Be(s);return u&&vt(s,{recursive:!0}),(u||o!=="initialState.sessionPath")&&vn({traceFrom:n,sessionId:a,sessionPath:s,idSource:o,mkdirFresh:u}),xn({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var $t=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,n={}){if(!(t instanceof L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let o=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:o.workflow,retries:o.retries,onComplete:o.onComplete,execute:async d=>{let m=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,c;return typeof o.input=="function"?c=o.input(m):o.input&&typeof o.input=="object"?c=o.input:c={},wt(o.workflow,{input:c,async:o.async===!0,conversationId:typeof o.conversationId=="function"?o.conversationId(m):o.conversationId,output:o.output,timeoutMs:o.timeoutMs,pollIntervalMs:o.pollIntervalMs,signal:m?._signal,parentAgent:d?.agent})}},u=new L(a);return u.name=e,this.nodes.set(e,u),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let s=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof L?t:new L(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){let n=this.edges.get(e);return n===void 0?this.edges.set(e,t):typeof n=="string"?n!==t&&this.edges.set(e,[n,t]):Array.isArray(n)?n.includes(t)||n.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:n}={}){let s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:n}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,n=i=>{t.set(i,1);for(let o of this._simpleTargets(i)){if(!o||o==="END")continue;let a=t.get(o)||0;a===1?e.add(`${i}->${o}`):a===0&&n(o)}t.set(i,2)};this.entryPoint&&n(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let o of this._simpleTargets(i))!o||o==="END"||e.has(`${i}->${o}`)||s.set(o,(s.get(o)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,s,i){let o=n;for(let a=e.length-1;a>=0;a--){let u=e[a],d=o;o=()=>u(t,d,s,i)}return o()}serialize(){let e=[],t={};for(let[c,l]of this.nodes){let I=this.nodeTypeMap.get(c)||(l?.config?._isRouter===!0?"decision":c);e.push({id:c,type:I,data:{nodeType:I,label:c}});let w={};l._isCustomCode&&typeof l.execute=="function"&&(w.customCode=l.execute.toString());let v=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;v&&(w.description=v);let A=this.nodePrompts.get(c);if(A)w.prompt=A;else if(typeof l.prompt=="function")try{let p=l.prompt({});typeof p=="string"&&p.trim()&&(w.prompt=p,w.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(w.executeCode=l.customExecute.toString()),typeof l?.config?.dispatchesWorkflow=="string"&&l.config.dispatchesWorkflow.trim()&&(w.dispatchesWorkflow=l.config.dispatchesWorkflow.trim()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let p=null;if(typeof he?.toJSONSchema=="function")try{p=he.toJSONSchema(l.outputSchema)}catch{}if(!p)try{p=Et(l.outputSchema,{target:"openApi3"})}catch{}w.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:l.outputSchema}}else w.outputSchema={schema:l.outputSchema};let $=(this.resolvedToolsMap||{})[c];$?.toolIds&&(w.tools=$.toolIds);let f=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;f&&f.length>0&&(w.skills=[...f]);let g=Array.isArray(l?.config?.plugins)?l.config.plugins:Array.isArray(l?.plugins)?l.plugins:null;g&&g.length>0&&(w.plugins=g.map(p=>p&&typeof p=="object"?{...p}:p));let y=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;y&&y.length>0&&(w.stores=y.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(w).length>0&&(t[c]=w)}let n=[];for(let[c,l]of this.edges)if(typeof l=="string")n.push({source:c,target:l});else if(Array.isArray(l))for(let I of l)n.push({source:c,target:I});else if(l.conditional){let I=this.conditionalCodeMap.get(c)||l.routes.toString(),w=this._inferConditionalTargets(l.routes,l.labels),v=l.labels||{},A=this.nodes.get(c),$=A?.config?._isRouter===!0||this.nodeTypeMap.get(c)==="decision"||!A,f=c;if(!$){let g=`${c}__branch`;e.push({id:g,type:"decision",data:{nodeType:"decision",label:g}}),n.push({source:c,target:g}),f=g}for(let g of w){let y={source:f,target:g,data:{conditionalCode:I}};v[g]&&(y.label=v[g]),n.push(y)}}let s=c=>{if(!c)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(c)}catch{}try{return Et(c,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let i=0;for(let c of n)if(c.target==="END"){i+=1;let l=`END__${i}`;c.target=l,e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}})}for(let c of this.nodes.keys())if(!this.edges.has(c)){i+=1;let l=`END__${i}`;e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:c,target:l})}let o=this._topoOrderNodes(e,n),a=this._runtimeSchema(),u=s(a||this.stateSchema),d=s(this.inputSchema),m=s(this.contextSchema);return{nodes:o,edges:n,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:m}}_topoOrderNodes(e,t){let n=new Map(e.map((c,l)=>[c.id,l])),s=new Map(e.map(c=>[c.id,c])),i=new Map(e.map(c=>[c.id,0])),o=new Map(e.map(c=>[c.id,[]]));for(let c of t)o.has(c.source)&&i.has(c.target)&&(o.get(c.source).push(c.target),i.set(c.target,i.get(c.target)+1));let a=new Set,u=new Set(n.keys()),d=[...u].filter(c=>i.get(c)===0),m=[];for(;m.length<e.length;){let c;if(d.length>0){if(d.sort((l,I)=>n.get(l)-n.get(I)),c=d.shift(),a.has(c))continue}else c=[...u].sort((l,I)=>n.get(l)-n.get(I))[0];a.add(c),u.delete(c),m.push(s.get(c));for(let l of o.get(c)||[])i.set(l,i.get(l)-1),i.get(l)<=0&&!a.has(l)&&d.push(l)}return m}_inferConditionalTargets(e,t){let n=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,o;for(;(o=i.exec(n))!==null;){let d=o[2]!==void 0?o[2]:o[3];d!==void 0&&d!==""&&s.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let u=new Set;for(let d of s)a.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,m;for(;(m=d.exec(n))!==null;)u.add(m[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");n=e.definitions[s]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],s=e.properties||{},i=e.required||[];for(let[o,a]of Object.entries(s)){let u=t?`${t}.${o}`:o;n.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(o),optional:!i.includes(o)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${u}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${s}: ${i}`);else if(Array.isArray(i)){let o=i.length,a=i.filter(d=>d?.passed===!0).length,u=i.some(d=>d?.passed!==void 0);n.push(u?`${s}: ${a}/${o} passed${o-a?`, ${o-a} failed`:""}`:`${s}: ${o} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(S){let h=new Error(`agent.normalizeInput() rejected the trigger input: ${S?.message||S}`);throw h.cause=S,h.code=S?.code||"NORMALIZE_INPUT_FAILED",h}let s=new AbortController;n.signal&&(n.signal.aborted?s.abort():n.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,o=t.cwd||process.cwd();En({path:z(o,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let S=z(o,".zibby.config.js");Be(S)&&(a=(await import(S)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let S=a?.agent;S?.provider?u=S.provider:S?.gemini?u="gemini":S?.claude?u="claude":S?.cursor?u="cursor":S?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},m=this._runtimeSchema();if(m){let S=m.safeParse(t);if(!S.success){let h=S.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),h.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${h.join(", ")}`)}O.step("State validated against schema")}let c=Tn(),l=t.sessionPath||c;l||kn();let{sessionPath:I,sessionTimestamp:w,sessionId:v}=Pn({cwd:o,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${v}`);let A=await fe.loadContext(t.specPath||"",o,d);Object.keys(A).length>0&&O.step(`Context loaded: ${Object.keys(A).join(", ")}`);let $=t.outputPath;!$&&t.specPath&&(e?.calculateOutputPath?$=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ce({...t,config:a,agentType:u,outputPath:$,sessionPath:I,sessionTimestamp:w,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(ve(),tt)),p=a.skills&&typeof a.skills=="object"?a.skills:{},_=Object.values(p).filter(S=>S&&typeof S=="object"&&typeof S.id=="string"),E=S=>{for(let h of _)if(h.id===S)return h;return y(S)},P=new Set;for(let[,S]of this.nodes)for(let h of S.config?.skills||[])P.add(h);for(let S of P){let h=E(S);if(typeof h?.middleware=="function")try{let C=await h.middleware();typeof C=="function"&&g.set(S,C)}catch{}}let{backEdges:V,joinDegree:Tt}=this._analyzeFlow(),ge=new Map,K=[],me=(S,h,C)=>{if(!S||S==="END")return;let j=Tt.get(S)||0;if(C&&j>1&&!V.has(`${h}->${S}`)){let X=(ge.get(S)||0)+1;if(X<j){ge.set(S,X);return}ge.set(S,0)}K.includes(S)||K.push(S)};this.entryPoint&&K.push(this.entryPoint);let se=[],Ce=a?.recursionLimit??100,kt=0;try{for(;K.length>0;){let h=K.pop();if(!h||h==="END")continue;if(++kt>Ce)throw new Error(`Workflow exceeded recursion limit (${Ce}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let C=z(I,Xe);if(Be(C)){try{bn(C)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
41
+ ${m}`)}}function An(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Tn(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return At(String(e).trim())}catch{return String(e).trim()}}function kn(){An()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function xn({sessionPath:r,sessionId:e}){r&&typeof r=="string"&&(process.env.ZIBBY_SESSION_PATH=r),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function On(r={}){let e=Qe.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,s=r.paths?.sessionPrefix;return s?`${s}_${n}`:n}function Pn({cwd:r=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,o="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let d=At(String(process.env.ZIBBY_SESSION_PATH));d&&(s=d,o="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,o="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,o="config.sessionId"):(a=On(e),o="generated")}i=i??Date.now();let m=e.paths?.output||pe;s=z(r,m,Ke,a)}let u=!Be(s);return u&&vt(s,{recursive:!0}),(u||o!=="initialState.sessionPath")&&vn({traceFrom:n,sessionId:a,sessionPath:s,idSource:o,mkdirFresh:u}),xn({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var $t=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,n={}){if(!(t instanceof L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let o=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:o.workflow,retries:o.retries,onComplete:o.onComplete,execute:async d=>{let m=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof o.input=="function"?l=o.input(m):o.input&&typeof o.input=="object"?l=o.input:l={},wt(o.workflow,{input:l,async:o.async===!0,conversationId:typeof o.conversationId=="function"?o.conversationId(m):o.conversationId,output:o.output,timeoutMs:o.timeoutMs,pollIntervalMs:o.pollIntervalMs,signal:m?._signal,parentAgent:d?.agent})}},u=new L(a);return u.name=e,this.nodes.set(e,u),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let s=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof L?t:new L(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){let n=this.edges.get(e);return n===void 0?this.edges.set(e,t):typeof n=="string"?n!==t&&this.edges.set(e,[n,t]):Array.isArray(n)?n.includes(t)||n.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:n}={}){let s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:n}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,n=i=>{t.set(i,1);for(let o of this._simpleTargets(i)){if(!o||o==="END")continue;let a=t.get(o)||0;a===1?e.add(`${i}->${o}`):a===0&&n(o)}t.set(i,2)};this.entryPoint&&n(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let o of this._simpleTargets(i))!o||o==="END"||e.has(`${i}->${o}`)||s.set(o,(s.get(o)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,s,i){let o=n;for(let a=e.length-1;a>=0;a--){let u=e[a],d=o;o=()=>u(t,d,s,i)}return o()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let I=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:I,data:{nodeType:I,label:l}});let w={};c._isCustomCode&&typeof c.execute=="function"&&(w.customCode=c.execute.toString());let v=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;v&&(w.description=v);let A=this.nodePrompts.get(l);if(A)w.prompt=A;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(w.prompt=p,w.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(w.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(w.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(w.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof he?.toJSONSchema=="function")try{p=he.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Et(c.outputSchema,{target:"openApi3"})}catch{}w.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else w.outputSchema={schema:c.outputSchema};let $=(this.resolvedToolsMap||{})[l];$?.toolIds&&(w.tools=$.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(w.skills=[...f]);let g=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;g&&g.length>0&&(w.plugins=g.map(p=>p&&typeof p=="object"?{...p}:p));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(w.stores=y.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(w).length>0&&(t[l]=w)}let n=[];for(let[l,c]of this.edges)if(typeof c=="string")n.push({source:l,target:c});else if(Array.isArray(c))for(let I of c)n.push({source:l,target:I});else if(c.conditional){let I=this.conditionalCodeMap.get(l)||c.routes.toString(),w=this._inferConditionalTargets(c.routes,c.labels),v=c.labels||{},A=this.nodes.get(l),$=A?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!A,f=l;if(!$){let g=`${l}__branch`;e.push({id:g,type:"decision",data:{nodeType:"decision",label:g}}),n.push({source:l,target:g}),f=g}for(let g of w){let y={source:f,target:g,data:{conditionalCode:I}};v[g]&&(y.label=v[g]),n.push(y)}}let s=l=>{if(!l)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(l)}catch{}try{return Et(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let i=0;for(let l of n)if(l.target==="END"){i+=1;let c=`END__${i}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:l,target:c})}let o=this._topoOrderNodes(e,n),a=this._runtimeSchema(),u=s(a||this.stateSchema),d=s(this.inputSchema),m=s(this.contextSchema);return{nodes:o,edges:n,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:m}}_topoOrderNodes(e,t){let n=new Map(e.map((l,c)=>[l.id,c])),s=new Map(e.map(l=>[l.id,l])),i=new Map(e.map(l=>[l.id,0])),o=new Map(e.map(l=>[l.id,[]]));for(let l of t)o.has(l.source)&&i.has(l.target)&&(o.get(l.source).push(l.target),i.set(l.target,i.get(l.target)+1));let a=new Set,u=new Set(n.keys()),d=[...u].filter(l=>i.get(l)===0),m=[];for(;m.length<e.length;){let l;if(d.length>0){if(d.sort((c,I)=>n.get(c)-n.get(I)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,I)=>n.get(c)-n.get(I))[0];a.add(l),u.delete(l),m.push(s.get(l));for(let c of o.get(l)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return m}_inferConditionalTargets(e,t){let n=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,o;for(;(o=i.exec(n))!==null;){let d=o[2]!==void 0?o[2]:o[3];d!==void 0&&d!==""&&s.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let u=new Set;for(let d of s)a.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,m;for(;(m=d.exec(n))!==null;)u.add(m[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");n=e.definitions[s]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],s=e.properties||{},i=e.required||[];for(let[o,a]of Object.entries(s)){let u=t?`${t}.${o}`:o;n.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(o),optional:!i.includes(o)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${u}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${s}: ${i}`);else if(Array.isArray(i)){let o=i.length,a=i.filter(d=>d?.passed===!0).length,u=i.some(d=>d?.passed!==void 0);n.push(u?`${s}: ${a}/${o} passed${o-a?`, ${o-a} failed`:""}`:`${s}: ${o} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(S){let h=new Error(`agent.normalizeInput() rejected the trigger input: ${S?.message||S}`);throw h.cause=S,h.code=S?.code||"NORMALIZE_INPUT_FAILED",h}let s=new AbortController;n.signal&&(n.signal.aborted?s.abort():n.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,o=t.cwd||process.cwd();En({path:z(o,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let S=z(o,".zibby.config.js");Be(S)&&(a=(await import(S)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let S=a?.agent;S?.provider?u=S.provider:S?.gemini?u="gemini":S?.claude?u="claude":S?.cursor?u="cursor":S?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},m=this._runtimeSchema();if(m){let S=m.safeParse(t);if(!S.success){let h=S.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),h.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${h.join(", ")}`)}O.step("State validated against schema")}let l=Tn(),c=t.sessionPath||l;c||kn();let{sessionPath:I,sessionTimestamp:w,sessionId:v}=Pn({cwd:o,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${v}`);let A=await fe.loadContext(t.specPath||"",o,d);Object.keys(A).length>0&&O.step(`Context loaded: ${Object.keys(A).join(", ")}`);let $=t.outputPath;!$&&t.specPath&&(e?.calculateOutputPath?$=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ce({...t,config:a,agentType:u,outputPath:$,sessionPath:I,sessionTimestamp:w,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(ve(),tt)),p=a.skills&&typeof a.skills=="object"?a.skills:{},_=Object.values(p).filter(S=>S&&typeof S=="object"&&typeof S.id=="string"),E=S=>{for(let h of _)if(h.id===S)return h;return y(S)},P=new Set;for(let[,S]of this.nodes)for(let h of S.config?.skills||[])P.add(h);for(let S of P){let h=E(S);if(typeof h?.middleware=="function")try{let C=await h.middleware();typeof C=="function"&&g.set(S,C)}catch{}}let{backEdges:V,joinDegree:Tt}=this._analyzeFlow(),ge=new Map,K=[],me=(S,h,C)=>{if(!S||S==="END")return;let j=Tt.get(S)||0;if(C&&j>1&&!V.has(`${h}->${S}`)){let X=(ge.get(S)||0)+1;if(X<j){ge.set(S,X);return}ge.set(S,0)}K.includes(S)||K.push(S)};this.entryPoint&&K.push(this.entryPoint);let se=[],Ce=a?.recursionLimit??100,kt=0;try{for(;K.length>0;){let h=K.pop();if(!h||h==="END")continue;if(++kt>Ce)throw new Error(`Workflow exceeded recursion limit (${Ce}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let C=z(I,Xe);if(Be(C)){try{bn(C)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
42
42
  \u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:se,stoppedExternally:!0};let j=this.nodes.get(h);if(!j)throw new Error(`Node '${h}' not found in graph`);let X=JSON.stringify({sessionPath:I,sessionTimestamp:w,currentNode:h,createdAt:new Date().toISOString(),config:f.get("config")}),xt=z(I,Z);bt(xt,X,"utf-8");let Me=f.get("config")?.paths?.output||pe,Ot=z(o,Me,Z);vt(z(o,Me),{recursive:!0});try{bt(Ot,X,"utf-8")}catch{}let je=t.onPipelineProgress;if(typeof je=="function")try{je({cwd:o,sessionPath:I,sessionId:v,outputBase:f.get("config")?.paths?.output||pe,currentNode:h})}catch{}let Pt=(this.resolvedToolsMap||{})[h]||null;f.set("_currentNodeTools",Pt);let Nt=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Nt[h]||{}),O.nodeStart(h);let De=Date.now(),oe=this.nodePrompts.get(h);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(ke(),Te));this._invokeAgent=k.invokeAgent}let Rt=this._invokeAgent,ye={},Bt=j.config?.skills||[];for(let k of Bt){let R=E(k);if(typeof R?.invokeAgentOptions=="function")try{let T=R.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:h});T&&typeof T=="object"&&(ye={...ye,...T})}catch(T){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${T.message}`)}}let Le=async(k,R,T={})=>{let M=Rt(k,R,{...ye,...T,signal:s.signal});return M.catch(()=>{}),s.signal.aborted?M:Promise.race([M,new Promise((Y,D)=>{let B=()=>{setTimeout(()=>{let Q=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);Q.name="AbortError",D(Q)},i)};s.signal.addEventListener("abort",B,{once:!0})})])},Ct=async(k={},R={})=>{let T=R.prompt||"";if(oe){let M=this._compiledPrompts.get(h);M||(M=$n.compile(oe,{noEscape:!0}),this._compiledPrompts.set(h,M));try{T=M(k)}catch(Y){throw console.error(`\u274C Template rendering failed for node '${h}':`,Y.message),new Error(`Template rendering failed: ${Y.message}`,{cause:Y})}}else if(!T)throw new Error(`No prompt template configured for node '${h}' and no prompt provided in options`);return Le(T,{state:f.getAll(),images:R.images||[]},{model:R.model||f.get("model"),workspace:f.get("workspace"),schema:R.schema,...R,signal:s.signal})},We=f.getAll(),Mt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of Mt)Object.prototype.hasOwnProperty.call(We,k)&&console.warn(`[workflow] node "${h}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ue={...We,state:f,invokeAgent:Ct,_coreInvokeAgent:Le,agent:e,nodeId:h,promptTemplate:oe,getPromptTemplate:()=>oe};try{let k=(j.config?.skills||[]).map(B=>g.get(B)).filter(Boolean),R=[...this.middleware,...k],T;T=await at(e,s.signal,async()=>R.length>0?this._composeMiddleware(R,h,async()=>j.execute(Ue,f),f.getAll(),f):j.execute(Ue,f));let M=Date.now()-De;if(se.push({node:h,success:T.success,duration:M,timestamp:new Date().toISOString()}),!T.success){if(s.signal.aborted)return O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:se,stoppedExternally:!0};f.append("errors",{node:h,error:T.error});let B=j.config?.retries||0,Q=`${h}_retries`,ie=f.getAll()[Q]||0;if(ie<B){O.stepInfo(`Retrying (attempt ${ie+1}/${B})`),f.update({[Q]:ie+1,[`${h}_raw`]:T.raw});continue}throw O.nodeFailed(h,T.error,{duration:M}),new Error(`Node '${h}' failed after ${ie} attempts: ${T.error}`)}f.update({[h]:T.output});let Y=this._summarizeNodeOutput(h,T.output);O.nodeComplete(h,{duration:M,details:Y});let D=this.edges.get(h);if(D)if(D.conditional){let B=D.routes(f.getAll());O.route(h,B),me(B,h,!1)}else if(Array.isArray(D))for(let B=D.length-1;B>=0;B--)me(D[B],h,!0);else me(D,h,!0)}catch(k){throw O.isInsideNode&&O.nodeFailed(h,k.message,{duration:Date.now()-De}),f.set("failed",!0),f.set("failedAt",h),k}}O.graphComplete();let S={success:!0,state:f.getAll(),executionLog:se};return e&&typeof e.onComplete=="function"&&await e.onComplete(S),S}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(S){console.warn(`[workflow] agent.cleanup() failed: ${S.message}`)}}}};export{$t as WorkflowGraph,kn as clearInheritedSessionEnvForFreshRun,On as generateWorkflowSessionId,Tn as readPinnedSessionPathFromEnv,Pn as resolveWorkflowSession,An as shouldTrustInheritedSessionEnv,xn as syncProcessEnvToSession};
package/dist/index.js CHANGED
@@ -38,7 +38,7 @@ ${i}`);let a=n(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let d=Ge(u,G);
38
38
  `):s.every(r=>typeof r=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=Vo(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:n}=await import("url"),s=await import(n(e).href);return s.default||s}return t}};import{mkdirSync as Vt,existsSync as Ze,writeFileSync as Yt,unlinkSync as Ko}from"node:fs";import{join as V,resolve as Kt}from"node:path";import{config as qo}from"dotenv";import{zodToJsonSchema as Zt}from"zod-to-json-schema";import{z as be}from"zod";import Xo from"handlebars";function Qo({traceFrom:o,sessionId:e,sessionPath:t,idSource:n,mkdirFresh:s}){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=${n} mkdir=${s?"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(`
39
39
  `).slice(2,14).join(`
40
40
  `);console.log(`[zibby:session] stack (${o}):
41
- ${h}`)}}function qt(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Xt(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Kt(String(e).trim())}catch{return String(e).trim()}}function Qt(){qt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function eo({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 to(o={}){let e=je.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,s=o.paths?.sessionPrefix;return s?`${s}_${n}`:n}function oo({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,r="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=Kt(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,r="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,r="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,r="config.sessionId"):(a=to(e),r="generated")}i=i??Date.now();let h=e.paths?.output||le;s=V(o,h,Ce,a)}let l=!Ze(s);return l&&Vt(s,{recursive:!0}),(l||r!=="initialState.sessionPath")&&Qo({traceFrom:n,sessionId:a,sessionPath:s,idSource:r,mkdirFresh:l}),eo({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}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.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,n={}){if(!(t instanceof F)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let r=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:r.workflow,retries:r.retries,onComplete:r.onComplete,execute:async u=>{let h=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof r.input=="function"?d=r.input(h):r.input&&typeof r.input=="object"?d=r.input:d={},Je(r.workflow,{input:d,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(h):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:h?._signal,parentAgent:u?.agent})}},l=new F(a);return l.name=e,this.nodes.set(e,l),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let s=!(t instanceof F)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof F?t:new F(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){let n=this.edges.get(e);return n===void 0?this.edges.set(e,t):typeof n=="string"?n!==t&&this.edges.set(e,[n,t]):Array.isArray(n)?n.includes(t)||n.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:n}={}){let s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:n}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,n=i=>{t.set(i,1);for(let r of this._simpleTargets(i)){if(!r||r==="END")continue;let a=t.get(r)||0;a===1?e.add(`${i}->${r}`):a===0&&n(r)}t.set(i,2)};this.entryPoint&&n(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let r of this._simpleTargets(i))!r||r==="END"||e.has(`${i}->${r}`)||s.set(r,(s.get(r)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,s,i){let r=n;for(let a=e.length-1;a>=0;a--){let l=e[a],u=r;r=()=>l(t,u,s,i)}return r()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let w=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:w,data:{nodeType:w,label:d}});let g={};c._isCustomCode&&typeof c.execute=="function"&&(g.customCode=c.execute.toString());let E=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;E&&(g.description=E);let $=this.nodePrompts.get(d);if($)g.prompt=$;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(g.prompt=p,g.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(g.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(g.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof be?.toJSONSchema=="function")try{p=be.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Zt(c.outputSchema,{target:"openApi3"})}catch{}g.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else g.outputSchema={schema:c.outputSchema};let b=(this.resolvedToolsMap||{})[d];b?.toolIds&&(g.tools=b.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(g.skills=[...f]);let m=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;m&&m.length>0&&(g.plugins=m.map(p=>p&&typeof p=="object"?{...p}:p));let S=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;S&&S.length>0&&(g.stores=S.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(g).length>0&&(t[d]=g)}let n=[];for(let[d,c]of this.edges)if(typeof c=="string")n.push({source:d,target:c});else if(Array.isArray(c))for(let w of c)n.push({source:d,target:w});else if(c.conditional){let w=this.conditionalCodeMap.get(d)||c.routes.toString(),g=this._inferConditionalTargets(c.routes,c.labels),E=c.labels||{},$=this.nodes.get(d),b=$?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!$,f=d;if(!b){let m=`${d}__branch`;e.push({id:m,type:"decision",data:{nodeType:"decision",label:m}}),n.push({source:d,target:m}),f=m}for(let m of g){let S={source:f,target:m,data:{conditionalCode:w}};E[m]&&(S.label=E[m]),n.push(S)}}let s=d=>{if(!d)return null;if(typeof be?.toJSONSchema=="function")try{return be.toJSONSchema(d)}catch{}try{return Zt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of n)if(d.target==="END"){i+=1;let c=`END__${i}`;d.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:d,target:c})}let r=this._topoOrderNodes(e,n),a=this._runtimeSchema(),l=s(a||this.stateSchema),u=s(this.inputSchema),h=s(this.contextSchema);return{nodes:r,edges:n,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:h}}_topoOrderNodes(e,t){let n=new Map(e.map((d,c)=>[d.id,c])),s=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),r=new Map(e.map(d=>[d.id,[]]));for(let d of t)r.has(d.source)&&i.has(d.target)&&(r.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(n.keys()),u=[...l].filter(d=>i.get(d)===0),h=[];for(;h.length<e.length;){let d;if(u.length>0){if(u.sort((c,w)=>n.get(c)-n.get(w)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,w)=>n.get(c)-n.get(w))[0];a.add(d),l.delete(d),h.push(s.get(d));for(let c of r.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return h}_inferConditionalTargets(e,t){let n=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,r;for(;(r=i.exec(n))!==null;){let u=r[2]!==void 0?r[2]:r[3];u!==void 0&&u!==""&&s.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of s)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=u.exec(n))!==null;)l.add(h[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");n=e.definitions[s]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],s=e.properties||{},i=e.required||[];for(let[r,a]of Object.entries(s)){let l=t?`${t}.${r}`:r;n.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!i.includes(r)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${l}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${s}: ${i}`);else if(Array.isArray(i)){let r=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);n.push(l?`${s}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${s}: ${r} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(_){let y=new Error(`agent.normalizeInput() rejected the trigger input: ${_?.message||_}`);throw y.cause=_,y.code=_?.code||"NORMALIZE_INPUT_FAILED",y}let s=new AbortController;n.signal&&(n.signal.aborted?s.abort():n.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();qo({path:V(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let _=V(r,".zibby.config.js");Ze(_)&&(a=(await import(_)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let _=a?.agent;_?.provider?l=_.provider:_?.gemini?l="gemini":_?.claude?l="claude":_?.cursor?l="cursor":_?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},h=this._runtimeSchema();if(h){let _=h.safeParse(t);if(!_.success){let y=_.error.issues.map(j=>`${j.path.join(".")}: ${j.message}`);throw console.error("\u274C Initial state validation failed:"),y.forEach(j=>console.error(` - ${j}`)),new Error(`State validation failed: ${y.join(", ")}`)}x.step("State validated against schema")}let d=Xt(),c=t.sessionPath||d;c||Qt();let{sessionPath:w,sessionTimestamp:g,sessionId:E}=oo({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});x.step(`Session ${E}`);let $=await he.loadContext(t.specPath||"",r,u);Object.keys($).length>0&&x.step(`Context loaded: ${Object.keys($).join(", ")}`);let b=t.outputPath;!b&&t.specPath&&(e?.calculateOutputPath?b=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new se({...t,config:a,agentType:l,outputPath:b,sessionPath:w,sessionTimestamp:g,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),m=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:S}=await Promise.resolve().then(()=>(ue(),$t)),p=a.skills&&typeof a.skills=="object"?a.skills:{},I=Object.values(p).filter(_=>_&&typeof _=="object"&&typeof _.id=="string"),T=_=>{for(let y of I)if(y.id===_)return y;return S(_)},O=new Set;for(let[,_]of this.nodes)for(let y of _.config?.skills||[])O.add(y);for(let _ of O){let y=T(_);if(typeof y?.middleware=="function")try{let j=await y.middleware();typeof j=="function"&&m.set(_,j)}catch{}}let{backEdges:te,joinDegree:io}=this._analyzeFlow(),Te=new Map,oe=[],ke=(_,y,j)=>{if(!_||_==="END")return;let D=io.get(_)||0;if(j&&D>1&&!te.has(`${y}->${_}`)){let ne=(Te.get(_)||0)+1;if(ne<D){Te.set(_,ne);return}Te.set(_,0)}oe.includes(_)||oe.push(_)};this.entryPoint&&oe.push(this.entryPoint);let me=[],tt=a?.recursionLimit??100,ao=0;try{for(;oe.length>0;){let y=oe.pop();if(!y||y==="END")continue;if(++ao>tt)throw new Error(`Workflow exceeded recursion limit (${tt}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let j=V(w,Re);if(Ze(j)){try{Ko(j)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
41
+ ${h}`)}}function qt(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Xt(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Kt(String(e).trim())}catch{return String(e).trim()}}function Qt(){qt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function eo({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 to(o={}){let e=je.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,s=o.paths?.sessionPrefix;return s?`${s}_${n}`:n}function oo({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,r="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=Kt(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,r="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,r="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,r="config.sessionId"):(a=to(e),r="generated")}i=i??Date.now();let h=e.paths?.output||le;s=V(o,h,Ce,a)}let l=!Ze(s);return l&&Vt(s,{recursive:!0}),(l||r!=="initialState.sessionPath")&&Qo({traceFrom:n,sessionId:a,sessionPath:s,idSource:r,mkdirFresh:l}),eo({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}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.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,n={}){if(!(t instanceof F)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let r=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:r.workflow,retries:r.retries,onComplete:r.onComplete,execute:async u=>{let h=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof r.input=="function"?d=r.input(h):r.input&&typeof r.input=="object"?d=r.input:d={},Je(r.workflow,{input:d,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(h):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:h?._signal,parentAgent:u?.agent})}},l=new F(a);return l.name=e,this.nodes.set(e,l),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let s=!(t instanceof F)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof F?t:new F(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){let n=this.edges.get(e);return n===void 0?this.edges.set(e,t):typeof n=="string"?n!==t&&this.edges.set(e,[n,t]):Array.isArray(n)?n.includes(t)||n.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:n}={}){let s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:n}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,n=i=>{t.set(i,1);for(let r of this._simpleTargets(i)){if(!r||r==="END")continue;let a=t.get(r)||0;a===1?e.add(`${i}->${r}`):a===0&&n(r)}t.set(i,2)};this.entryPoint&&n(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let r of this._simpleTargets(i))!r||r==="END"||e.has(`${i}->${r}`)||s.set(r,(s.get(r)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,s,i){let r=n;for(let a=e.length-1;a>=0;a--){let l=e[a],u=r;r=()=>l(t,u,s,i)}return r()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let w=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:w,data:{nodeType:w,label:d}});let g={};c._isCustomCode&&typeof c.execute=="function"&&(g.customCode=c.execute.toString());let E=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;E&&(g.description=E);let $=this.nodePrompts.get(d);if($)g.prompt=$;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(g.prompt=p,g.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(g.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(g.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(g.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof be?.toJSONSchema=="function")try{p=be.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Zt(c.outputSchema,{target:"openApi3"})}catch{}g.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else g.outputSchema={schema:c.outputSchema};let b=(this.resolvedToolsMap||{})[d];b?.toolIds&&(g.tools=b.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(g.skills=[...f]);let m=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;m&&m.length>0&&(g.plugins=m.map(p=>p&&typeof p=="object"?{...p}:p));let S=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;S&&S.length>0&&(g.stores=S.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(g).length>0&&(t[d]=g)}let n=[];for(let[d,c]of this.edges)if(typeof c=="string")n.push({source:d,target:c});else if(Array.isArray(c))for(let w of c)n.push({source:d,target:w});else if(c.conditional){let w=this.conditionalCodeMap.get(d)||c.routes.toString(),g=this._inferConditionalTargets(c.routes,c.labels),E=c.labels||{},$=this.nodes.get(d),b=$?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!$,f=d;if(!b){let m=`${d}__branch`;e.push({id:m,type:"decision",data:{nodeType:"decision",label:m}}),n.push({source:d,target:m}),f=m}for(let m of g){let S={source:f,target:m,data:{conditionalCode:w}};E[m]&&(S.label=E[m]),n.push(S)}}let s=d=>{if(!d)return null;if(typeof be?.toJSONSchema=="function")try{return be.toJSONSchema(d)}catch{}try{return Zt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of n)if(d.target==="END"){i+=1;let c=`END__${i}`;d.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:d,target:c})}let r=this._topoOrderNodes(e,n),a=this._runtimeSchema(),l=s(a||this.stateSchema),u=s(this.inputSchema),h=s(this.contextSchema);return{nodes:r,edges:n,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:h}}_topoOrderNodes(e,t){let n=new Map(e.map((d,c)=>[d.id,c])),s=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),r=new Map(e.map(d=>[d.id,[]]));for(let d of t)r.has(d.source)&&i.has(d.target)&&(r.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(n.keys()),u=[...l].filter(d=>i.get(d)===0),h=[];for(;h.length<e.length;){let d;if(u.length>0){if(u.sort((c,w)=>n.get(c)-n.get(w)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,w)=>n.get(c)-n.get(w))[0];a.add(d),l.delete(d),h.push(s.get(d));for(let c of r.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return h}_inferConditionalTargets(e,t){let n=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,r;for(;(r=i.exec(n))!==null;){let u=r[2]!==void 0?r[2]:r[3];u!==void 0&&u!==""&&s.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of s)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=u.exec(n))!==null;)l.add(h[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");n=e.definitions[s]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],s=e.properties||{},i=e.required||[];for(let[r,a]of Object.entries(s)){let l=t?`${t}.${r}`:r;n.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!i.includes(r)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${l}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${s}: ${i}`);else if(Array.isArray(i)){let r=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);n.push(l?`${s}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${s}: ${r} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(_){let y=new Error(`agent.normalizeInput() rejected the trigger input: ${_?.message||_}`);throw y.cause=_,y.code=_?.code||"NORMALIZE_INPUT_FAILED",y}let s=new AbortController;n.signal&&(n.signal.aborted?s.abort():n.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();qo({path:V(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let _=V(r,".zibby.config.js");Ze(_)&&(a=(await import(_)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let _=a?.agent;_?.provider?l=_.provider:_?.gemini?l="gemini":_?.claude?l="claude":_?.cursor?l="cursor":_?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},h=this._runtimeSchema();if(h){let _=h.safeParse(t);if(!_.success){let y=_.error.issues.map(j=>`${j.path.join(".")}: ${j.message}`);throw console.error("\u274C Initial state validation failed:"),y.forEach(j=>console.error(` - ${j}`)),new Error(`State validation failed: ${y.join(", ")}`)}x.step("State validated against schema")}let d=Xt(),c=t.sessionPath||d;c||Qt();let{sessionPath:w,sessionTimestamp:g,sessionId:E}=oo({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});x.step(`Session ${E}`);let $=await he.loadContext(t.specPath||"",r,u);Object.keys($).length>0&&x.step(`Context loaded: ${Object.keys($).join(", ")}`);let b=t.outputPath;!b&&t.specPath&&(e?.calculateOutputPath?b=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new se({...t,config:a,agentType:l,outputPath:b,sessionPath:w,sessionTimestamp:g,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),m=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:S}=await Promise.resolve().then(()=>(ue(),$t)),p=a.skills&&typeof a.skills=="object"?a.skills:{},I=Object.values(p).filter(_=>_&&typeof _=="object"&&typeof _.id=="string"),T=_=>{for(let y of I)if(y.id===_)return y;return S(_)},O=new Set;for(let[,_]of this.nodes)for(let y of _.config?.skills||[])O.add(y);for(let _ of O){let y=T(_);if(typeof y?.middleware=="function")try{let j=await y.middleware();typeof j=="function"&&m.set(_,j)}catch{}}let{backEdges:te,joinDegree:io}=this._analyzeFlow(),Te=new Map,oe=[],ke=(_,y,j)=>{if(!_||_==="END")return;let D=io.get(_)||0;if(j&&D>1&&!te.has(`${y}->${_}`)){let ne=(Te.get(_)||0)+1;if(ne<D){Te.set(_,ne);return}Te.set(_,0)}oe.includes(_)||oe.push(_)};this.entryPoint&&oe.push(this.entryPoint);let me=[],tt=a?.recursionLimit??100,ao=0;try{for(;oe.length>0;){let y=oe.pop();if(!y||y==="END")continue;if(++ao>tt)throw new Error(`Workflow exceeded recursion limit (${tt}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let j=V(w,Re);if(Ze(j)){try{Ko(j)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
42
42
  \u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:me,stoppedExternally:!0};let D=this.nodes.get(y);if(!D)throw new Error(`Node '${y}' not found in graph`);let ne=JSON.stringify({sessionPath:w,sessionTimestamp:g,currentNode:y,createdAt:new Date().toISOString(),config:f.get("config")}),co=V(w,G);Yt(co,ne,"utf-8");let ot=f.get("config")?.paths?.output||le,lo=V(r,ot,G);Vt(V(r,ot),{recursive:!0});try{Yt(lo,ne,"utf-8")}catch{}let nt=t.onPipelineProgress;if(typeof nt=="function")try{nt({cwd:r,sessionPath:w,sessionId:E,outputBase:f.get("config")?.paths?.output||le,currentNode:y})}catch{}let uo=(this.resolvedToolsMap||{})[y]||null;f.set("_currentNodeTools",uo);let po=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",po[y]||{}),x.nodeStart(y);let rt=Date.now(),ye=this.nodePrompts.get(y);if(!this._invokeAgent){let A=await Promise.resolve().then(()=>(X(),pe));this._invokeAgent=A.invokeAgent}let fo=this._invokeAgent,Ae={},ho=D.config?.skills||[];for(let A of ho){let C=T(A);if(typeof C?.invokeAgentOptions=="function")try{let k=C.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:y});k&&typeof k=="object"&&(Ae={...Ae,...k})}catch(k){console.warn(`[graph] skill '${A}' invokeAgentOptions threw: ${k.message}`)}}let st=async(A,C,k={})=>{let M=fo(A,C,{...Ae,...k,signal:s.signal});return M.catch(()=>{}),s.signal.aborted?M:Promise.race([M,new Promise((K,L)=>{let R=()=>{setTimeout(()=>{let re=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);re.name="AbortError",L(re)},i)};s.signal.addEventListener("abort",R,{once:!0})})])},go=async(A={},C={})=>{let k=C.prompt||"";if(ye){let M=this._compiledPrompts.get(y);M||(M=Xo.compile(ye,{noEscape:!0}),this._compiledPrompts.set(y,M));try{k=M(A)}catch(K){throw console.error(`\u274C Template rendering failed for node '${y}':`,K.message),new Error(`Template rendering failed: ${K.message}`,{cause:K})}}else if(!k)throw new Error(`No prompt template configured for node '${y}' and no prompt provided in options`);return st(k,{state:f.getAll(),images:C.images||[]},{model:C.model||f.get("model"),workspace:f.get("workspace"),schema:C.schema,...C,signal:s.signal})},it=f.getAll(),mo=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let A of mo)Object.prototype.hasOwnProperty.call(it,A)&&console.warn(`[workflow] node "${y}": state key "${A}" is shadowed by the engine context prop; read it via context.state.get('${A}')`);let at={...it,state:f,invokeAgent:go,_coreInvokeAgent:st,agent:e,nodeId:y,promptTemplate:ye,getPromptTemplate:()=>ye};try{let A=(D.config?.skills||[]).map(R=>m.get(R)).filter(Boolean),C=[...this.middleware,...A],k;k=await Ct(e,s.signal,async()=>C.length>0?this._composeMiddleware(C,y,async()=>D.execute(at,f),f.getAll(),f):D.execute(at,f));let M=Date.now()-rt;if(me.push({node:y,success:k.success,duration:M,timestamp:new Date().toISOString()}),!k.success){if(s.signal.aborted)return x.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:me,stoppedExternally:!0};f.append("errors",{node:y,error:k.error});let R=D.config?.retries||0,re=`${y}_retries`,we=f.getAll()[re]||0;if(we<R){x.stepInfo(`Retrying (attempt ${we+1}/${R})`),f.update({[re]:we+1,[`${y}_raw`]:k.raw});continue}throw x.nodeFailed(y,k.error,{duration:M}),new Error(`Node '${y}' failed after ${we} attempts: ${k.error}`)}f.update({[y]:k.output});let K=this._summarizeNodeOutput(y,k.output);x.nodeComplete(y,{duration:M,details:K});let L=this.edges.get(y);if(L)if(L.conditional){let R=L.routes(f.getAll());x.route(y,R),ke(R,y,!1)}else if(Array.isArray(L))for(let R=L.length-1;R>=0;R--)ke(L[R],y,!0);else ke(L,y,!0)}catch(A){throw x.isInsideNode&&x.nodeFailed(y,A.message,{duration:Date.now()-rt}),f.set("failed",!0),f.set("failedAt",y),A}}x.graphComplete();let _={success:!0,state:f.getAll(),executionLog:me};return e&&typeof e.onComplete=="function"&&await e.onComplete(_),_}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(_){console.warn(`[workflow] agent.cleanup() failed: ${_.message}`)}}}};var Ve=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Ve]||(globalThis[Ve]=new Map);var ge=globalThis[Ve];function no(o,e){ge.set(o,e)}function Ke(o){return ge.get(o)}function Ie(o){return ge.has(o)}function en(){return Array.from(ge.keys())}function qe(o){let e=ge.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}no("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let n=t?._coreInvokeAgent;n||(n=(await Promise.resolve().then(()=>(X(),pe))).invokeAgent);let s=e.extraPromptInstructions||"Execute the task based on the current state.",i=tn(s,t),r=await n(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:r,nodeId:o},raw:typeof r=="string"?r:r.raw}}})});function tn(o,e){let t=/@([\w.]+)/g,n=new Set,s;for(;(s=t.exec(o))!==null;)n.add(s[1]);if(n.size===0)return o;let i=[],r=new Set;for(let a of n){let l=a.split(".")[0];if(r.has(l))continue;let u=a.split(".").reduce((c,w)=>c?.[w],e);if(u===void 0)continue;let h=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),d=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${d}
43
43
  ${h}`),a.includes(".")||r.add(l)}return i.length===0?o:`${o}
44
44
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/agent-workflow",
3
- "version": "0.6.5",
3
+ "version": "0.6.6",
4
4
  "description": "Graph-based AI agent workflow orchestration. Bring your own agent strategies.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",