@zibby/agent-workflow 0.6.9 → 0.6.10

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.
@@ -1,20 +1,20 @@
1
- var W=Object.defineProperty;var x=(e,n,t)=>()=>{if(t)throw t[0];try{return e&&(n=e(e=0)),n}catch(r){throw t=[r],r}};var H=(e,n)=>{for(var t in n)W(e,t,{get:n[t],enumerable:!0})};function O(e){return J.get(e)||null}var A,I,J,de,j=x(()=>{A=Symbol.for("@zibby/agent-workflow.skills"),I=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[A]||(globalThis[A]=new Map);globalThis[I]||(globalThis[I]=new Map);J=globalThis[A],de=globalThis[I]});var M,q,_,b,C=x(()=>{M=()=>{},q={debug:M,info:M,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},_={impl:q},b={debug:(...e)=>_.impl.debug?.(...e),info:(...e)=>_.impl.info?.(...e),warn:(...e)=>_.impl.warn?.(...e),error:(...e)=>_.impl.error?.(...e)}});var D=x(()=>{});var F={};H(F,{getAgentStrategy:()=>B,invokeAgent:()=>X,listStrategies:()=>Q,registerStrategy:()=>Z,resolveInvocationExtras:()=>z,resolveInvocationModel:()=>G});function Z(e){if(!e||typeof e.getName!="function"||typeof e.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let n=k.findIndex(t=>t.getName()===e.getName());n>=0?k[n]=e:k.push(e)}function Q(){return k.map(e=>e.getName())}function G({config:e={},options:n={},strategyName:t,envModel:r,nodeConfigModel:i}={}){let s=e.models||{},o=typeof i=="string"&&i.trim()&&i.trim()!=="auto"?i.trim():null,c=n.nodeName&&s[n.nodeName]||null,a=s.default||null,l=e.agent?.[t]?.model||null,h=(typeof r=="string"?r.trim():"")||null;return o||c||a||l||n.model||h||null}function z({options:e={},stateView:n={},context:t={}}={}){return{workspace:n.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],extraMcpServers:e.extraMcpServers||n.extraMcpServers||t.extraMcpServers||[],plugins:e.plugins||t.plugins||[]}}function B(e={}){let{state:n={},preferredAgent:t=null}=e,r=t||n.agentType||process.env.AGENT_TYPE;if(!r){let s=k.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}b.debug(`[workflow] agent selection: requested=${r}`);let i=k.find(s=>s.getName()===r);if(!i){let s=k.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${s}`)}if(!i.canHandle(e))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return b.debug(`[workflow] using agent: ${i.getName()}`),i}async function X(e,n={},t={}){let r=n.state&&typeof n.state.getAll=="function"?n.state.getAll():n.state||{},i={...n,state:r},s=B(i),o=r.config||t.config||{},c=r._currentNodeConfig||{},a=typeof c.agent=="string"?c.agent.trim():"",l=!a||a===s.name?c.model:null,h=G({config:o,options:t,strategyName:s.name,envModel:process.env.MODEL,nodeConfigModel:l}),T={...t,model:h,...z({options:t,stateView:r,context:n}),config:o},m=e,S=T.skills||[];if(S.length>0&&!t.skipPromptFragments){let u=t.connectedIntegrations;if(!u){let p=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof p=="string"&&p.trim()!==""){u={};for(let g of p.split(",").map(w=>w.trim()).filter(Boolean))u[g]=!0}}let y=p=>{let g=p&&p.requiresIntegration;return!g||!u?!0:(Array.isArray(g)?g:[g]).some(E=>u[E]===!0)},f=s.name==="assistant",v=p=>p?.inProcessOnly!==!0||f,$=S.map(p=>{let g=O(p);if(!y(g)||!v(g))return null;let w=g?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);$.length>0&&(m+=`
1
+ var H=Object.defineProperty;var x=(e,n,t)=>()=>{if(t)throw t[0];try{return e&&(n=e(e=0)),n}catch(r){throw t=[r],r}};var J=(e,n)=>{for(var t in n)H(e,t,{get:n[t],enumerable:!0})};function O(e){return q.get(e)||null}var A,I,q,pe,j=x(()=>{A=Symbol.for("@zibby/agent-workflow.skills"),I=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[A]||(globalThis[A]=new Map);globalThis[I]||(globalThis[I]=new Map);q=globalThis[A],pe=globalThis[I]});var L,Z,C,_,N,R=x(()=>{L=()=>{},Z={debug:L,info:L,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},C=Symbol.for("@zibby/agent-workflow.logger");globalThis[C]||(globalThis[C]={impl:Z});_=globalThis[C],N={debug:(...e)=>_.impl.debug?.(...e),info:(...e)=>_.impl.info?.(...e),warn:(...e)=>_.impl.warn?.(...e),error:(...e)=>_.impl.error?.(...e)}});var z=x(()=>{});var Y={};J(Y,{getAgentStrategy:()=>F,invokeAgent:()=>ee,listStrategies:()=>X,registerStrategy:()=>Q,resolveInvocationExtras:()=>B,resolveInvocationModel:()=>G});function Q(e){if(!e||typeof e.getName!="function"||typeof e.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let n=k.findIndex(t=>t.getName()===e.getName());n>=0?k[n]=e:k.push(e)}function X(){return k.map(e=>e.getName())}function G({config:e={},options:n={},strategyName:t,envModel:r,nodeConfigModel:i}={}){let s=e.models||{},o=typeof i=="string"&&i.trim()&&i.trim()!=="auto"?i.trim():null,c=n.nodeName&&s[n.nodeName]||null,a=s.default||null,l=e.agent?.[t]?.model||null,h=(typeof r=="string"?r.trim():"")||null;return o||c||a||l||n.model||h||null}function B({options:e={},stateView:n={},context:t={}}={}){return{workspace:n.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],extraMcpServers:e.extraMcpServers||n.extraMcpServers||t.extraMcpServers||[],plugins:e.plugins||t.plugins||[]}}function F(e={}){let{state:n={},preferredAgent:t=null}=e,r=t||n.agentType||process.env.AGENT_TYPE;if(!r){let s=k.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}N.debug(`[workflow] agent selection: requested=${r}`);let i=k.find(s=>s.getName()===r);if(!i){let s=k.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${s}`)}if(!i.canHandle(e))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return N.debug(`[workflow] using agent: ${i.getName()}`),i}async function ee(e,n={},t={}){let r=n.state&&typeof n.state.getAll=="function"?n.state.getAll():n.state||{},i={...n,state:r},s=F(i),o=r.config||t.config||{},c=r._currentNodeConfig||{},a=typeof c.agent=="string"?c.agent.trim():"",l=!a||a===s.name?c.model:null,h=G({config:o,options:t,strategyName:s.name,envModel:process.env.MODEL,nodeConfigModel:l}),T={...t,model:h,...B({options:t,stateView:r,context:n}),config:o},m=e,b=T.skills||[];if(b.length>0&&!t.skipPromptFragments){let f=t.connectedIntegrations;if(!f){let p=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof p=="string"&&p.trim()!==""){f={};for(let g of p.split(",").map(w=>w.trim()).filter(Boolean))f[g]=!0}}let y=p=>{let g=p&&p.requiresIntegration;return!g||!f?!0:(Array.isArray(g)?g:[g]).some(E=>f[E]===!0)},u=s.name==="assistant",v=p=>p?.inProcessOnly!==!0||u,$=b.map(p=>{let g=O(p);if(!y(g)||!v(g))return null;let w=g?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);$.length>0&&(m+=`
2
2
 
3
3
  ${$.join(`
4
4
 
5
- `)}`)}let d=r._currentNodeConfig?.stores;if(Array.isArray(d)&&d.length>0&&typeof d[0]=="object"){let u=d.length<=8,y=d.map(f=>{let v=f?.id??f?.storeId??"",$=(f?.name??"").toString().trim()||v,p=f?.type?` \xB7 ${f.type}`:"",g=(f?.description||"").toString().replace(/\s+/g," ").trim(),w=`- ${$} \xB7 ${g||"(no description)"}${p} (id: ${v})`;if(u&&f?.schema&&typeof f.schema=="object"){let E=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);E.length&&(w+=`
5
+ `)}`)}let d=r._currentNodeConfig?.stores;if(Array.isArray(d)&&d.length>0&&typeof d[0]=="object"){let f=d.length<=8,y=d.map(u=>{let v=u?.id??u?.storeId??"",$=(u?.name??"").toString().trim()||v,p=u?.type?` \xB7 ${u.type}`:"",g=(u?.description||"").toString().replace(/\s+/g," ").trim(),w=`- ${$} \xB7 ${g||"(no description)"}${p} (id: ${v})`;if(f&&u?.schema&&typeof u.schema=="object"){let E=u.schema.properties&&typeof u.schema.properties=="object"?Object.keys(u.schema.properties):Object.keys(u.schema);E.length&&(w+=`
6
6
  fields: ${E.join(", ")}`)}return w});m+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
9
9
  ${y.join(`
10
- `)}`}let N=r._currentNodeConfig?.extraPromptInstructions?.trim();return N&&(m+=`
10
+ `)}`}let S=r._currentNodeConfig?.extraPromptInstructions?.trim();return S&&(m+=`
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
- ${N}
17
- `),b.debug(`[workflow] prompt length: ${m.length} chars`),s.invoke(m,T)}var R,k,Y=x(()=>{D();C();j();R=Symbol.for("@zibby/agent-workflow.strategies");globalThis[R]||(globalThis[R]=[]);k=globalThis[R]});j();C();var L={};var P=Symbol.for("@zibby/agent-workflow.nodes");globalThis[P]||(globalThis[P]=new Map);var U=globalThis[P];function ee(e,n){U.set(e,n)}function V(e){let n=U.get(e);return n?n.factory&&typeof n.create=="function"?n.create.toString():typeof n.execute=="function"?n.execute.toString():typeof n=="function"?n.toString():null:null}ee("ai_agent",{name:"ai_agent",factory:!0,create:(e,n={})=>({name:e,_isCustomCode:!0,execute:async t=>{let r=t?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(Y(),F))).invokeAgent);let i=n.extraPromptInstructions||"Execute the task based on the current state.",s=ne(i,t),o=await r(s,{cwd:t.workspace||process.cwd(),model:t.model,tools:n.resolvedTools||null});return{success:!0,output:{raw:o,nodeId:e},raw:typeof o=="string"?o:o.raw}}})});function ne(e,n){let t=/@([\w.]+)/g,r=new Set,i;for(;(i=t.exec(e))!==null;)r.add(i[1]);if(r.size===0)return e;let s=[],o=new Set;for(let c of r){let a=c.split(".")[0];if(o.has(a))continue;let l=c.split(".").reduce((m,S)=>m?.[S],n);if(l===void 0)continue;let h=typeof l=="string"?l:l?.raw??JSON.stringify(l,null,2),T=c.replace(/_/g," ").replace(/\b\w/g,m=>m.toUpperCase());s.push(`## ${T}
16
+ ${S}
17
+ `),N.debug(`[workflow] prompt length: ${m.length} chars`),s.invoke(m,T)}var P,k,U=x(()=>{z();R();j();P=Symbol.for("@zibby/agent-workflow.strategies");globalThis[P]||(globalThis[P]=[]);k=globalThis[P]});j();R();var D={};var M=Symbol.for("@zibby/agent-workflow.nodes");globalThis[M]||(globalThis[M]=new Map);var V=globalThis[M];function ne(e,n){V.set(e,n)}function K(e){let n=V.get(e);return n?n.factory&&typeof n.create=="function"?n.create.toString():typeof n.execute=="function"?n.execute.toString():typeof n=="function"?n.toString():null:null}ne("ai_agent",{name:"ai_agent",factory:!0,create:(e,n={})=>({name:e,_isCustomCode:!0,execute:async t=>{let r=t?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(U(),Y))).invokeAgent);let i=n.extraPromptInstructions||"Execute the task based on the current state.",s=te(i,t),o=await r(s,{cwd:t.workspace||process.cwd(),model:t.model,tools:n.resolvedTools||null});return{success:!0,output:{raw:o,nodeId:e},raw:typeof o=="string"?o:o.raw}}})});function te(e,n){let t=/@([\w.]+)/g,r=new Set,i;for(;(i=t.exec(e))!==null;)r.add(i[1]);if(r.size===0)return e;let s=[],o=new Set;for(let c of r){let a=c.split(".")[0];if(o.has(a))continue;let l=c.split(".").reduce((m,b)=>m?.[b],n);if(l===void 0)continue;let h=typeof l=="string"?l:l?.raw??JSON.stringify(l,null,2),T=c.replace(/_/g," ").replace(/\b\w/g,m=>m.toUpperCase());s.push(`## ${T}
18
18
  ${h}`),c.includes(".")||o.add(a)}return s.length===0?e:`${e}
19
19
 
20
20
  ---
@@ -22,13 +22,13 @@ ${h}`),c.includes(".")||o.add(a)}return s.length===0?e:`${e}
22
22
 
23
23
  ${s.join(`
24
24
 
25
- `)}`}function Ee(e,n={}){let{nodes:t,edges:r,nodeConfigs:i={}}=e,s=new Set,o=[],c=new Map;for(let u of t){let y=u.data?.nodeType||u.type;c.set(u.id,y),y==="decision"?s.add(u.id):o.push({id:u.id,nodeType:y,label:u.data?.label||u.id})}let a=o.some(u=>{let y=i[u.id]||{};return!y.customCode&&!y.executeCode}),{toolsPerNode:l,toolIdsByVar:h}=ce(o,i),{simpleEdges:T,conditionalEdges:m}=le(r,s),S=ue(o,r,s),d=[],N=n.workflowType||"workflow";return d.push(te(n)),d.push(oe(N,{usesRegisteredNodes:a})),d.push(re(h)),d.push(se(N)),d.push(ie(o,i)),d.push(ae(o,S,T,m,l,N)),d.filter(Boolean).join(`
26
- `)}function xe(e){let n={};for(let[t,r]of Object.entries(e)){let{tools:i,...s}=r;Object.keys(s).length>0&&(n[t]=s)}return n}function te(e){let n=e.workflowType||"workflow";return["// Generated workflow",`// ${e.projectId?`Project: ${e.projectId} | `:""}Type: ${n} | Version: ${e.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
27
- `)}function oe(e,{usesRegisteredNodes:n=!0}={}){let t=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return n&&t.push("// import './register-nodes.js'; // register custom node types here"),t.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),t.join(`
28
- `)}function re(e){if(e.size===0)return"";let n=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];for(let[t,r]of e)n.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(r)}); // ${r.join(", ")}`);return n.push(""),n.join(`
29
- `)}function se(e){return["// \u2500\u2500 Node Configs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","const __filename = fileURLToPath(import.meta.url);","const __dirname = dirname(__filename);",`const configPath = join(__dirname, 'workflow-${e}.config.json');`,"const nodeConfigs = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')) : {};",""].join(`
30
- `)}function ie(e,n){let t=["// \u2500\u2500 Node Implementations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",""];for(let r of e){let i=K(r.id),s=n[r.id]?.customCode;if(s)t.push(`// @custom \u2014 modified from default "${r.nodeType}" template`),t.push(`const ${i}_execute = ${s};`);else{let o=V(r.nodeType);o?(t.push(`// Default "${r.nodeType}" implementation`),t.push(`const ${i}_execute = ${o};`)):(t.push(`// No template for "${r.nodeType}" \u2014 passthrough`),t.push(`const ${i}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}t.push("")}return t.join(`
31
- `)}function ae(e,n,t,r,i,s){let o=["// \u2500\u2500 Graph Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];o.push("export function buildGraph(options = {}) {"),o.push(" const graph = new WorkflowGraph(options);",""),o.push(" // Nodes");for(let a of e){let l=K(a.id);o.push(` graph.addNode('${a.id}', { name: '${a.id}', execute: ${l}_execute });`),o.push(` graph.setNodeType('${a.id}', '${a.nodeType}');`)}o.push("",` graph.setEntryPoint('${n}');`,""),(t.length>0||r.length>0)&&o.push(" // Edges");for(let a of t)o.push(` graph.addEdge('${a.source}', '${a.target}');`);for(let a of r){let l=a.code.split(`
25
+ `)}`}function xe(e,n={}){let{nodes:t,edges:r,nodeConfigs:i={}}=e,s=new Set,o=[],c=new Map;for(let f of t){let y=f.data?.nodeType||f.type;c.set(f.id,y),y==="decision"?s.add(f.id):o.push({id:f.id,nodeType:y,label:f.data?.label||f.id})}let a=o.some(f=>{let y=i[f.id]||{};return!y.customCode&&!y.executeCode}),{toolsPerNode:l,toolIdsByVar:h}=le(o,i),{simpleEdges:T,conditionalEdges:m}=fe(r,s),b=ue(o,r,s),d=[],S=n.workflowType||"workflow";return d.push(oe(n)),d.push(re(S,{usesRegisteredNodes:a})),d.push(se(h)),d.push(ie(S)),d.push(ae(o,i)),d.push(ce(o,b,T,m,l,S)),d.filter(Boolean).join(`
26
+ `)}function _e(e){let n={};for(let[t,r]of Object.entries(e)){let{tools:i,...s}=r;Object.keys(s).length>0&&(n[t]=s)}return n}function oe(e){let n=e.workflowType||"workflow";return["// Generated workflow",`// ${e.projectId?`Project: ${e.projectId} | `:""}Type: ${n} | Version: ${e.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
27
+ `)}function re(e,{usesRegisteredNodes:n=!0}={}){let t=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return n&&t.push("// import './register-nodes.js'; // register custom node types here"),t.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),t.join(`
28
+ `)}function se(e){if(e.size===0)return"";let n=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];for(let[t,r]of e)n.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(r)}); // ${r.join(", ")}`);return n.push(""),n.join(`
29
+ `)}function ie(e){return["// \u2500\u2500 Node Configs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","const __filename = fileURLToPath(import.meta.url);","const __dirname = dirname(__filename);",`const configPath = join(__dirname, 'workflow-${e}.config.json');`,"const nodeConfigs = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')) : {};",""].join(`
30
+ `)}function ae(e,n){let t=["// \u2500\u2500 Node Implementations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",""];for(let r of e){let i=W(r.id),s=n[r.id]?.customCode;if(s)t.push(`// @custom \u2014 modified from default "${r.nodeType}" template`),t.push(`const ${i}_execute = ${s};`);else{let o=K(r.nodeType);o?(t.push(`// Default "${r.nodeType}" implementation`),t.push(`const ${i}_execute = ${o};`)):(t.push(`// No template for "${r.nodeType}" \u2014 passthrough`),t.push(`const ${i}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}t.push("")}return t.join(`
31
+ `)}function ce(e,n,t,r,i,s){let o=["// \u2500\u2500 Graph Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];o.push("export function buildGraph(options = {}) {"),o.push(" const graph = new WorkflowGraph(options);",""),o.push(" // Nodes");for(let a of e){let l=W(a.id);o.push(` graph.addNode('${a.id}', { name: '${a.id}', execute: ${l}_execute });`),o.push(` graph.setNodeType('${a.id}', '${a.nodeType}');`)}o.push("",` graph.setEntryPoint('${n}');`,""),(t.length>0||r.length>0)&&o.push(" // Edges");for(let a of t)o.push(` graph.addEdge('${a.source}', '${a.target}');`);for(let a of r){let l=a.code.split(`
32
32
  `).map((h,T)=>T===0?h:` ${h}`).join(`
33
33
  `);o.push(` graph.addConditionalEdges('${a.source}', ${l});`)}let c=[];for(let a of e){let l=i.get(a.id);l&&c.push(` '${a.id}': ${l},`)}return c.length>0&&o.push(""," graph.resolvedToolsMap = {",...c," };"),o.push(""," return graph;","}",""),o.push("export { nodeConfigs };",""),o.join(`
34
- `)}function ce(e,n){let t=new Map,r=new Map;for(let i of e){let s=n[i.id]?.tools,o;if(Array.isArray(s)&&s.length>0)o=[...s].sort();else{let c=L[i.nodeType];c?.length>0&&(o=[...c].sort())}if(o){let c=`${o.map(a=>a.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;t.set(i.id,c),r.has(c)||r.set(c,o)}}return{toolsPerNode:t,toolIdsByVar:r}}function le(e,n){let t=[],r=[],i=new Map,s=new Set;for(let o of e)i.has(o.source)||i.set(o.source,[]),i.get(o.source).push(o);for(let o of e)if(!n.has(o.source))if(n.has(o.target)){if(s.has(o.target))continue;s.add(o.target);let a=(i.get(o.target)||[]).find(l=>l.data?.conditionalCode||l.conditionalCode);a&&r.push({source:o.source,code:a.data?.conditionalCode||a.conditionalCode})}else t.push({source:o.source,target:o.target});return{simpleEdges:t,conditionalEdges:r}}function ue(e,n,t){let r=new Set;for(let s of n)t.has(s.target)||r.add(s.target);let i=e.find(s=>!r.has(s.id));return i?i.id:e[0]?.id}function K(e){return e.replace(/[^a-zA-Z0-9]/g,"_")}export{xe as generateNodeConfigsJson,Ee as generateWorkflowCode};
34
+ `)}function le(e,n){let t=new Map,r=new Map;for(let i of e){let s=n[i.id]?.tools,o;if(Array.isArray(s)&&s.length>0)o=[...s].sort();else{let c=D[i.nodeType];c?.length>0&&(o=[...c].sort())}if(o){let c=`${o.map(a=>a.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;t.set(i.id,c),r.has(c)||r.set(c,o)}}return{toolsPerNode:t,toolIdsByVar:r}}function fe(e,n){let t=[],r=[],i=new Map,s=new Set;for(let o of e)i.has(o.source)||i.set(o.source,[]),i.get(o.source).push(o);for(let o of e)if(!n.has(o.source))if(n.has(o.target)){if(s.has(o.target))continue;s.add(o.target);let a=(i.get(o.target)||[]).find(l=>l.data?.conditionalCode||l.conditionalCode);a&&r.push({source:o.source,code:a.data?.conditionalCode||a.conditionalCode})}else t.push({source:o.source,target:o.target});return{simpleEdges:t,conditionalEdges:r}}function ue(e,n,t){let r=new Set;for(let s of n)t.has(s.target)||r.add(s.target);let i=e.find(s=>!r.has(s.id));return i?i.id:e[0]?.id}function W(e){return e.replace(/[^a-zA-Z0-9]/g,"_")}export{_e as generateNodeConfigsJson,xe as generateWorkflowCode};
@@ -1,9 +1,9 @@
1
- var Zt=Object.defineProperty;var Ae=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var pe=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var Ke=(n,e)=>{for(var t in e)Zt(n,t,{get:e[t],enumerable:!0})};var Ve,Kt,ge,b,G=pe(()=>{Ve=()=>{},Kt={debug:Ve,info:Ve,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},ge={impl:Kt},b={debug:(...n)=>ge.impl.debug?.(...n),info:(...n)=>ge.impl.info?.(...n),warn:(...n)=>ge.impl.warn?.(...n),error:(...n)=>ge.impl.error?.(...n)}});var ct=pe(()=>{});var lt={};Ke(lt,{clearSkills:()=>rn,getAllSkills:()=>nn,getSkill:()=>se,getSkillSource:()=>tn,hasSkill:()=>en,listSkillIds:()=>on,registerSkill:()=>Qt});function Qt(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:o=!1}=e,r=n.id;if(H.has(r)&&!o){let i=re.get(r);if(!(i===t)){let a=i||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${r}" 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).`)}}H.set(r,Object.freeze({...n})),t===void 0?re.delete(r):re.set(r,t)}function se(n){return H.get(n)||null}function en(n){return H.has(n)}function tn(n){return re.get(n)||null}function nn(){return new Map(H)}function on(){return Array.from(H.keys())}function rn(){H.clear(),re.clear()}var Pe,Ne,H,re,ye=pe(()=>{Pe=Symbol.for("@zibby/agent-workflow.skills"),Ne=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Pe]||(globalThis[Pe]=new Map);globalThis[Ne]||(globalThis[Ne]=new Map);H=globalThis[Pe],re=globalThis[Ne]});var ie={};Ke(ie,{getAgentStrategy:()=>pt,invokeAgent:()=>cn,listStrategies:()=>an,registerStrategy:()=>sn,resolveInvocationExtras:()=>dt,resolveInvocationModel:()=>ut});function sn(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=J.findIndex(t=>t.getName()===n.getName());e>=0?J[e]=n:J.push(n)}function an(){return J.map(n=>n.getName())}function ut({config:n={},options:e={},strategyName:t,envModel:o,nodeConfigModel:r}={}){let i=n.models||{},s=typeof r=="string"&&r.trim()&&r.trim()!=="auto"?r.trim():null,a=e.nodeName&&i[e.nodeName]||null,u=i.default||null,d=n.agent?.[t]?.model||null,h=(typeof o=="string"?o.trim():"")||null;return s||a||u||d||e.model||h||null}function dt({options:n={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],extraMcpServers:n.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:n.plugins||t.plugins||[]}}function pt(n={}){let{state:e={},preferredAgent:t=null}=n,o=t||e.agentType||process.env.AGENT_TYPE;if(!o){let i=J.map(s=>s.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=${o}`);let r=J.find(i=>i.getName()===o);if(!r){let i=J.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${i}`)}if(!r.canHandle(n))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return b.debug(`[workflow] using agent: ${r.getName()}`),r}async function cn(n,e={},t={}){let o=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},r={...e,state:o},i=pt(r),s=o.config||t.config||{},a=o._currentNodeConfig||{},u=typeof a.agent=="string"?a.agent.trim():"",d=!u||u===i.name?a.model:null,h=ut({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:d}),l={...t,model:h,...dt({options:t,stateView:o,context:e}),config:s},c=n,w=l.skills||[];if(w.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(T=>T.trim()).filter(Boolean))A[_]=!0}}let E=p=>{let _=p&&p.requiresIntegration;return!_||!A?!0:(Array.isArray(_)?_:[_]).some(v=>A[v]===!0)},f=i.name==="assistant",g=p=>p?.inProcessOnly!==!0||f,$=w.map(p=>{let _=se(p);if(!E(_)||!g(_))return null;let T=_?.promptFragment;return typeof T=="function"?T():T}).filter(Boolean);$.length>0&&(c+=`
1
+ var Zt=Object.defineProperty;var $e=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var ue=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var Ke=(n,e)=>{for(var t in e)Zt(n,t,{get:e[t],enumerable:!0})};var Ve,Kt,Te,fe,b,G=ue(()=>{Ve=()=>{},Kt={debug:Ve,info:Ve,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},Te=Symbol.for("@zibby/agent-workflow.logger");globalThis[Te]||(globalThis[Te]={impl:Kt});fe=globalThis[Te],b={debug:(...n)=>fe.impl.debug?.(...n),info:(...n)=>fe.impl.info?.(...n),warn:(...n)=>fe.impl.warn?.(...n),error:(...n)=>fe.impl.error?.(...n)}});var ct=ue(()=>{});var lt={};Ke(lt,{clearSkills:()=>rn,getAllSkills:()=>nn,getSkill:()=>re,getSkillSource:()=>tn,hasSkill:()=>en,listSkillIds:()=>on,registerSkill:()=>Qt});function Qt(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:o=!1}=e,r=n.id;if(H.has(r)&&!o){let i=oe.get(r);if(!(i===t)){let a=i||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${r}" 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).`)}}H.set(r,Object.freeze({...n})),t===void 0?oe.delete(r):oe.set(r,t)}function re(n){return H.get(n)||null}function en(n){return H.has(n)}function tn(n){return oe.get(n)||null}function nn(){return new Map(H)}function on(){return Array.from(H.keys())}function rn(){H.clear(),oe.clear()}var Oe,Pe,H,oe,ge=ue(()=>{Oe=Symbol.for("@zibby/agent-workflow.skills"),Pe=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Oe]||(globalThis[Oe]=new Map);globalThis[Pe]||(globalThis[Pe]=new Map);H=globalThis[Oe],oe=globalThis[Pe]});var se={};Ke(se,{getAgentStrategy:()=>pt,invokeAgent:()=>cn,listStrategies:()=>an,registerStrategy:()=>sn,resolveInvocationExtras:()=>dt,resolveInvocationModel:()=>ut});function sn(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=J.findIndex(t=>t.getName()===n.getName());e>=0?J[e]=n:J.push(n)}function an(){return J.map(n=>n.getName())}function ut({config:n={},options:e={},strategyName:t,envModel:o,nodeConfigModel:r}={}){let i=n.models||{},s=typeof r=="string"&&r.trim()&&r.trim()!=="auto"?r.trim():null,a=e.nodeName&&i[e.nodeName]||null,u=i.default||null,d=n.agent?.[t]?.model||null,g=(typeof o=="string"?o.trim():"")||null;return s||a||u||d||e.model||g||null}function dt({options:n={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],extraMcpServers:n.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:n.plugins||t.plugins||[]}}function pt(n={}){let{state:e={},preferredAgent:t=null}=n,o=t||e.agentType||process.env.AGENT_TYPE;if(!o){let i=J.map(s=>s.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=${o}`);let r=J.find(i=>i.getName()===o);if(!r){let i=J.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${i}`)}if(!r.canHandle(n))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return b.debug(`[workflow] using agent: ${r.getName()}`),r}async function cn(n,e={},t={}){let o=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},r={...e,state:o},i=pt(r),s=o.config||t.config||{},a=o._currentNodeConfig||{},u=typeof a.agent=="string"?a.agent.trim():"",d=!u||u===i.name?a.model:null,g=ut({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:d}),l={...t,model:g,...dt({options:t,stateView:o,context:e}),config:s},c=n,h=l.skills||[];if(h.length>0&&!t.skipPromptFragments){let T=t.connectedIntegrations;if(!T){let p=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof p=="string"&&p.trim()!==""){T={};for(let _ of p.split(",").map(A=>A.trim()).filter(Boolean))T[_]=!0}}let E=p=>{let _=p&&p.requiresIntegration;return!_||!T?!0:(Array.isArray(_)?_:[_]).some(v=>T[v]===!0)},f=i.name==="assistant",m=p=>p?.inProcessOnly!==!0||f,$=h.map(p=>{let _=re(p);if(!E(_)||!m(_))return null;let A=_?.promptFragment;return typeof A=="function"?A():A}).filter(Boolean);$.length>0&&(c+=`
2
2
 
3
3
  ${$.join(`
4
4
 
5
- `)}`)}let m=o._currentNodeConfig?.stores;if(Array.isArray(m)&&m.length>0&&typeof m[0]=="object"){let A=m.length<=8,E=m.map(f=>{let g=f?.id??f?.storeId??"",$=(f?.name??"").toString().trim()||g,p=f?.type?` \xB7 ${f.type}`:"",_=(f?.description||"").toString().replace(/\s+/g," ").trim(),T=`- ${$} \xB7 ${_||"(no description)"}${p} (id: ${g})`;if(A&&f?.schema&&typeof f.schema=="object"){let v=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);v.length&&(T+=`
6
- fields: ${v.join(", ")}`)}return T});c+=`
5
+ `)}`)}let y=o._currentNodeConfig?.stores;if(Array.isArray(y)&&y.length>0&&typeof y[0]=="object"){let T=y.length<=8,E=y.map(f=>{let m=f?.id??f?.storeId??"",$=(f?.name??"").toString().trim()||m,p=f?.type?` \xB7 ${f.type}`:"",_=(f?.description||"").toString().replace(/\s+/g," ").trim(),A=`- ${$} \xB7 ${_||"(no description)"}${p} (id: ${m})`;if(T&&f?.schema&&typeof f.schema=="object"){let v=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);v.length&&(A+=`
6
+ fields: ${v.join(", ")}`)}return A});c+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
9
9
  ${E.join(`
@@ -14,37 +14,37 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
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
  ${I}
17
- `),b.debug(`[workflow] prompt length: ${c.length} chars`),i.invoke(c,l)}var Ce,J,ae=pe(()=>{ct();G();ye();Ce=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ce]||(globalThis[Ce]=[]);J=globalThis[Ce]});var qt=new Set(["__proto__","constructor","prototype"]);function Te(n){if(qt.has(n))throw new Error(`Invalid state key: "${n}"`)}var fe=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){Te(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)Te(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){Te(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 z from"handlebars";var he=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 o=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(r=>r[0]);for(let r of o)try{return this.validate(JSON.parse(r))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,r]of Object.entries(this.schema)){if(r.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&r.type){let i=typeof e[o];i!==r.type&&t.push(`Field '${o}' expected ${r.type}, got ${i}`)}if(r.validate&&o in e){let i=r.validate(e[o]);i&&t.push(`Field '${o}': ${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 Ne,J,ie=ue(()=>{ct();G();ge();Ne=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ne]||(globalThis[Ne]=[]);J=globalThis[Ne]});var qt=new Set(["__proto__","constructor","prototype"]);function ve(n){if(qt.has(n))throw new Error(`Invalid state key: "${n}"`)}var de=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){ve(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)ve(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){ve(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import z from"handlebars";var pe=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 o=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(r=>r[0]);for(let r of o)try{return this.validate(JSON.parse(r))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,r]of Object.entries(this.schema)){if(r.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&r.type){let i=typeof e[o];i!==r.type&&t.push(`Field '${o}' expected ${r.type}, got ${i}`)}if(r.validate&&o in e){let i=r.validate(e[o]);i&&t.push(`Field '${o}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
18
18
  ${t.join(`
19
- `)}`);return e}};G();import{writeFileSync as Re,readFileSync as ft,existsSync as ht,mkdirSync as ln}from"node:fs";import{join as Be,dirname as un}from"node:path";import O from"chalk";var Vt="__WORKFLOW_GRAPH_LOG__",oe=O.gray("\u2502"),Xt=O.gray("\u250C"),Xe=O.gray("\u2514"),ke=O.green("\u25C6"),Qe=O.hex("#c084fc")("\u25C6"),et=O.hex("#2dd4bf")("\u25C6"),xe=O.red("\u25C6"),tt=`${oe} `,nt=2;function ot(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function rt(n,e){return(t,o,r)=>{if(typeof t!="string")return n(t,o,r);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let u=t[a];e.lineStart&&(s+=tt,e.col=nt,e.lineStart=!1),u===`
19
+ `)}`);return e}};G();import{writeFileSync as Ce,readFileSync as ft,existsSync as ht,mkdirSync as ln}from"node:fs";import{join as Re,dirname as un}from"node:path";import O from"chalk";var Vt="__WORKFLOW_GRAPH_LOG__",ne=O.gray("\u2502"),Xt=O.gray("\u250C"),Xe=O.gray("\u2514"),Ae=O.green("\u25C6"),Qe=O.hex("#c084fc")("\u25C6"),et=O.hex("#2dd4bf")("\u25C6"),ke=O.red("\u25C6"),tt=`${ne} `,nt=2;function ot(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function rt(n,e){return(t,o,r)=>{if(typeof t!="string")return n(t,o,r);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let u=t[a];e.lineStart&&(s+=tt,e.col=nt,e.lineStart=!1),u===`
20
20
  `?(s+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,s+=u):e.inEsc?(s+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,s+=u,e.col>=i&&(s+=`
21
- ${tt}`,e.col=nt))}return n(s,o,r)}}var Oe=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=rt(this._origStdoutWrite,e),process.stderr.write=rt(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
21
+ ${tt}`,e.col=nt))}return n(s,o,r)}}var xe=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=rt(this._origStdoutWrite,e),process.stderr.write=rt(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
22
22
  `),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
23
23
  `),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
24
24
  `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Vt}${JSON.stringify(e)}
25
25
  `;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
26
26
  `),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
27
27
  `)):process.stdout.write.bind(process.stdout)(`${e} ${t}
28
- `)}step(e){this._origStdoutWrite?this._writeDot(ke,e):process.stdout.write.bind(process.stdout)(`${oe} ${ke} ${e}
29
- `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Qe,e):process.stdout.write.bind(process.stdout)(`${oe} ${Qe} ${e}
30
- `)}stepMemory(e){let t=O.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(et,t):process.stdout.write.bind(process.stdout)(`${oe} ${et} ${t}
31
- `)}stepFail(e){this._origStdoutWrite?this._writeDot(xe,O.red(e)):process.stdout.write.bind(process.stdout)(`${oe} ${xe} ${O.red(e)}
32
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Xt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:r}=t;if(r)for(let s of r)this._rawWrite(`${ke} ${s}`);let i=o?O.dim(` ${ot(o)}`):"";this._rawWrite(`${Xe} ${O.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:r}=o,i=r?O.dim(` ${ot(r)}`):"";this._rawWrite(`${xe} ${O.red(t)}`),this._rawWrite(`${Xe} ${O.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(O.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},P=new Oe;var me=".zibby/output",st="sessions",V=".session-info.json",it=".zibby-stop";var eo=Object.freeze(["codebase-memory","code-scan","artifact"]),at=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];z.helpers.inc||z.registerHelper("inc",n=>Number(n)+1);z.helpers.json||z.registerHelper("json",n=>JSON.stringify(n,null,2));z.helpers.eq||z.registerHelper("eq",(n,e)=>n===e);var U=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 he(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 o=()=>t&&typeof t.getAll=="function"?t.getAll():e,r=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(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=z.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(o())):i=this.prompt;let s=r("_skillHints");s&&(i=`${s}
28
+ `)}step(e){this._origStdoutWrite?this._writeDot(Ae,e):process.stdout.write.bind(process.stdout)(`${ne} ${Ae} ${e}
29
+ `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Qe,e):process.stdout.write.bind(process.stdout)(`${ne} ${Qe} ${e}
30
+ `)}stepMemory(e){let t=O.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(et,t):process.stdout.write.bind(process.stdout)(`${ne} ${et} ${t}
31
+ `)}stepFail(e){this._origStdoutWrite?this._writeDot(ke,O.red(e)):process.stdout.write.bind(process.stdout)(`${ne} ${ke} ${O.red(e)}
32
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Xt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:r}=t;if(r)for(let s of r)this._rawWrite(`${Ae} ${s}`);let i=o?O.dim(` ${ot(o)}`):"";this._rawWrite(`${Xe} ${O.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:r}=o,i=r?O.dim(` ${ot(r)}`):"";this._rawWrite(`${ke} ${O.red(t)}`),this._rawWrite(`${Xe} ${O.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(O.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},P=new xe;var he=".zibby/output",st="sessions",V=".session-info.json",it=".zibby-stop";var eo=Object.freeze(["codebase-memory","code-scan","artifact"]),at=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];z.helpers.inc||z.registerHelper("inc",n=>Number(n)+1);z.helpers.json||z.registerHelper("json",n=>JSON.stringify(n,null,2));z.helpers.eq||z.registerHelper("eq",(n,e)=>n===e);var F=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 pe(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 o=()=>t&&typeof t.getAll=="function"?t.getAll():e,r=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)`);let l=null;for(let c=0;c<=this.retries;c++){try{let h=await this.customExecute(e);if(typeof h=="object"&&h!==null&&h.success===!1)l={success:!1,error:h.error||"Node execution failed",raw:h.raw||null};else return this.isZodSchema?(b.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(h),raw:null}):{success:!0,output:h,raw:null}}catch(h){b.error(`[workflow] node '${this.name}' failed: ${h.message}`),h.name==="ZodError"&&b.error(`Schema errors: ${JSON.stringify(h.issues||h.errors,null,2)}`),l={success:!1,error:h.message,raw:null}}c<this.retries&&b.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return l}let i;typeof this.prompt=="function"?i=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=z.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(o())):i=this.prompt;let s=r("_skillHints");s&&(i=`${s}
33
33
 
34
- ${i}`);let a=o(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Be(d,V);if(ht(l)){let w=JSON.parse(ft(l,"utf-8"));w.currentNode=this.name,Re(l,JSON.stringify(w,null,2),"utf-8")}let c=Be(d,"..",V);if(ht(c))try{let w=JSON.parse(ft(c,"utf-8"));w.currentNode=this.name,Re(c,JSON.stringify(w,null,2),"utf-8")}catch{}}}catch(l){b.debug(`[workflow] could not update session info: ${l.message}`)}let h=null;for(let l=0;l<=this.retries;l++)try{b.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=o().config||{},w=c.agents||{},m=this.config.agent??w[this.name]??null,I={state:o()};m&&(I.preferredAgent=m);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=e?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(ae(),ie))).invokeAgent);let f=await E(i,I,A),g,$;if(typeof f=="string"?(g=f,$=null):f.structured?(g=f.raw||JSON.stringify(f.structured,null,2),$=f.structured):(g=f.raw||JSON.stringify(f,null,2),$=f.extracted||null),d)try{let p=Be(d,this.name,"raw_stream_output.txt");ln(un(p),{recursive:!0}),Re(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&&$){b.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify($,null,2)}`);let p=$;if(typeof this.onComplete=="function")try{p=await this.onComplete(o(),$)}catch(_){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(o(),{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)}`),P.step("Output parsed"),{success:!0,output:p,raw:g}}return{success:!0,output:g,raw:g}}catch(c){h=c,l<this.retries&&b.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};G();G();import{mkdirSync as fn,existsSync as Z,statSync as $t,readdirSync as vt,rmSync as hn}from"node:fs";import{spawn as bt}from"node:child_process";import{join as F}from"node:path";import{pathToFileURL as gn}from"node:url";import{AsyncLocalStorage as mn}from"node:async_hooks";import{AsyncLocalStorage as dn}from"node:async_hooks";var ce=new dn;function X(){let n=ce.getStore();return n||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 gt(n,e){let t=ce.getStore()||X(),o=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return ce.run(o,e)}function mt(n,e,t){let o=ce.getStore()||X(),r=Object.freeze({...o,agent:n??o.agent??null,signal:e??o.signal??null});return ce.run(r,t)}var Me=new Map,je=new Map,yt=new Map;function wt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Me.set(n,e),je.set(n,"ready"),yt.set(n,{...t,cachedAt:Date.now()})}function St(n,e){je.set(n,"failed"),yt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Me.delete(n)}function _t(n){return je.get(n)==="ready"?Me.get(n):null}var we=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function yn(){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"}},It=new mn,Et=Promise.resolve();async function wn(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(t.length===0)return e();let o=It.getStore()===!0,r=null;if(!o){let s=Et;Et=new Promise(a=>{r=a}),await s}let i=new Map;try{for(let[s,a]of t)i.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=a;return b.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await It.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;r&&r()}}function Sn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,o=process.env.PROJECT_ID,r=process.env.PROJECT_API_TOKEN;if(!t||!o||!r)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:r}}async function _n({apiBase:n,authToken:e,body:t}){let o;try{o=await fetch(`${n}/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 r=null;try{r=await o.json()}catch{}if(!o.ok){if(o.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(o.status===429){let i=r?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=i,s}if(o.status===400&&r?.validationErrors){let i=new Error(`Sub-graph rejected input: ${r?.error||r?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=r.validationErrors,i.missing=r.missing,i}throw new N("begin-status",`begin returned ${o.status}`)}return r?.data||r}async function Y({apiBase:n,authToken:e,payload:t}){try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});o.ok||b.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){b.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function bn(n,e){let t=F(e,".ready"),o=F(e,"graph.mjs");if(Z(t)&&Z(o))return;fn(e,{recursive:!0});let r=F(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),u=s(r,"wx");a(u),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(Z(t)&&Z(o))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 h=bt("curl",["-fsSL",n],{stdio:["ignore","pipe","inherit"]}),l=bt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(l.stdin);let c,w,m=()=>{if(c!==void 0&&w!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(w!==0)return d(new Error(`tar exited ${w}`));u()}};h.on("close",I=>{c=I,m()}),l.on("close",I=>{w=I,m()}),h.on("error",d),l.on("error",d)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(r)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(r)}catch{}throw new N("bundle-extract-failed",s.message)}}async function In(n){let e=F(n,"graph.mjs");if(!Z(e))throw new N("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(gn(e).href)}catch(r){throw new N("import-failed",`${r?.code||r?.name||"unknown"}: ${r.message}`)}let o=t.default||Object.values(t).find(r=>typeof r=="function"&&r.prototype?.buildGraph);if(!o)throw new N("entry-class-missing","no buildGraph() class export found");return o}async function At(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=X(),o;try{o=Sn()}catch(p){throw p}b.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let r=await _n({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:h,bundleReady:l,nodeConfigs:c}=r,w=yn();if(s&&s!==w)throw await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new N("runtime-mismatch",`${w} vs ${s}`);if(!l||!a)throw await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new N("no-bundle","workflow bundle not built yet");let m=_t(n);if(!m){let p=F(we,`${h}@${d||"0"}`);try{await bn(a,p);try{$n()}catch{}}catch(_){throw _.fallback&&await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason}}}),_}try{m=await In(p),wt(n,m,{workflowUuid:h,version:d,runtimeTag:s,cacheDir:p})}catch(_){throw St(n,_),await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason||"IMPORT_FAILED"}}}),_.fallback?_:new N("import-failed",_.message)}}let I=Date.now(),A=r.env&&typeof r.env=="object"&&!Array.isArray(r.env)?r.env:null,E=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...E?{nodeConfigs:c}:{}},g,$;try{g=await wn(A,async()=>{let _=await(typeof m=="function"&&m.prototype?.buildGraph?new m:m).buildGraph();return gt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>_.run(e.parentAgent,f,{signal:e.signal}))}),$=g&&typeof g=="object"&&"state"in g?g.state:g}catch(p){throw await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-I}}),p}if(g&&typeof g=="object"&&g.stoppedExternally){await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"canceled",finalState:$,durationMs:Date.now()-I}});let p=new Error(`Sub-graph '${n}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"completed",finalState:$,durationMs:Date.now()-I}}),{finalState:$,executionId:i}}function En(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),r;try{r=$t(o)}catch{continue}if(r.isDirectory()){let i;try{i=vt(o)}catch{continue}for(let s of i)t.push(F(o,s))}else e+=r.size}return e}function $n({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Z(we))return{evicted:0,freedBytes:0};let e=vt(we),t=[],o=0;for(let a of e){let u=F(we,a),d;try{d=$t(u)}catch{continue}let h=d.isDirectory()?En(u):d.size;o+=h,t.push({name:a,full:u,size:h,mtimeMs:d.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let r=Math.floor(n*.7),i=0,s=0;for(let a of t){if(o-i<=r)break;if(!Z(F(a.full,".lock")))try{hn(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(u){b.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return s>0&&b.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:o-i}}catch(e){return b.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var vn=2e3,An=600*1e3,Tn=new Set(["completed","failed","canceled","timeout"]);function kn(){let n=process.env.PROGRESS_API_URL;if(!n)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 n.replace(/\/executions\/?$/,"")}function xn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function On(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function Pn(){return process.env.EXECUTION_ID||null}function Tt(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,o)=>t==null?t:t[o],n):n}async function kt(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=X();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=o)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${o}. 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 '${n}'`);let{finalState:p}=await At(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),_=Tt(p,e.output);return b.info(`[sub-graph] '${n}' completed in-process`),_}catch(p){if(p instanceof N||p?.fallback)b.info(`[sub-graph] in-process fallback for '${n}': ${p.reason||"unknown"} \u2014 using HTTP`);else throw p}let r=kn(),i=xn(),s=On(),a=Pn(),u=`${r}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(n)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};b.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let h=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(d)});if(!h.ok){let p=null,_="";try{p=await h.json(),_=p?.error||p?.message||JSON.stringify(p)}catch{_=await h.text().catch(()=>"")}if(h.status===429){let v=p?.quotaInfo||{},D=new Error(`Sub-graph '${n}' blocked by execution quota (${v.used??"?"}/${v.limit??"?"} on plan ${v.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw D.code="SUBGRAPH_QUOTA_EXCEEDED",D.status=429,D.subgraph=n,D.quotaInfo=v,D}if(h.status===400){let v=new Error(`Sub-graph '${n}' rejected input: ${_}`);throw v.code="SUBGRAPH_INVALID_INPUT",v.status=400,v.subgraph=n,v.validationErrors=p?.validationErrors||null,v.missing=p?.missing||null,v}let T=new Error(`Sub-graph '${n}' trigger rejected (${h.status}): ${_}`);throw T.code="SUBGRAPH_TRIGGER_FAILED",T.status=h.status,T.subgraph=n,T}let l=await h.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return b.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:n};let w=Number.isFinite(e.timeoutMs)?e.timeoutMs:An,m=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:vn,I=`${r}/executions/${encodeURIComponent(c)}`,A=Date.now()+w,E="accepted",f=0,g=null;for(;Date.now()<A;){await new Promise(v=>setTimeout(v,m)),f+=1;let p;try{p=await fetch(I,{headers:{Authorization:`Bearer ${s}`}})}catch(v){g=v?.message||String(v),b.warn(`[sub-graph] status poll for ${c} could not reach the API (${g}), will retry`);continue}if(!p.ok){if(p.status>=500){b.warn(`[sub-graph] status poll for ${c} returned ${p.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${p.status}`)}let _;try{_=await p.json()}catch(v){g=v?.message||String(v),b.warn(`[sub-graph] status poll for ${c} returned an unreadable body (${g}), will retry`);continue}let T=_?.data||_?.execution||_;if(E=T?.status||E,Tn.has(E)){if(E!=="completed"){let Q=new Error(`Sub-graph '${n}' (${c}) ended in status '${E}'`);throw Q.subgraphJobId=c,Q.subgraphStatus=E,Q}let v=T?.finalState||T?.state||{},D=Tt(v,e.output);return b.info(`[sub-graph] '${n}' (${c}) completed after ${f} polls`),D}}let $=new Error(`Sub-graph '${n}' (${c}) timed out after ${Math.round(w/1e3)}s (last status: ${E})`+(g?`; the status API was unreachable on the last attempt (${g})`:""));throw $.subgraphJobId=c,$.subgraphStatus=E,g&&($.subgraphTransportError=g),$}import{existsSync as xt,readFileSync as Nn}from"node:fs";import{join as De,dirname as Ot}from"node:path";var Se=class{static async loadContext(e,t,o={}){let r={},i=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Ot(De(t,e));for(let u of i){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let h=u.replace(/\.[^.]+$/,"").toLowerCase();r[h]=d}}}let s=o.discovery||{};for(let[a,u]of Object.entries(s))try{let d=De(t,u);xt(d)&&(r[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return r}static async findAndMergeContextFiles(e,t,o){let r=[],i=t;for(;i.startsWith(o);){let s=De(i,e);if(xt(s))try{r.unshift(await this.loadFile(s))}catch(u){console.warn(`[workflow] could not load ${e} from ${s}: ${u.message}`)}let a=Ot(i);if(a===i)break;i=a}return r.length===0?null:r.every(s=>typeof s=="string")?r.join(`
34
+ ${i}`);let a=o(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Re(d,V);if(ht(l)){let h=JSON.parse(ft(l,"utf-8"));h.currentNode=this.name,Ce(l,JSON.stringify(h,null,2),"utf-8")}let c=Re(d,"..",V);if(ht(c))try{let h=JSON.parse(ft(c,"utf-8"));h.currentNode=this.name,Ce(c,JSON.stringify(h,null,2),"utf-8")}catch{}}}catch(l){b.debug(`[workflow] could not update session info: ${l.message}`)}let g=null;for(let l=0;l<=this.retries;l++)try{b.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=o().config||{},h=c.agents||{},y=this.config.agent??h[this.name]??null,I={state:o()};y&&(I.preferredAgent=y);let T={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=e?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(ie(),se))).invokeAgent);let f=await E(i,I,T),m,$;if(typeof f=="string"?(m=f,$=null):f.structured?(m=f.raw||JSON.stringify(f.structured,null,2),$=f.structured):(m=f.raw||JSON.stringify(f,null,2),$=f.extracted||null),d)try{let p=Re(d,this.name,"raw_stream_output.txt");ln(un(p),{recursive:!0}),Ce(p,typeof m=="string"?m:JSON.stringify(m),"utf-8")}catch(p){b.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&$){b.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify($,null,2)}`);let p=$;if(typeof this.onComplete=="function")try{p=await this.onComplete(o(),$)}catch(_){b.warn(`[workflow] onComplete hook failed: ${_.message}`)}return{success:!0,output:p,raw:m}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:m}),raw:m}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(m);return b.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),P.step("Output parsed"),{success:!0,output:p,raw:m}}return{success:!0,output:m,raw:m}}catch(c){g=c,l<this.retries&&b.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:g.message,raw:null}}};G();G();import{mkdirSync as fn,existsSync as Z,statSync as $t,readdirSync as vt,rmSync as hn}from"node:fs";import{spawn as bt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as gn}from"node:url";import{AsyncLocalStorage as mn}from"node:async_hooks";import{AsyncLocalStorage as dn}from"node:async_hooks";var ae=new dn;function X(){let n=ae.getStore();return n||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 gt(n,e){let t=ae.getStore()||X(),o=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return ae.run(o,e)}function mt(n,e,t){let o=ae.getStore()||X(),r=Object.freeze({...o,agent:n??o.agent??null,signal:e??o.signal??null});return ae.run(r,t)}var Be=new Map,Me=new Map,yt=new Map;function wt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Be.set(n,e),Me.set(n,"ready"),yt.set(n,{...t,cachedAt:Date.now()})}function St(n,e){Me.set(n,"failed"),yt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Be.delete(n)}function _t(n){return Me.get(n)==="ready"?Be.get(n):null}var me=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function yn(){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"}},It=new mn,Et=Promise.resolve();async function wn(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(t.length===0)return e();let o=It.getStore()===!0,r=null;if(!o){let s=Et;Et=new Promise(a=>{r=a}),await s}let i=new Map;try{for(let[s,a]of t)i.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=a;return b.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await It.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;r&&r()}}function Sn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,o=process.env.PROJECT_ID,r=process.env.PROJECT_API_TOKEN;if(!t||!o||!r)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:r}}async function _n({apiBase:n,authToken:e,body:t}){let o;try{o=await fetch(`${n}/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 r=null;try{r=await o.json()}catch{}if(!o.ok){if(o.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(o.status===429){let i=r?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=i,s}if(o.status===400&&r?.validationErrors){let i=new Error(`Sub-graph rejected input: ${r?.error||r?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=r.validationErrors,i.missing=r.missing,i}throw new N("begin-status",`begin returned ${o.status}`)}return r?.data||r}async function Y({apiBase:n,authToken:e,payload:t}){try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});o.ok||b.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){b.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function bn(n,e){let t=U(e,".ready"),o=U(e,"graph.mjs");if(Z(t)&&Z(o))return;fn(e,{recursive:!0});let r=U(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),u=s(r,"wx");a(u),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(Z(t)&&Z(o))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 g=bt("curl",["-fsSL",n],{stdio:["ignore","pipe","inherit"]}),l=bt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});g.stdout.pipe(l.stdin);let c,h,y=()=>{if(c!==void 0&&h!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(h!==0)return d(new Error(`tar exited ${h}`));u()}};g.on("close",I=>{c=I,y()}),l.on("close",I=>{h=I,y()}),g.on("error",d),l.on("error",d)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(r)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(r)}catch{}throw new N("bundle-extract-failed",s.message)}}async function In(n){let e=U(n,"graph.mjs");if(!Z(e))throw new N("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(gn(e).href)}catch(r){throw new N("import-failed",`${r?.code||r?.name||"unknown"}: ${r.message}`)}let o=t.default||Object.values(t).find(r=>typeof r=="function"&&r.prototype?.buildGraph);if(!o)throw new N("entry-class-missing","no buildGraph() class export found");return o}async function Tt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=X(),o;try{o=Sn()}catch(p){throw p}b.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let r=await _n({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:g,bundleReady:l,nodeConfigs:c}=r,h=yn();if(s&&s!==h)throw await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new N("runtime-mismatch",`${h} vs ${s}`);if(!l||!a)throw await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new N("no-bundle","workflow bundle not built yet");let y=_t(n);if(!y){let p=U(me,`${g}@${d||"0"}`);try{await bn(a,p);try{$n()}catch{}}catch(_){throw _.fallback&&await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason}}}),_}try{y=await In(p),wt(n,y,{workflowUuid:g,version:d,runtimeTag:s,cacheDir:p})}catch(_){throw St(n,_),await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason||"IMPORT_FAILED"}}}),_.fallback?_:new N("import-failed",_.message)}}let I=Date.now(),T=r.env&&typeof r.env=="object"&&!Array.isArray(r.env)?r.env:null,E=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...E?{nodeConfigs:c}:{}},m,$;try{m=await wn(T,async()=>{let _=await(typeof y=="function"&&y.prototype?.buildGraph?new y:y).buildGraph();return gt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>_.run(e.parentAgent,f,{signal:e.signal}))}),$=m&&typeof m=="object"&&"state"in m?m.state:m}catch(p){throw await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-I}}),p}if(m&&typeof m=="object"&&m.stoppedExternally){await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"canceled",finalState:$,durationMs:Date.now()-I}});let p=new Error(`Sub-graph '${n}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"completed",finalState:$,durationMs:Date.now()-I}}),{finalState:$,executionId:i}}function En(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),r;try{r=$t(o)}catch{continue}if(r.isDirectory()){let i;try{i=vt(o)}catch{continue}for(let s of i)t.push(U(o,s))}else e+=r.size}return e}function $n({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Z(me))return{evicted:0,freedBytes:0};let e=vt(me),t=[],o=0;for(let a of e){let u=U(me,a),d;try{d=$t(u)}catch{continue}let g=d.isDirectory()?En(u):d.size;o+=g,t.push({name:a,full:u,size:g,mtimeMs:d.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let r=Math.floor(n*.7),i=0,s=0;for(let a of t){if(o-i<=r)break;if(!Z(U(a.full,".lock")))try{hn(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(u){b.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return s>0&&b.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:o-i}}catch(e){return b.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var vn=2e3,Tn=600*1e3,An=new Set(["completed","failed","canceled","timeout"]);function kn(){let n=process.env.PROGRESS_API_URL;if(!n)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 n.replace(/\/executions\/?$/,"")}function xn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function On(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function Pn(){return process.env.EXECUTION_ID||null}function At(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,o)=>t==null?t:t[o],n):n}async function kt(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=X();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=o)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${o}. 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 '${n}'`);let{finalState:p}=await Tt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),_=At(p,e.output);return b.info(`[sub-graph] '${n}' completed in-process`),_}catch(p){if(p instanceof N||p?.fallback)b.info(`[sub-graph] in-process fallback for '${n}': ${p.reason||"unknown"} \u2014 using HTTP`);else throw p}let r=kn(),i=xn(),s=On(),a=Pn(),u=`${r}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(n)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};b.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let g=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(d)});if(!g.ok){let p=null,_="";try{p=await g.json(),_=p?.error||p?.message||JSON.stringify(p)}catch{_=await g.text().catch(()=>"")}if(g.status===429){let v=p?.quotaInfo||{},D=new Error(`Sub-graph '${n}' blocked by execution quota (${v.used??"?"}/${v.limit??"?"} on plan ${v.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw D.code="SUBGRAPH_QUOTA_EXCEEDED",D.status=429,D.subgraph=n,D.quotaInfo=v,D}if(g.status===400){let v=new Error(`Sub-graph '${n}' rejected input: ${_}`);throw v.code="SUBGRAPH_INVALID_INPUT",v.status=400,v.subgraph=n,v.validationErrors=p?.validationErrors||null,v.missing=p?.missing||null,v}let A=new Error(`Sub-graph '${n}' trigger rejected (${g.status}): ${_}`);throw A.code="SUBGRAPH_TRIGGER_FAILED",A.status=g.status,A.subgraph=n,A}let l=await g.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return b.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:n};let h=Number.isFinite(e.timeoutMs)?e.timeoutMs:Tn,y=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:vn,I=`${r}/executions/${encodeURIComponent(c)}`,T=Date.now()+h,E="accepted",f=0,m=null;for(;Date.now()<T;){await new Promise(v=>setTimeout(v,y)),f+=1;let p;try{p=await fetch(I,{headers:{Authorization:`Bearer ${s}`}})}catch(v){m=v?.message||String(v),b.warn(`[sub-graph] status poll for ${c} could not reach the API (${m}), will retry`);continue}if(!p.ok){if(p.status>=500){b.warn(`[sub-graph] status poll for ${c} returned ${p.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${p.status}`)}let _;try{_=await p.json()}catch(v){m=v?.message||String(v),b.warn(`[sub-graph] status poll for ${c} returned an unreadable body (${m}), will retry`);continue}let A=_?.data||_?.execution||_;if(E=A?.status||E,An.has(E)){if(E!=="completed"){let Q=new Error(`Sub-graph '${n}' (${c}) ended in status '${E}'`);throw Q.subgraphJobId=c,Q.subgraphStatus=E,Q}let v=A?.finalState||A?.state||{},D=At(v,e.output);return b.info(`[sub-graph] '${n}' (${c}) completed after ${f} polls`),D}}let $=new Error(`Sub-graph '${n}' (${c}) timed out after ${Math.round(h/1e3)}s (last status: ${E})`+(m?`; the status API was unreachable on the last attempt (${m})`:""));throw $.subgraphJobId=c,$.subgraphStatus=E,m&&($.subgraphTransportError=m),$}import{existsSync as xt,readFileSync as Nn}from"node:fs";import{join as je,dirname as Ot}from"node:path";var ye=class{static async loadContext(e,t,o={}){let r={},i=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Ot(je(t,e));for(let u of i){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let g=u.replace(/\.[^.]+$/,"").toLowerCase();r[g]=d}}}let s=o.discovery||{};for(let[a,u]of Object.entries(s))try{let d=je(t,u);xt(d)&&(r[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return r}static async findAndMergeContextFiles(e,t,o){let r=[],i=t;for(;i.startsWith(o);){let s=je(i,e);if(xt(s))try{r.unshift(await this.loadFile(s))}catch(u){console.warn(`[workflow] could not load ${e} from ${s}: ${u.message}`)}let a=Ot(i);if(a===i)break;i=a}return r.length===0?null:r.every(s=>typeof s=="string")?r.join(`
35
35
 
36
36
  ---
37
37
 
38
- `):r.every(s=>typeof s=="object")?Object.assign({},...r):r[r.length-1]}static async loadFile(e){let t=Nn(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 Ct,existsSync as Le,writeFileSync as Pt,unlinkSync as Cn}from"node:fs";import{join as q,resolve as Rt}from"node:path";import{config as Rn}from"dotenv";import{zodToJsonSchema as Nt}from"zod-to-json-schema";import{z as _e}from"zod";import Bn from"handlebars";function Mn({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(`
38
+ `):r.every(s=>typeof s=="object")?Object.assign({},...r):r[r.length-1]}static async loadFile(e){let t=Nn(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 Ct,existsSync as De,writeFileSync as Pt,unlinkSync as Cn}from"node:fs";import{join as q,resolve as Rt}from"node:path";import{config as Rn}from"dotenv";import{zodToJsonSchema as Nt}from"zod-to-json-schema";import{z as we}from"zod";import Bn from"handlebars";function Mn({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 g=(new Error("session trace").stack||"").split(`
39
39
  `).slice(2,14).join(`
40
40
  `);console.log(`[zibby:session] stack (${n}):
41
- ${h}`)}}function jn(){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 Dn(){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 Rt(String(e).trim())}catch{return String(e).trim()}}function Ln(){jn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Wn({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 Un(n={}){let e=at.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 Fn({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=Rt(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=Un(e),s="generated")}i=i??Date.now();let h=e.paths?.output||me;r=q(n,h,st,a)}let u=!Le(r);return u&&Ct(r,{recursive:!0}),(u||s!=="initialState.sessionPath")&&Mn({traceFrom:o,sessionId:a,sessionPath:r,idSource:s,mkdirFresh:u}),Wn({sessionPath:r,sessionId:a}),{sessionPath:r,sessionId:a,sessionTimestamp:i}}var be=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 U)&&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={},kt(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 U(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 U)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof U?t:new U(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 w=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:w,data:{nodeType:w,label:l}});let m={};c._isCustomCode&&typeof c.execute=="function"&&(m.customCode=c.execute.toString());let I=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;I&&(m.description=I);let A=this.nodePrompts.get(l);if(A)m.prompt=A;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(m.prompt=p,m.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(m.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(m.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(m.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof _e?.toJSONSchema=="function")try{p=_e.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Nt(c.outputSchema,{target:"openApi3"})}catch{}m.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else m.outputSchema={schema:c.outputSchema};let E=(this.resolvedToolsMap||{})[l];E?.toolIds&&(m.tools=E.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(m.skills=[...f]);let g=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;g&&g.length>0&&(m.plugins=g.map(p=>p&&typeof p=="object"?{...p}:p));let $=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;$&&$.length>0&&(m.stores=$.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(m).length>0&&(t[l]=m)}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 w of c)o.push({source:l,target:w});else if(c.conditional){let w=this.conditionalCodeMap.get(l)||c.routes.toString(),m=this._inferConditionalTargets(c.routes,c.labels),I=c.labels||{},A=this.nodes.get(l),E=A?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!A,f=l;if(!E){let g=`${l}__branch`;e.push({id:g,type:"decision",data:{nodeType:"decision",label:g}}),o.push({source:l,target:g}),f=g}for(let g of m){let $={source:f,target:g,data:{conditionalCode:w}};I[g]&&($.label=I[g]),o.push($)}}let r=l=>{if(!l)return null;if(typeof _e?.toJSONSchema=="function")try{return _e.toJSONSchema(l)}catch{}try{return Nt(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,w)=>o.get(c)-o.get(w)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,w)=>o.get(c)-o.get(w))[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(S){let y=new Error(`agent.normalizeInput() rejected the trigger input: ${S?.message||S}`);throw y.cause=S,y.code=S?.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();Rn({path:q(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let S=q(s,".zibby.config.js");Le(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||{},h=this._runtimeSchema();if(h){let S=h.safeParse(t);if(!S.success){let y=S.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(", ")}`)}P.step("State validated against schema")}let l=Dn(),c=t.sessionPath||l;c||Ln();let{sessionPath:w,sessionTimestamp:m,sessionId:I}=Fn({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});P.step(`Session ${I}`);let A=await Se.loadContext(t.specPath||"",s,d);Object.keys(A).length>0&&P.step(`Context loaded: ${Object.keys(A).join(", ")}`);let E=t.outputPath;!E&&t.specPath&&(e?.calculateOutputPath?E=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new fe({...t,config:a,agentType:u,outputPath:E,sessionPath:w,sessionTimestamp:m,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:r.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:$}=await Promise.resolve().then(()=>(ye(),lt)),p=a.skills&&typeof a.skills=="object"?a.skills:{},_=Object.values(p).filter(S=>S&&typeof S=="object"&&typeof S.id=="string"),T=S=>{for(let y of _)if(y.id===S)return y;return $(S)},v=new Set;for(let[,S]of this.nodes)for(let y of S.config?.skills||[])v.add(y);for(let S of v){let y=T(S);if(typeof y?.middleware=="function")try{let B=await y.middleware();typeof B=="function"&&g.set(S,B)}catch{}}let{backEdges:D,joinDegree:Q}=this._analyzeFlow(),Ee=new Map,ee=[],$e=(S,y,B)=>{if(!S||S==="END")return;let L=Q.get(S)||0;if(B&&L>1&&!D.has(`${y}->${S}`)){let te=(Ee.get(S)||0)+1;if(te<L){Ee.set(S,te);return}Ee.set(S,0)}ee.includes(S)||ee.push(S)};this.entryPoint&&ee.push(this.entryPoint);let le=[],Ge=a?.recursionLimit??100,Lt=0;try{for(;ee.length>0;){let y=ee.pop();if(!y||y==="END")continue;if(++Lt>Ge)throw new Error(`Workflow exceeded recursion limit (${Ge}) \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=q(w,it);if(Le(B)){try{Cn(B)}catch{}r.abort()}if(r.signal.aborted)return console.warn(`
42
- \u{1F6D1} External stop requested \u2014 ending workflow.`),P.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:le,stoppedExternally:!0};let L=this.nodes.get(y);if(!L)throw new Error(`Node '${y}' not found in graph`);let te=JSON.stringify({sessionPath:w,sessionTimestamp:m,currentNode:y,createdAt:new Date().toISOString(),config:f.get("config")}),Wt=q(w,V);Pt(Wt,te,"utf-8");let He=f.get("config")?.paths?.output||me,Ut=q(s,He,V);Ct(q(s,He),{recursive:!0});try{Pt(Ut,te,"utf-8")}catch{}let Je=t.onPipelineProgress;if(typeof Je=="function")try{Je({cwd:s,sessionPath:w,sessionId:I,outputBase:f.get("config")?.paths?.output||me,currentNode:y})}catch{}let Ft=(this.resolvedToolsMap||{})[y]||null;f.set("_currentNodeTools",Ft);let Gt=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Gt[y]||{}),P.nodeStart(y);let ze=Date.now(),ue=this.nodePrompts.get(y);if(!this._invokeAgent){let x=await Promise.resolve().then(()=>(ae(),ie));this._invokeAgent=x.invokeAgent}let Ht=this._invokeAgent,ve={},Jt=L.config?.skills||[];for(let x of Jt){let C=T(x);if(typeof C?.invokeAgentOptions=="function")try{let k=C.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:y});k&&typeof k=="object"&&(ve={...ve,...k})}catch(k){console.warn(`[graph] skill '${x}' invokeAgentOptions threw: ${k.message}`)}}let Ye=async(x,C,k={})=>{let M=Ht(x,C,{...ve,...k,signal:r.signal});return M.catch(()=>{}),r.signal.aborted?M:Promise.race([M,new Promise((K,W)=>{let R=()=>{setTimeout(()=>{let ne=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);ne.name="AbortError",W(ne)},i)};r.signal.addEventListener("abort",R,{once:!0})})])},zt=async(x={},C={})=>{let k=C.prompt||"";if(ue){let M=this._compiledPrompts.get(y);M||(M=Bn.compile(ue,{noEscape:!0}),this._compiledPrompts.set(y,M));try{k=M(x)}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 Ye(k,{state:f.getAll(),images:C.images||[]},{model:C.model||f.get("model"),workspace:f.get("workspace"),schema:C.schema,...C,signal:r.signal})},Ze=f.getAll(),Yt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let x of Yt)Object.prototype.hasOwnProperty.call(Ze,x)&&console.warn(`[workflow] node "${y}": state key "${x}" is shadowed by the engine context prop; read it via context.state.get('${x}')`);let qe={...Ze,state:f,invokeAgent:zt,_coreInvokeAgent:Ye,agent:e,nodeId:y,promptTemplate:ue,getPromptTemplate:()=>ue};try{let x=(L.config?.skills||[]).map(R=>g.get(R)).filter(Boolean),C=[...this.middleware,...x],k;k=await mt(e,r.signal,async()=>C.length>0?this._composeMiddleware(C,y,async()=>L.execute(qe,f),f.getAll(),f):L.execute(qe,f));let M=Date.now()-ze;if(le.push({node:y,success:k.success,duration:M,timestamp:new Date().toISOString()}),!k.success){if(r.signal.aborted)return P.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:le,stoppedExternally:!0};f.append("errors",{node:y,error:k.error});let R=L.config?.retries||0,ne=`${y}_retries`,de=f.getAll()[ne]||0;if(de<R){P.stepInfo(`Retrying (attempt ${de+1}/${R})`),f.update({[ne]:de+1,[`${y}_raw`]:k.raw});continue}throw P.nodeFailed(y,k.error,{duration:M}),new Error(`Node '${y}' failed after ${de} attempts: ${k.error}`)}f.update({[y]:k.output});let K=this._summarizeNodeOutput(y,k.output);P.nodeComplete(y,{duration:M,details:K});let W=this.edges.get(y);if(W)if(W.conditional){let R=W.routes(f.getAll());P.route(y,R),$e(R,y,!1)}else if(Array.isArray(W))for(let R=W.length-1;R>=0;R--)$e(W[R],y,!0);else $e(W,y,!0)}catch(x){throw P.isInsideNode&&P.nodeFailed(y,x.message,{duration:Date.now()-ze}),f.set("failed",!0),f.set("failedAt",y),x}}P.graphComplete();let S={success:!0,state:f.getAll(),executionLog:le};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}`)}}}};var We=Symbol.for("@zibby/agent-workflow.nodes");globalThis[We]||(globalThis[We]=new Map);var Ue=globalThis[We];function Gn(n,e){Ue.set(n,e)}function Bt(n){return Ue.get(n)}function Fe(n){return Ue.has(n)}Gn("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(()=>(ae(),ie))).invokeAgent);let r=e.extraPromptInstructions||"Execute the task based on the current state.",i=Hn(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 Hn(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,w)=>c?.[w],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
- ${h}`),a.includes(".")||s.add(u)}return i.length===0?n:`${n}
41
+ ${g}`)}}function jn(){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 Dn(){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 Rt(String(e).trim())}catch{return String(e).trim()}}function Ln(){jn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Wn({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 Fn(n={}){let e=at.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=Rt(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=Fn(e),s="generated")}i=i??Date.now();let g=e.paths?.output||he;r=q(n,g,st,a)}let u=!De(r);return u&&Ct(r,{recursive:!0}),(u||s!=="initialState.sessionPath")&&Mn({traceFrom:o,sessionId:a,sessionPath:r,idSource:s,mkdirFresh:u}),Wn({sessionPath:r,sessionId:a}),{sessionPath:r,sessionId:a,sessionTimestamp:i}}var Se=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 F)&&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 g=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof s.input=="function"?l=s.input(g):s.input&&typeof s.input=="object"?l=s.input:l={},kt(s.workflow,{input:l,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(g):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:g?._signal,parentAgent:d?.agent})}},u=new F(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 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(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 h=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:h,data:{nodeType:h,label:l}});let y={};c._isCustomCode&&typeof c.execute=="function"&&(y.customCode=c.execute.toString());let I=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;I&&(y.description=I);let T=this.nodePrompts.get(l);if(T)y.prompt=T;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(y.prompt=p,y.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(y.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(y.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(y.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=Nt(c.outputSchema,{target:"openApi3"})}catch{}y.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else y.outputSchema={schema:c.outputSchema};let E=(this.resolvedToolsMap||{})[l];E?.toolIds&&(y.tools=E.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(y.skills=[...f]);let m=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;m&&m.length>0&&(y.plugins=m.map(p=>p&&typeof p=="object"?{...p}:p));let $=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;$&&$.length>0&&(y.stores=$.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(y).length>0&&(t[l]=y)}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 h of c)o.push({source:l,target:h});else if(c.conditional){let h=this.conditionalCodeMap.get(l)||c.routes.toString(),y=this._inferConditionalTargets(c.routes,c.labels),I=c.labels||{},T=this.nodes.get(l),E=T?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!T,f=l;if(!E){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 y){let $={source:f,target:m,data:{conditionalCode:h}};I[m]&&($.label=I[m]),o.push($)}}let r=l=>{if(!l)return null;if(typeof we?.toJSONSchema=="function")try{return we.toJSONSchema(l)}catch{}try{return Nt(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),g=r(this.contextSchema);return{nodes:s,edges:o,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:g}}_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),g=[];for(;g.length<e.length;){let l;if(d.length>0){if(d.sort((c,h)=>o.get(c)-o.get(h)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,h)=>o.get(c)-o.get(h))[0];a.add(l),u.delete(l),g.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 g}_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,g;for(;(g=d.exec(o))!==null;)u.add(g[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(S){let w=new Error(`agent.normalizeInput() rejected the trigger input: ${S?.message||S}`);throw w.cause=S,w.code=S?.code||"NORMALIZE_INPUT_FAILED",w}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();Rn({path:q(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let S=q(s,".zibby.config.js");De(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||{},g=this._runtimeSchema();if(g){let S=g.safeParse(t);if(!S.success){let w=S.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),w.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${w.join(", ")}`)}P.step("State validated against schema")}let l=Dn(),c=t.sessionPath||l;c||Ln();let{sessionPath:h,sessionTimestamp:y,sessionId:I}=Un({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});P.step(`Session ${I}`);let T=await ye.loadContext(t.specPath||"",s,d);Object.keys(T).length>0&&P.step(`Context loaded: ${Object.keys(T).join(", ")}`);let E=t.outputPath;!E&&t.specPath&&(e?.calculateOutputPath?E=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new de({...t,config:a,agentType:u,outputPath:E,sessionPath:h,sessionTimestamp:y,context:T,resolvedTools:this.resolvedToolsMap||{},_signal:r.signal}),m=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:$}=await Promise.resolve().then(()=>(ge(),lt)),p=a.skills&&typeof a.skills=="object"?a.skills:{},_=Object.values(p).filter(S=>S&&typeof S=="object"&&typeof S.id=="string"),A=S=>{for(let w of _)if(w.id===S)return w;return $(S)},v=new Set;for(let[,S]of this.nodes)for(let w of S.config?.skills||[])v.add(w);for(let S of v){let w=A(S);if(typeof w?.middleware=="function")try{let R=await w.middleware();typeof R=="function"&&m.set(S,R)}catch{}}let{backEdges:D,joinDegree:Q}=this._analyzeFlow(),be=new Map,ee=[],Ie=(S,w,R)=>{if(!S||S==="END")return;let L=Q.get(S)||0;if(R&&L>1&&!D.has(`${w}->${S}`)){let te=(be.get(S)||0)+1;if(te<L){be.set(S,te);return}be.set(S,0)}ee.includes(S)||ee.push(S)};this.entryPoint&&ee.push(this.entryPoint);let ce=[],Ue=a?.recursionLimit??100,Lt=0;try{for(;ee.length>0;){let w=ee.pop();if(!w||w==="END")continue;if(++Lt>Ue)throw new Error(`Workflow exceeded recursion limit (${Ue}) \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 R=q(h,it);if(De(R)){try{Cn(R)}catch{}r.abort()}if(r.signal.aborted)return console.warn(`
42
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),P.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ce,stoppedExternally:!0};let L=this.nodes.get(w);if(!L)throw new Error(`Node '${w}' not found in graph`);let te=JSON.stringify({sessionPath:h,sessionTimestamp:y,currentNode:w,createdAt:new Date().toISOString(),config:f.get("config")}),Wt=q(h,V);Pt(Wt,te,"utf-8");let Ge=f.get("config")?.paths?.output||he,Ft=q(s,Ge,V);Ct(q(s,Ge),{recursive:!0});try{Pt(Ft,te,"utf-8")}catch{}let He=t.onPipelineProgress;if(typeof He=="function")try{He({cwd:s,sessionPath:h,sessionId:I,outputBase:f.get("config")?.paths?.output||he,currentNode:w})}catch{}let Ut=(this.resolvedToolsMap||{})[w]||null;f.set("_currentNodeTools",Ut);let Gt=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Gt[w]||{}),P.nodeStart(w);let Je=Date.now(),le=this.nodePrompts.get(w);if(!this._invokeAgent){let x=await Promise.resolve().then(()=>(ie(),se));this._invokeAgent=x.invokeAgent}let Ht=this._invokeAgent,Ee={},Jt=L.config?.skills||[];for(let x of Jt){let C=A(x);if(typeof C?.invokeAgentOptions=="function")try{let k=C.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:w});k&&typeof k=="object"&&(Ee={...Ee,...k})}catch(k){console.warn(`[graph] skill '${x}' invokeAgentOptions threw: ${k.message}`)}}let ze=async(x,C,k={})=>{let B=Ht(x,C,{...Ee,...k,signal:r.signal});return B.catch(()=>{}),r.signal.aborted?B:Promise.race([B,new Promise((K,W)=>{let M=()=>{setTimeout(()=>{let qe=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);qe.name="AbortError",W(qe)},i)};r.signal.addEventListener("abort",M,{once:!0})})])},zt=async(x={},C={})=>{let k=C.prompt||"";if(le){let B=this._compiledPrompts.get(w);B||(B=Bn.compile(le,{noEscape:!0}),this._compiledPrompts.set(w,B));try{k=B(x)}catch(K){throw console.error(`\u274C Template rendering failed for node '${w}':`,K.message),new Error(`Template rendering failed: ${K.message}`,{cause:K})}}else if(!k)throw new Error(`No prompt template configured for node '${w}' and no prompt provided in options`);return ze(k,{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(),Yt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let x of Yt)Object.prototype.hasOwnProperty.call(Ye,x)&&console.warn(`[workflow] node "${w}": state key "${x}" is shadowed by the engine context prop; read it via context.state.get('${x}')`);let Ze={...Ye,state:f,invokeAgent:zt,_coreInvokeAgent:ze,agent:e,nodeId:w,promptTemplate:le,getPromptTemplate:()=>le};try{let x=(L.config?.skills||[]).map(M=>m.get(M)).filter(Boolean),C=[...this.middleware,...x],k;k=await mt(e,r.signal,async()=>C.length>0?this._composeMiddleware(C,w,async()=>L.execute(Ze,f),f.getAll(),f):L.execute(Ze,f));let B=Date.now()-Je;if(ce.push({node:w,success:k.success,duration:B,timestamp:new Date().toISOString()}),!k.success){if(r.signal.aborted)return P.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ce,stoppedExternally:!0};f.append("errors",{node:w,error:k.error});let M=(L.config?.retries||0)+1;throw P.nodeFailed(w,k.error,{duration:B}),new Error(`Node '${w}' failed after ${M} attempt(s): ${k.error}`)}f.update({[w]:k.output});let K=this._summarizeNodeOutput(w,k.output);P.nodeComplete(w,{duration:B,details:K});let W=this.edges.get(w);if(W)if(W.conditional){let M=W.routes(f.getAll());P.route(w,M),Ie(M,w,!1)}else if(Array.isArray(W))for(let M=W.length-1;M>=0;M--)Ie(W[M],w,!0);else Ie(W,w,!0)}catch(x){throw P.isInsideNode&&P.nodeFailed(w,x.message,{duration:Date.now()-Je}),f.set("failed",!0),f.set("failedAt",w),x}}P.graphComplete();let S={success:!0,state:f.getAll(),executionLog:ce};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}`)}}}};var Le=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Le]||(globalThis[Le]=new Map);var We=globalThis[Le];function Gn(n,e){We.set(n,e)}function Bt(n){return We.get(n)}function Fe(n){return We.has(n)}Gn("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=Hn(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 Hn(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,h)=>c?.[h],e);if(d===void 0)continue;let g=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
+ ${g}`),a.includes(".")||s.add(u)}return i.length===0?n:`${n}
44
44
 
45
45
  ---
46
46
  # Referenced Context
47
47
 
48
48
  ${i.join(`
49
49
 
50
- `)}`}ye();G();var Jn={};function jt(n,e){if(Array.isArray(e))return Mt(e);let t=Jn[n];return!t||t.length===0?null:Mt(t)}function Mt(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},o=[];for(let r of n){let i=se(r);if(!i){b.warn(`[workflow] unknown skill "${r}" \u2014 skipping`);continue}o.push(r);for(let s of i.tools||[])e.push({name:s.name,description:s.description,input_schema:s.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let s=i.resolve();s&&(t[i.serverName]={...s,toolPrefix:r})}else{let s={};for(let a of i.envKeys||[]){let u=process.env[a];u&&(s[a]=u)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:s,toolPrefix:r}}}return o.length===0?null:{toolIds:o,claudeTools:e,mcpServers:t}}G();function tr(n,e={}){let{nodes:t,edges:o,nodeConfigs:r={}}=n;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(o))throw new j("Graph edges must be an array");let i=new be(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let s=new Set,a=new Map,u={};for(let c of t){let w=Ie(c);a.set(c.id,{...c,resolvedType:w}),w==="decision"&&s.add(c.id)}for(let[c,w]of a){if(s.has(c))continue;let m=w.resolvedType,I=r[c]||{},A=jt(m,I.tools);A&&(u[c]=A);let E={};I.prompt&&(E.prompt=I.prompt);let f=Fe(m);if(b.debug(`[workflow] compiler: node "${c}" type="${m}" registered=${f}`),I.customCode&&!f)i.addNode(c,Dt(c,I.customCode,I),E),i.setNodeType(c,m);else if(f){let g=Bt(m);g.factory?i.addNode(c,g.create(c,{...I,resolvedTools:A}),E):i.addNode(c,g,E),i.setNodeType(c,m)}else if(I.executeCode)i.addNode(c,Dt(c,I.executeCode,I),E),i.setNodeType(c,m);else throw new j(`Unknown node type "${m}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=u;let d=new Set;for(let c of o)s.has(c.target)||d.add(c.target);let h=t.find(c=>!s.has(c.id)&&!d.has(c.id));if(!h)throw new j("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(h.id);let l=zn(o,"source");for(let c of o)if(!s.has(c.source))if(s.has(c.target)){let w=c.target,m=l.get(w)||[];if(m.length===0)throw new j(`Decision node "${w}" has no outgoing edges`);let I=Yn(w,m,s);i.addConditionalEdges(c.source,I)}else i.addEdge(c.source,c.target);return i}function nr(n){let e=[];if(!n||typeof n!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(n.nodes)||n.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(n.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=n.nodeConfigs||{};for(let a of n.nodes){let u=Ie(a);if(u==="decision"||Fe(u))continue;let d=t[a.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${u}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let o=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)o.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),o.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let r=new Set(n.nodes.filter(a=>Ie(a)==="decision").map(a=>a.id)),i=new Set;for(let a of n.edges)r.has(a.target)||i.add(a.target);let s=n.nodes.filter(a=>!r.has(a.id)&&!i.has(a.id));s.length===0?e.push("No entry point found (every node has incoming edges)"):s.length>1&&e.push(`Multiple entry points found: ${s.map(a=>a.id).join(", ")}`);for(let a of r){let u=n.edges.filter(h=>h.source===a);u.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),u.some(h=>h.data?.conditionalCode||h.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function or(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>Ie(e)!=="decision").map(e=>e.id)}function Ie(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function zn(n,e){let t=new Map;for(let o of n){let r=o[e];t.has(r)||t.set(r,[]),t.get(r).push(o)}return t}function Yn(n,e,t){let o=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!o)throw new j(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let r=o.data?.conditionalCode||o.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),s;try{let u=new Function(`return (${r})`)();s=d=>{let h=u(d);return i.has(h)||b.warn(`[workflow] conditional route from "${n}" returned "${h}" which is not in valid targets: ${[...i].join(", ")}`),h}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return s}function Dt(n,e,t={}){let o;try{o=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new j(`Failed to compile customCode for node "${n}": ${s.message}`)}let r=o(async(...s)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(ae(),ie));return a(...s)},typeof Ae<"u"?Ae:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:n,_isCustomCode:!0,outputSchema:i,execute:async s=>{try{let a=await r(s);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var j=class extends Error{constructor(e){super(e),this.name="CompilationError"}};export{j as CompilationError,tr as compileGraph,or as extractSteps,nr as validateGraphConfig};
50
+ `)}`}ge();G();var Jn={};function jt(n,e){if(Array.isArray(e))return Mt(e);let t=Jn[n];return!t||t.length===0?null:Mt(t)}function Mt(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},o=[];for(let r of n){let i=re(r);if(!i){b.warn(`[workflow] unknown skill "${r}" \u2014 skipping`);continue}o.push(r);for(let s of i.tools||[])e.push({name:s.name,description:s.description,input_schema:s.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let s=i.resolve();s&&(t[i.serverName]={...s,toolPrefix:r})}else{let s={};for(let a of i.envKeys||[]){let u=process.env[a];u&&(s[a]=u)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:s,toolPrefix:r}}}return o.length===0?null:{toolIds:o,claudeTools:e,mcpServers:t}}G();function tr(n,e={}){let{nodes:t,edges:o,nodeConfigs:r={}}=n;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(o))throw new j("Graph edges must be an array");let i=new Se(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let s=new Set,a=new Map,u={};for(let c of t){let h=_e(c);a.set(c.id,{...c,resolvedType:h}),h==="decision"&&s.add(c.id)}for(let[c,h]of a){if(s.has(c))continue;let y=h.resolvedType,I=r[c]||{},T=jt(y,I.tools);T&&(u[c]=T);let E={};I.prompt&&(E.prompt=I.prompt);let f=Fe(y);if(b.debug(`[workflow] compiler: node "${c}" type="${y}" registered=${f}`),I.customCode&&!f)i.addNode(c,Dt(c,I.customCode,I),E),i.setNodeType(c,y);else if(f){let m=Bt(y);m.factory?i.addNode(c,m.create(c,{...I,resolvedTools:T}),E):i.addNode(c,m,E),i.setNodeType(c,y)}else if(I.executeCode)i.addNode(c,Dt(c,I.executeCode,I),E),i.setNodeType(c,y);else throw new j(`Unknown node type "${y}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=u;let d=new Set;for(let c of o)s.has(c.target)||d.add(c.target);let g=t.find(c=>!s.has(c.id)&&!d.has(c.id));if(!g)throw new j("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(g.id);let l=zn(o,"source");for(let c of o)if(!s.has(c.source))if(s.has(c.target)){let h=c.target,y=l.get(h)||[];if(y.length===0)throw new j(`Decision node "${h}" has no outgoing edges`);let I=Yn(h,y,s);i.addConditionalEdges(c.source,I)}else i.addEdge(c.source,c.target);return i}function nr(n){let e=[];if(!n||typeof n!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(n.nodes)||n.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(n.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=n.nodeConfigs||{};for(let a of n.nodes){let u=_e(a);if(u==="decision"||Fe(u))continue;let d=t[a.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${u}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let o=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)o.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),o.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let r=new Set(n.nodes.filter(a=>_e(a)==="decision").map(a=>a.id)),i=new Set;for(let a of n.edges)r.has(a.target)||i.add(a.target);let s=n.nodes.filter(a=>!r.has(a.id)&&!i.has(a.id));s.length===0?e.push("No entry point found (every node has incoming edges)"):s.length>1&&e.push(`Multiple entry points found: ${s.map(a=>a.id).join(", ")}`);for(let a of r){let u=n.edges.filter(g=>g.source===a);u.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),u.some(g=>g.data?.conditionalCode||g.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function or(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>_e(e)!=="decision").map(e=>e.id)}function _e(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function zn(n,e){let t=new Map;for(let o of n){let r=o[e];t.has(r)||t.set(r,[]),t.get(r).push(o)}return t}function Yn(n,e,t){let o=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!o)throw new j(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let r=o.data?.conditionalCode||o.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),s;try{let u=new Function(`return (${r})`)();s=d=>{let g=u(d);return i.has(g)||b.warn(`[workflow] conditional route from "${n}" returned "${g}" which is not in valid targets: ${[...i].join(", ")}`),g}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return s}function Dt(n,e,t={}){let o;try{o=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new j(`Failed to compile customCode for node "${n}": ${s.message}`)}let r=o(async(...s)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(ie(),se));return a(...s)},typeof $e<"u"?$e:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:n,_isCustomCode:!0,outputSchema:i,execute:async s=>{try{let a=await r(s);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var j=class extends Error{constructor(e){super(e),this.name="CompilationError"}};export{j as CompilationError,tr as compileGraph,or as extractSteps,nr as validateGraphConfig};