@zibby/agent-workflow 2.0.7 → 2.0.8

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,34 +1,34 @@
1
- var H=Object.defineProperty;var x=(e,n,o)=>()=>{if(o)throw o[0];try{return e&&(n=e(e=0)),n}catch(r){throw o=[r],r}};var J=(e,n)=>{for(var o in n)H(e,o,{get:n[o],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(o=>o.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:o,envModel:r,nodeConfigModel:i}={}){let s=e.models||{},t=typeof i=="string"&&i.trim()?i.trim():null,c=n.nodeName&&s[n.nodeName]||null,a=s.default||null,l=e.agent?.[o]?.model||null,h=(typeof r=="string"?r.trim():"")||null;return t||c||a||l||n.model||h||null}function B({options:e={},stateView:n={},context:o={}}={}){return{workspace:n.workspace||e.workspace,schema:e.schema||o.schema,images:e.images||o.images||[],skills:e.skills||o.skills||[],extraMcpServers:e.extraMcpServers||n.extraMcpServers||o.extraMcpServers||[],plugins:e.plugins||o.plugins||[]}}function F(e={}){let{state:n={},preferredAgent:o=null}=e,r=o||n.agentType||process.env.AGENT_TYPE;if(!r){let s=k.map(t=>t.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(t=>t.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={},o={}){let r=n.state&&typeof n.state.getAll=="function"?n.state.getAll():n.state||{},i={...n,state:r},s=F(i),t=r.config||o.config||{},c=r._currentNodeConfig||{},a=typeof c.agent=="string"?c.agent.trim():"",l=!a||a===s.name?c.model:null,h=G({config:t,options:o,strategyName:s.name,envModel:process.env.MODEL,nodeConfigModel:l}),T={...o,model:h,...B({options:o,stateView:r,context:n}),config:t},m=e,b=T.skills||[];if(b.length>0&&!o.skipPromptFragments){let f=o.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+=`
1
+ var Q=Object.defineProperty;var _=(e,n,o)=>()=>{if(o)throw o[0];try{return e&&(n=e(e=0)),n}catch(r){throw o=[r],r}};var X=(e,n)=>{for(var o in n)Q(e,o,{get:n[o],enumerable:!0})};function C(e){return ee.get(e)||null}var O,j,ee,ye,R=_(()=>{O=Symbol.for("@zibby/agent-workflow.skills"),j=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[O]||(globalThis[O]=new Map);globalThis[j]||(globalThis[j]=new Map);ee=globalThis[O],ye=globalThis[j]});var z,ne,P,A,E,M=_(()=>{z=()=>{},ne={debug:z,info:z,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},P=Symbol.for("@zibby/agent-workflow.logger");globalThis[P]||(globalThis[P]={impl:ne});A=globalThis[P],E={debug:(...e)=>A.impl.debug?.(...e),info:(...e)=>A.impl.info?.(...e),warn:(...e)=>A.impl.warn?.(...e),error:(...e)=>A.impl.error?.(...e)}});var G=_(()=>{});var W={};X(W,{EFFORT_LEVELS:()=>D,getAgentStrategy:()=>K,invokeAgent:()=>re,listStrategies:()=>te,registerStrategy:()=>oe,resolveInvocationEffort:()=>V,resolveInvocationExtras:()=>U,resolveInvocationModel:()=>Y});function oe(e){if(!e||typeof e.getName!="function"||typeof e.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let n=b.findIndex(o=>o.getName()===e.getName());n>=0?b[n]=e:b.push(e)}function te(){return b.map(e=>e.getName())}function Y({config:e={},options:n={},strategyName:o,envModel:r,nodeConfigModel:i}={}){let s=e.models||{},t=typeof i=="string"&&i.trim()?i.trim():null,c=n.nodeName&&s[n.nodeName]||null,a=s.default||null,l=e.agent?.[o]?.model||null,m=(typeof r=="string"?r.trim():"")||null;return t||c||a||l||n.model||m||null}function V({options:e={},envEffort:n,nodeConfigEffort:o}={}){let r=[o,e.effort,n].map(i=>typeof i=="string"?i.trim().toLowerCase():"").find(Boolean);return r?D.indexOf(r)===-1?(E.warn(`[workflow] ignoring unknown effort "${r}" \u2014 expected one of ${D.join(", ")}`),null):r:null}function U({options:e={},stateView:n={},context:o={}}={}){return{workspace:n.workspace||e.workspace,schema:e.schema||o.schema,images:e.images||o.images||[],skills:e.skills||o.skills||[],extraMcpServers:e.extraMcpServers||n.extraMcpServers||o.extraMcpServers||[],plugins:e.plugins||o.plugins||[]}}function K(e={}){let{state:n={},preferredAgent:o=null}=e,r=o||n.agentType||process.env.AGENT_TYPE;if(!r){let s=b.map(t=>t.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}E.debug(`[workflow] agent selection: requested=${r}`);let i=b.find(s=>s.getName()===r);if(!i){let s=b.map(t=>t.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 E.debug(`[workflow] using agent: ${i.getName()}`),i}async function re(e,n={},o={}){let r=n.state&&typeof n.state.getAll=="function"?n.state.getAll():n.state||{},i={...n,state:r},s=K(i),t=r.config||o.config||{},c=r._currentNodeConfig||{},a=typeof c.agent=="string"?c.agent.trim():"",l=!a||a===s.name?c.model:null,m=Y({config:t,options:o,strategyName:s.name,envModel:process.env.MODEL,nodeConfigModel:l}),T=!a||a===s.name?c.effort:null,w=V({options:o,envEffort:process.env.EFFORT,nodeConfigEffort:T}),S={...o,model:m,...w?{effort:w}:{},...U({options:o,stateView:r,context:n}),config:t},d=e,v=S.skills||[];if(v.length>0&&!o.skipPromptFragments){let k=o.connectedIntegrations;if(!k){let p=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof p=="string"&&p.trim()!==""){k={};for(let g of p.split(",").map(y=>y.trim()).filter(Boolean))k[g]=!0}}let I=p=>{let g=p&&p.requiresIntegration;return!g||!k?!0:(Array.isArray(g)?g:[g]).some(x=>k[x]===!0)},u=s.name==="assistant",N=p=>p?.inProcessOnly!==!0||u,$=v.map(p=>{let g=C(p);if(!I(g)||!N(g))return null;let y=g?.promptFragment;return typeof y=="function"?y():y}).filter(Boolean);$.length>0&&(d+=`
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 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
- fields: ${E.join(", ")}`)}return w});m+=`
5
+ `)}`)}let f=r._currentNodeConfig?.stores;if(Array.isArray(f)&&f.length>0&&typeof f[0]=="object"){let k=f.length<=8,I=f.map(u=>{let N=u?.id??u?.storeId??"",$=(u?.name??"").toString().trim()||N,p=u?.type?` \xB7 ${u.type}`:"",g=(u?.description||"").toString().replace(/\s+/g," ").trim(),y=`- ${$} \xB7 ${g||"(no description)"}${p} (id: ${N})`;if(k&&u?.schema&&typeof u.schema=="object"){let x=u.schema.properties&&typeof u.schema.properties=="object"?Object.keys(u.schema.properties):Object.keys(u.schema);x.length&&(y+=`
6
+ fields: ${x.join(", ")}`)}return y});d+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
9
- ${y.join(`
10
- `)}`}let S=r._currentNodeConfig?.extraPromptInstructions?.trim();return S&&(m+=`
9
+ ${I.join(`
10
+ `)}`}let h=r._currentNodeConfig?.extraPromptInstructions?.trim();return h&&(d+=`
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
- ${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 o=>{let r=o?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(U(),Y))).invokeAgent);let i=n.extraPromptInstructions||"Execute the task based on the current state.",s=oe(i,o),t=await r(s,{cwd:o.workspace||process.cwd(),model:o.model,tools:n.resolvedTools||null});return{success:!0,output:{raw:t,nodeId:e},raw:typeof t=="string"?t:t.raw}}})});function oe(e,n){let o=/@([\w.]+)/g,r=new Set,i;for(;(i=o.exec(e))!==null;)r.add(i[1]);if(r.size===0)return e;let s=[],t=new Set;for(let c of r){let a=c.split(".")[0];if(t.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
- ${h}`),c.includes(".")||t.add(a)}return s.length===0?e:`${e}
16
+ ${h}
17
+ `),E.debug(`[workflow] prompt length: ${d.length} chars`),s.invoke(d,S)}var L,b,D,H=_(()=>{G();M();R();L=Symbol.for("@zibby/agent-workflow.strategies");globalThis[L]||(globalThis[L]=[]);b=globalThis[L];D=["low","medium","high","xhigh","max"]});R();M();var B={};var F=Symbol.for("@zibby/agent-workflow.nodes");globalThis[F]||(globalThis[F]=new Map);var J=globalThis[F];function se(e,n){J.set(e,n)}function q(e){let n=J.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}se("ai_agent",{name:"ai_agent",factory:!0,create:(e,n={})=>({name:e,_isCustomCode:!0,execute:async o=>{let r=o?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(H(),W))).invokeAgent);let i=n.extraPromptInstructions||"Execute the task based on the current state.",s=ie(i,o),t=await r(s,{cwd:o.workspace||process.cwd(),model:o.model,tools:n.resolvedTools||null});return{success:!0,output:{raw:t,nodeId:e},raw:typeof t=="string"?t:t.raw}}})});function ie(e,n){let o=/@([\w.]+)/g,r=new Set,i;for(;(i=o.exec(e))!==null;)r.add(i[1]);if(r.size===0)return e;let s=[],t=new Set;for(let c of r){let a=c.split(".")[0];if(t.has(a))continue;let l=c.split(".").reduce((w,S)=>w?.[S],n);if(l===void 0)continue;let m=typeof l=="string"?l:l?.raw??JSON.stringify(l,null,2),T=c.replace(/_/g," ").replace(/\b\w/g,w=>w.toUpperCase());s.push(`## ${T}
18
+ ${m}`),c.includes(".")||t.add(a)}return s.length===0?e:`${e}
19
19
 
20
20
  ---
21
21
  # Referenced Context
22
22
 
23
23
  ${s.join(`
24
24
 
25
- `)}`}function xe(e,n={}){let{nodes:o,edges:r,nodeConfigs:i={}}=e,s=new Set,t=[],c=new Map;for(let f of o){let y=f.data?.nodeType||f.type;c.set(f.id,y),y==="decision"?s.add(f.id):t.push({id:f.id,nodeType:y,label:f.data?.label||f.id})}let a=t.some(f=>{let y=i[f.id]||{};return!y.customCode&&!y.executeCode}),{toolsPerNode:l,toolIdsByVar:h}=le(t,i),{simpleEdges:T,conditionalEdges:m}=fe(r,s),b=ue(t,r,s),d=[],S=n.workflowType||"workflow";return d.push(te(n)),d.push(re(S,{usesRegisteredNodes:a})),d.push(se(h)),d.push(ie(S)),d.push(ae(t,i)),d.push(ce(t,b,T,m,l,S)),d.filter(Boolean).join(`
26
- `)}function _e(e){let n={};for(let[o,r]of Object.entries(e)){let{tools:i,...s}=r;Object.keys(s).length>0&&(n[o]=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 re(e,{usesRegisteredNodes:n=!0}={}){let o=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return n&&o.push("// import './register-nodes.js'; // register custom node types here"),o.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),o.join(`
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[o,r]of e)n.push(`const ${o} = 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 o=["// \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)o.push(`// @custom \u2014 modified from default "${r.nodeType}" template`),o.push(`const ${i}_execute = ${s};`);else{let t=K(r.nodeType);t?(o.push(`// Default "${r.nodeType}" implementation`),o.push(`const ${i}_execute = ${t};`)):(o.push(`// No template for "${r.nodeType}" \u2014 passthrough`),o.push(`const ${i}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}o.push("")}return o.join(`
31
- `)}function ce(e,n,o,r,i,s){let t=["// \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"];t.push("export function buildGraph(options = {}) {"),t.push(" const graph = new WorkflowGraph(options);",""),t.push(" // Nodes");for(let a of e){let l=W(a.id);t.push(` graph.addNode('${a.id}', { name: '${a.id}', execute: ${l}_execute });`),t.push(` graph.setNodeType('${a.id}', '${a.nodeType}');`)}t.push("",` graph.setEntryPoint('${n}');`,""),(o.length>0||r.length>0)&&t.push(" // Edges");for(let a of o)t.push(` graph.addEdge('${a.source}', '${a.target}');`);for(let a of r){let l=a.code.split(`
32
- `).map((h,T)=>T===0?h:` ${h}`).join(`
25
+ `)}`}function Oe(e,n={}){let{nodes:o,edges:r,nodeConfigs:i={}}=e,s=new Set,t=[],c=new Map;for(let f of o){let h=f.data?.nodeType||f.type;c.set(f.id,h),h==="decision"?s.add(f.id):t.push({id:f.id,nodeType:h,label:f.data?.label||f.id})}let a=t.some(f=>{let h=i[f.id]||{};return!h.customCode&&!h.executeCode}),{toolsPerNode:l,toolIdsByVar:m}=pe(t,i),{simpleEdges:T,conditionalEdges:w}=ge(r,s),S=me(t,r,s),d=[],v=n.workflowType||"workflow";return d.push(ae(n)),d.push(ce(v,{usesRegisteredNodes:a})),d.push(le(m)),d.push(fe(v)),d.push(ue(t,i)),d.push(de(t,S,T,w,l,v)),d.filter(Boolean).join(`
26
+ `)}function je(e){let n={};for(let[o,r]of Object.entries(e)){let{tools:i,...s}=r;Object.keys(s).length>0&&(n[o]=s)}return n}function ae(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 ce(e,{usesRegisteredNodes:n=!0}={}){let o=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return n&&o.push("// import './register-nodes.js'; // register custom node types here"),o.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),o.join(`
28
+ `)}function le(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[o,r]of e)n.push(`const ${o} = getResolvedToolDefinitions(${JSON.stringify(r)}); // ${r.join(", ")}`);return n.push(""),n.join(`
29
+ `)}function fe(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 ue(e,n){let o=["// \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=Z(r.id),s=n[r.id]?.customCode;if(s)o.push(`// @custom \u2014 modified from default "${r.nodeType}" template`),o.push(`const ${i}_execute = ${s};`);else{let t=q(r.nodeType);t?(o.push(`// Default "${r.nodeType}" implementation`),o.push(`const ${i}_execute = ${t};`)):(o.push(`// No template for "${r.nodeType}" \u2014 passthrough`),o.push(`const ${i}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}o.push("")}return o.join(`
31
+ `)}function de(e,n,o,r,i,s){let t=["// \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"];t.push("export function buildGraph(options = {}) {"),t.push(" const graph = new WorkflowGraph(options);",""),t.push(" // Nodes");for(let a of e){let l=Z(a.id);t.push(` graph.addNode('${a.id}', { name: '${a.id}', execute: ${l}_execute });`),t.push(` graph.setNodeType('${a.id}', '${a.nodeType}');`)}t.push("",` graph.setEntryPoint('${n}');`,""),(o.length>0||r.length>0)&&t.push(" // Edges");for(let a of o)t.push(` graph.addEdge('${a.source}', '${a.target}');`);for(let a of r){let l=a.code.split(`
32
+ `).map((m,T)=>T===0?m:` ${m}`).join(`
33
33
  `);t.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&&t.push(""," graph.resolvedToolsMap = {",...c," };"),t.push(""," return graph;","}",""),t.push("export { nodeConfigs };",""),t.join(`
34
- `)}function le(e,n){let o=new Map,r=new Map;for(let i of e){let s=n[i.id]?.tools,t;if(Array.isArray(s)&&s.length>0)t=[...s].sort();else{let c=D[i.nodeType];c?.length>0&&(t=[...c].sort())}if(t){let c=`${t.map(a=>a.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;o.set(i.id,c),r.has(c)||r.set(c,t)}}return{toolsPerNode:o,toolIdsByVar:r}}function fe(e,n){let o=[],r=[],i=new Map,s=new Set;for(let t of e)i.has(t.source)||i.set(t.source,[]),i.get(t.source).push(t);for(let t of e)if(!n.has(t.source))if(n.has(t.target)){if(s.has(t.target))continue;s.add(t.target);let a=(i.get(t.target)||[]).find(l=>l.data?.conditionalCode||l.conditionalCode);a&&r.push({source:t.source,code:a.data?.conditionalCode||a.conditionalCode})}else o.push({source:t.source,target:t.target});return{simpleEdges:o,conditionalEdges:r}}function ue(e,n,o){let r=new Set;for(let s of n)o.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};
34
+ `)}function pe(e,n){let o=new Map,r=new Map;for(let i of e){let s=n[i.id]?.tools,t;if(Array.isArray(s)&&s.length>0)t=[...s].sort();else{let c=B[i.nodeType];c?.length>0&&(t=[...c].sort())}if(t){let c=`${t.map(a=>a.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;o.set(i.id,c),r.has(c)||r.set(c,t)}}return{toolsPerNode:o,toolIdsByVar:r}}function ge(e,n){let o=[],r=[],i=new Map,s=new Set;for(let t of e)i.has(t.source)||i.set(t.source,[]),i.get(t.source).push(t);for(let t of e)if(!n.has(t.source))if(n.has(t.target)){if(s.has(t.target))continue;s.add(t.target);let a=(i.get(t.target)||[]).find(l=>l.data?.conditionalCode||l.conditionalCode);a&&r.push({source:t.source,code:a.data?.conditionalCode||a.conditionalCode})}else o.push({source:t.source,target:t.target});return{simpleEdges:o,conditionalEdges:r}}function me(e,n,o){let r=new Set;for(let s of n)o.has(s.target)||r.add(s.target);let i=e.find(s=>!r.has(s.id));return i?i.id:e[0]?.id}function Z(e){return e.replace(/[^a-zA-Z0-9]/g,"_")}export{je as generateNodeConfigsJson,Oe as generateWorkflowCode};
@@ -1,45 +1,45 @@
1
- var ln=Object.defineProperty;var Oe=(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 he=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var st=(n,e)=>{for(var t in e)ln(n,t,{get:e[t],enumerable:!0})};var it,dn,Ne,ye,T,J=he(()=>{it=()=>{},dn={debug:it,info:it,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},Ne=Symbol.for("@zibby/agent-workflow.logger");globalThis[Ne]||(globalThis[Ne]={impl:dn});ye=globalThis[Ne],T={debug:(...n)=>ye.impl.debug?.(...n),info:(...n)=>ye.impl.info?.(...n),warn:(...n)=>ye.impl.warn?.(...n),error:(...n)=>ye.impl.error?.(...n)}});var bt=he(()=>{});var Et={};st(Et,{clearSkills:()=>xn,getAllSkills:()=>vn,getSkill:()=>ie,getSkillSource:()=>An,hasSkill:()=>Tn,listSkillIds:()=>$n,registerSkill:()=>In});function In(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:r=!1}=e,o=n.id;if(Y.has(o)&&!r){let i=se.get(o);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${o}" is already registered by ${a}; ${l} 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).`)}}Y.set(o,Object.freeze({...n})),t===void 0?se.delete(o):se.set(o,t)}function ie(n){return Y.get(n)||null}function Tn(n){return Y.has(n)}function An(n){return se.get(n)||null}function vn(){return new Map(Y)}function $n(){return Array.from(Y.keys())}function xn(){Y.clear(),se.clear()}var Ue,je,Y,se,we=he(()=>{Ue=Symbol.for("@zibby/agent-workflow.skills"),je=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Ue]||(globalThis[Ue]=new Map);globalThis[je]||(globalThis[je]=new Map);Y=globalThis[Ue],se=globalThis[je]});var ae={};st(ae,{getAgentStrategy:()=>At,invokeAgent:()=>Nn,listStrategies:()=>kn,registerStrategy:()=>On,resolveInvocationExtras:()=>Tt,resolveInvocationModel:()=>It});function On(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=Z.findIndex(t=>t.getName()===n.getName());e>=0?Z[e]=n:Z.push(n)}function kn(){return Z.map(n=>n.getName())}function It({config:n={},options:e={},strategyName:t,envModel:r,nodeConfigModel:o}={}){let i=n.models||{},s=typeof o=="string"&&o.trim()?o.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,u=n.agent?.[t]?.model||null,S=(typeof r=="string"?r.trim():"")||null;return s||a||l||u||e.model||S||null}function Tt({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 At(n={}){let{state:e={},preferredAgent:t=null}=n,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let i=Z.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}T.debug(`[workflow] agent selection: requested=${r}`);let o=Z.find(i=>i.getName()===r);if(!o){let i=Z.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!o.canHandle(n))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return T.debug(`[workflow] using agent: ${o.getName()}`),o}async function Nn(n,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},o={...e,state:r},i=At(o),s=r.config||t.config||{},a=r._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",u=!l||l===i.name?a.model:null,S=It({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:u}),d={...t,model:S,...Tt({options:t,stateView:r,context:e}),config:s},c=n,y=d.skills||[];if(y.length>0&&!t.skipPromptFragments){let v=t.connectedIntegrations;if(!v){let m=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof m=="string"&&m.trim()!==""){v={};for(let g of m.split(",").map(h=>h.trim()).filter(Boolean))v[g]=!0}}let $=m=>{let g=m&&m.requiresIntegration;return!g||!v?!0:(Array.isArray(g)?g:[g]).some(w=>v[w]===!0)},f=i.name==="assistant",I=m=>m?.inProcessOnly!==!0||f,A=y.map(m=>{let g=ie(m);if(!$(g)||!I(g))return null;let h=g?.promptFragment;return typeof h=="function"?h():h}).filter(Boolean);A.length>0&&(c+=`
1
+ var dn=Object.defineProperty;var Oe=(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 he=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var it=(n,e)=>{for(var t in e)dn(n,t,{get:e[t],enumerable:!0})};var at,fn,Ne,ye,T,J=he(()=>{at=()=>{},fn={debug:at,info:at,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},Ne=Symbol.for("@zibby/agent-workflow.logger");globalThis[Ne]||(globalThis[Ne]={impl:fn});ye=globalThis[Ne],T={debug:(...n)=>ye.impl.debug?.(...n),info:(...n)=>ye.impl.info?.(...n),warn:(...n)=>ye.impl.warn?.(...n),error:(...n)=>ye.impl.error?.(...n)}});var Et=he(()=>{});var It={};it(It,{clearSkills:()=>kn,getAllSkills:()=>xn,getSkill:()=>ie,getSkillSource:()=>$n,hasSkill:()=>vn,listSkillIds:()=>On,registerSkill:()=>An});function An(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:r=!1}=e,o=n.id;if(Y.has(o)&&!r){let i=se.get(o);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${o}" is already registered by ${a}; ${l} 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).`)}}Y.set(o,Object.freeze({...n})),t===void 0?se.delete(o):se.set(o,t)}function ie(n){return Y.get(n)||null}function vn(n){return Y.has(n)}function $n(n){return se.get(n)||null}function xn(){return new Map(Y)}function On(){return Array.from(Y.keys())}function kn(){Y.clear(),se.clear()}var Ue,je,Y,se,we=he(()=>{Ue=Symbol.for("@zibby/agent-workflow.skills"),je=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Ue]||(globalThis[Ue]=new Map);globalThis[je]||(globalThis[je]=new Map);Y=globalThis[Ue],se=globalThis[je]});var ae={};it(ae,{EFFORT_LEVELS:()=>Fe,getAgentStrategy:()=>$t,invokeAgent:()=>Mn,listStrategies:()=>Rn,registerStrategy:()=>Nn,resolveInvocationEffort:()=>At,resolveInvocationExtras:()=>vt,resolveInvocationModel:()=>Tt});function Nn(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=Z.findIndex(t=>t.getName()===n.getName());e>=0?Z[e]=n:Z.push(n)}function Rn(){return Z.map(n=>n.getName())}function Tt({config:n={},options:e={},strategyName:t,envModel:r,nodeConfigModel:o}={}){let i=n.models||{},s=typeof o=="string"&&o.trim()?o.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,u=n.agent?.[t]?.model||null,S=(typeof r=="string"?r.trim():"")||null;return s||a||l||u||e.model||S||null}function At({options:n={},envEffort:e,nodeConfigEffort:t}={}){let r=[t,n.effort,e].map(o=>typeof o=="string"?o.trim().toLowerCase():"").find(Boolean);return r?Fe.indexOf(r)===-1?(T.warn(`[workflow] ignoring unknown effort "${r}" \u2014 expected one of ${Fe.join(", ")}`),null):r:null}function vt({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 $t(n={}){let{state:e={},preferredAgent:t=null}=n,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let i=Z.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}T.debug(`[workflow] agent selection: requested=${r}`);let o=Z.find(i=>i.getName()===r);if(!o){let i=Z.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!o.canHandle(n))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return T.debug(`[workflow] using agent: ${o.getName()}`),o}async function Mn(n,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},o={...e,state:r},i=$t(o),s=r.config||t.config||{},a=r._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",u=!l||l===i.name?a.model:null,S=Tt({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:u}),p=!l||l===i.name?a.effort:null,c=At({options:t,envEffort:process.env.EFFORT,nodeConfigEffort:p}),m={...t,model:S,...c?{effort:c}:{},...vt({options:t,stateView:r,context:e}),config:s},d=n,b=m.skills||[];if(b.length>0&&!t.skipPromptFragments){let f=t.connectedIntegrations;if(!f){let h=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof h=="string"&&h.trim()!==""){f={};for(let g of h.split(",").map(x=>x.trim()).filter(Boolean))f[g]=!0}}let A=h=>{let g=h&&h.requiresIntegration;return!g||!f?!0:(Array.isArray(g)?g:[g]).some(P=>f[P]===!0)},E=i.name==="assistant",w=h=>h?.inProcessOnly!==!0||E,y=b.map(h=>{let g=ie(h);if(!A(g)||!w(g))return null;let x=g?.promptFragment;return typeof x=="function"?x():x}).filter(Boolean);y.length>0&&(d+=`
2
2
 
3
- ${A.join(`
3
+ ${y.join(`
4
4
 
5
- `)}`)}let p=r._currentNodeConfig?.stores;if(Array.isArray(p)&&p.length>0&&typeof p[0]=="object"){let v=p.length<=8,$=p.map(f=>{let I=f?.id??f?.storeId??"",A=(f?.name??"").toString().trim()||I,m=f?.type?` \xB7 ${f.type}`:"",g=(f?.description||"").toString().replace(/\s+/g," ").trim(),h=`- ${A} \xB7 ${g||"(no description)"}${m} (id: ${I})`;if(v&&f?.schema&&typeof f.schema=="object"){let w=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);w.length&&(h+=`
6
- fields: ${w.join(", ")}`)}return h});c+=`
5
+ `)}`)}let $=r._currentNodeConfig?.stores;if(Array.isArray($)&&$.length>0&&typeof $[0]=="object"){let f=$.length<=8,A=$.map(E=>{let w=E?.id??E?.storeId??"",y=(E?.name??"").toString().trim()||w,h=E?.type?` \xB7 ${E.type}`:"",g=(E?.description||"").toString().replace(/\s+/g," ").trim(),x=`- ${y} \xB7 ${g||"(no description)"}${h} (id: ${w})`;if(f&&E?.schema&&typeof E.schema=="object"){let P=E.schema.properties&&typeof E.schema.properties=="object"?Object.keys(E.schema.properties):Object.keys(E.schema);P.length&&(x+=`
6
+ fields: ${P.join(", ")}`)}return x});d+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
9
- ${$.join(`
10
- `)}`}let b=r._currentNodeConfig?.extraPromptInstructions?.trim();return b&&(c+=`
9
+ ${A.join(`
10
+ `)}`}let v=r._currentNodeConfig?.extraPromptInstructions?.trim();return v&&(d+=`
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
- ${b}
17
- `),T.debug(`[workflow] prompt length: ${c.length} chars`),i.invoke(c,d)}var Le,Z,ce=he(()=>{bt();J();we();Le=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Le]||(globalThis[Le]=[]);Z=globalThis[Le]});var un=new Set(["__proto__","constructor","prototype"]);function ke(n){if(un.has(n))throw new Error(`Invalid state key: "${n}"`)}var ge=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){ke(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)ke(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){ke(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 q from"handlebars";var me=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(o=>o[0]);for(let o of r)try{return this.validate(JSON.parse(o))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,o]of Object.entries(this.schema)){if(o.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&o.type){let i=typeof e[r];i!==o.type&&t.push(`Field '${r}' expected ${o.type}, got ${i}`)}if(o.validate&&r in e){let i=o.validate(e[r]);i&&t.push(`Field '${r}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
16
+ ${v}
17
+ `),T.debug(`[workflow] prompt length: ${d.length} chars`),i.invoke(d,m)}var Le,Z,Fe,ce=he(()=>{Et();J();we();Le=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Le]||(globalThis[Le]=[]);Z=globalThis[Le];Fe=["low","medium","high","xhigh","max"]});var pn=new Set(["__proto__","constructor","prototype"]);function ke(n){if(pn.has(n))throw new Error(`Invalid state key: "${n}"`)}var ge=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){ke(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)ke(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){ke(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 q from"handlebars";var me=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(o=>o[0]);for(let o of r)try{return this.validate(JSON.parse(o))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,o]of Object.entries(this.schema)){if(o.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&o.type){let i=typeof e[r];i!==o.type&&t.push(`Field '${r}' expected ${o.type}, got ${i}`)}if(o.validate&&r in e){let i=o.validate(e[r]);i&&t.push(`Field '${r}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
18
18
  ${t.join(`
19
- `)}`);return e}};J();import{writeFileSync as Fe,readFileSync as vt,existsSync as $t,mkdirSync as Mn}from"node:fs";import{join as Ge,dirname as Rn}from"node:path";import N from"chalk";var pn="__WORKFLOW_GRAPH_LOG__",oe=N.gray("\u2502"),fn=N.gray("\u250C"),at=N.gray("\u2514"),Me=N.green("\u25C6"),ct=N.hex("#c084fc")("\u25C6"),lt=N.hex("#2dd4bf")("\u25C6"),Re=N.red("\u25C6"),ut=`${oe} `,dt=2;function pt(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function ft(n,e){return(t,r,o)=>{if(typeof t!="string")return n(t,r,o);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(s+=ut,e.col=dt,e.lineStart=!1),l===`
19
+ `)}`);return e}};J();import{writeFileSync as Ge,readFileSync as xt,existsSync as Ot,mkdirSync as Pn}from"node:fs";import{join as We,dirname as Cn}from"node:path";import N from"chalk";var hn="__WORKFLOW_GRAPH_LOG__",oe=N.gray("\u2502"),gn=N.gray("\u250C"),ct=N.gray("\u2514"),Re=N.green("\u25C6"),lt=N.hex("#c084fc")("\u25C6"),ut=N.hex("#2dd4bf")("\u25C6"),Me=N.red("\u25C6"),dt=`${oe} `,pt=2;function ft(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function ht(n,e){return(t,r,o)=>{if(typeof t!="string")return n(t,r,o);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(s+=dt,e.col=pt,e.lineStart=!1),l===`
20
20
  `?(s+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,s+=l):e.inEsc?(s+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,s+=l,e.col>=i&&(s+=`
21
- ${ut}`,e.col=dt))}return n(s,r,o)}}var Pe=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=ft(this._origStdoutWrite,e),process.stderr.write=ft(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
21
+ ${dt}`,e.col=pt))}return n(s,r,o)}}var Pe=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=ht(this._origStdoutWrite,e),process.stderr.write=ht(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
- `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${pn}${JSON.stringify(e)}
24
+ `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${hn}${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(Me,e):process.stdout.write.bind(process.stdout)(`${oe} ${Me} ${e}
29
- `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(ct,e):process.stdout.write.bind(process.stdout)(`${oe} ${ct} ${e}
30
- `)}stepMemory(e){let t=N.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(lt,t):process.stdout.write.bind(process.stdout)(`${oe} ${lt} ${t}
31
- `)}stepFail(e){this._origStdoutWrite?this._writeDot(Re,N.red(e)):process.stdout.write.bind(process.stdout)(`${oe} ${Re} ${N.red(e)}
32
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${fn} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:o}=t;if(o)for(let s of o)this._rawWrite(`${Me} ${s}`);let i=r?N.dim(` ${pt(r)}`):"";this._rawWrite(`${at} ${N.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:o}=r,i=o?N.dim(` ${pt(o)}`):"";this._rawWrite(`${Re} ${N.red(t)}`),this._rawWrite(`${at} ${N.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(N.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},R=new Pe;var Se=".zibby/output",ht="sessions",ee=".session-info.json",gt=".zibby-stop";var kr=Object.freeze(["codebase-memory","code-scan","artifact"]),mt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var hn=Object.freeze({authentication_failed:"deterministic",oauth_org_not_allowed:"deterministic",billing_error:"deterministic",invalid_request:"deterministic",max_output_tokens:"deterministic",rate_limit:"transient",server_error:"transient",unknown:"inconclusive"}),gn=Object.freeze([/stream idle timeout/i,/partial response received/i,/no chunks received/i,/stream ended without receiving any events/i,/stream completed without receiving/i,/socket hang up/i,/premature close/i,/\b(?:ECONNRESET|ECONNABORTED|ECONNREFUSED|EPIPE|ETIMEDOUT|EAI_AGAIN|ENETUNREACH|ENETRESET|EHOSTUNREACH)\b/,/\bfetch failed\b/i,/\bnetwork (?:error|timeout)\b/i,/request timed out/i,/\brequest timeout\b/i,/\boverloaded(?:_error)?\b/i,/\brate[_ ]limit(?:_error|ed)?\b/i,/\b(?:HTTP|http_status|status(?:\s*code)?)[:= ]\s*(?:429|5\d\d)\b/i,/\b(?:429|500|502|503|504|529)\s+(?:too many requests|internal server error|bad gateway|service unavailable|gateway time-?out|overloaded)\b/i]),mn=Object.freeze([/\bAbortError\b/,/\bAPIUserAbortError\b/,/\boperation was aborted\b/i,/\bcanceled by parent abort\b/i,/\bstopped by operator\b/i]),wt=/provider error \[([a-z_]+)(?:\s+http\s+(\d{3}))?\]/i;function Be(n){if(n==null)return"";if(typeof n=="string")return n;if(typeof n!="object")return String(n);let e=n;return[e.message,e.name,e.code,e.providerErrorText,e.cause?.message??(typeof e.cause=="string"?e.cause:void 0),e.cause?.code].filter(r=>typeof r=="string"||typeof r=="number").join(" | ")}function yn(n){if(n&&typeof n=="object"){let t=n.providerErrorKind;if(typeof t=="string"&&t.trim())return t.trim()}let e=wt.exec(Be(n));return e?e[1].toLowerCase():null}function Sn(n){if(n&&typeof n=="object"){let r=Number(n.providerErrorStatus);if(Number.isInteger(r)&&r>=100&&r<=599)return r}let e=wt.exec(Be(n)),t=e&&e[2]?Number(e[2]):NaN;return Number.isInteger(t)?t:null}function wn(n){let e=Be(n);if(!e)return"deterministic";for(let o of mn)if(o.test(e))return"deterministic";let t=yn(n);if(t){let o=hn[t];if(o==="transient"||o==="deterministic")return o}let r=Sn(n);if(r===429||r>=500&&r<=599)return"transient";for(let o of gn)if(o.test(e))return"transient";return"deterministic"}var yt=2,_n=5;function bn(n=process.env){let e=n?.AGENT_TRANSIENT_RETRIES;if(e==null||String(e).trim()==="")return yt;let t=Number(e);return!Number.isFinite(t)||t<0?yt:Math.min(_n,Math.floor(t))}var Ce=5e3,_t=3e4;function En(n=process.env){let e=n?.AGENT_TRANSIENT_BACKOFF_MS;if(e==null||String(e).trim()==="")return Ce;let t=Number(e);return!Number.isFinite(t)||t<0?Ce:Math.min(_t,Math.floor(t))}function St(n,e=Math.random,t=Ce){if(!(t>0))return 0;let r=Math.max(1,Math.floor(Number(n)||1)),o=Math.min(_t,t*2**(r-1)),i=1+(e()-.5)*.4;return Math.max(1,Math.round(o*i))}function De(n,{env:e=process.env,rand:t=Math.random}={}){let r=Math.max(0,Math.floor(Number(n)||0)),o=bn(e),i=En(e),s=0,a=0;return{get attemptsMade(){return 1+s+a},get transientUsed(){return a},get transientMax(){return o},next(l){let u=wn(l);return s<r?(s+=1,{retry:!0,paidBy:"declared",delayMs:u==="transient"?St(s,t,i):0,failureClass:u,index:s,of:r}):u==="transient"&&a<o?(a+=1,{retry:!0,paidBy:"transient",delayMs:St(a,t,i),failureClass:u,index:a,of:o}):{retry:!1,delayMs:0,failureClass:u}}}}async function xt(n,e,t,r){if(!e.retry)return!1;if(r())return T.info(`[workflow] node '${n}': run aborted \u2014 not retrying`),!1;let o=t?.message??String(t??"");return e.paidBy==="transient"?T.warn(`[workflow] node '${n}': TRANSIENT provider failure \u2014 ${o}. Retrying in ${Math.round(e.delayMs/1e3)}s (transient retry ${e.index}/${e.of}; the workspace is untouched, so files this node already wrote survive into the retry).`):T.info(`[workflow] node '${n}' failed (${e.failureClass}), retrying (${e.index}/${e.of})\u2026`),e.delayMs>0&&(await new Promise(i=>setTimeout(i,e.delayMs)),r())?(T.info(`[workflow] node '${n}': run aborted during backoff \u2014 not retrying`),!1):!0}q.helpers.inc||q.registerHelper("inc",n=>Number(n)+1);q.helpers.json||q.registerHelper("json",n=>JSON.stringify(n,null,2));q.helpers.eq||q.registerHelper("eq",(n,e)=>n===e);var W=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 me(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 T.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,o=y=>t&&typeof t.get=="function"?t.get(y):e?.[y],i=()=>o("_signal")?.aborted===!0;if(typeof this.customExecute=="function"){T.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let y=De(this.retries),p=null,b=null;for(;;){try{let f=await this.customExecute(e);if(typeof f=="object"&&f!==null&&f.success===!1)b=null,p={success:!1,error:f.error||`node '${this.name}' returned { success: false } with no \`error\` field. On a custom-code node \`success\` is RESERVED: the engine reads it as "this node failed" and stops the graph. If it was meant as a DOMAIN fact (no diff to commit, a PR deliberately skipped), give that fact its own field name and return the outcome \u2014 or set \`error\` to say what actually failed.`,raw:f.raw||null};else return this.isZodSchema?(T.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(f),raw:null}):{success:!0,output:f,raw:null}}catch(f){T.error(`[workflow] node '${this.name}' failed: ${f.message}`),f.name==="ZodError"&&T.error(`Schema errors: ${JSON.stringify(f.issues||f.errors,null,2)}`),b=f,p={success:!1,error:f.message,raw:null}}let v=b??p?.error,$=y.next(v);if(!await xt(this.name,$,v,i))break}return p&&(p.attempts=y.attemptsMade),p}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=q.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let a=o("_skillHints");a&&(s=`${a}
28
+ `)}step(e){this._origStdoutWrite?this._writeDot(Re,e):process.stdout.write.bind(process.stdout)(`${oe} ${Re} ${e}
29
+ `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(lt,e):process.stdout.write.bind(process.stdout)(`${oe} ${lt} ${e}
30
+ `)}stepMemory(e){let t=N.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(ut,t):process.stdout.write.bind(process.stdout)(`${oe} ${ut} ${t}
31
+ `)}stepFail(e){this._origStdoutWrite?this._writeDot(Me,N.red(e)):process.stdout.write.bind(process.stdout)(`${oe} ${Me} ${N.red(e)}
32
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${gn} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:o}=t;if(o)for(let s of o)this._rawWrite(`${Re} ${s}`);let i=r?N.dim(` ${ft(r)}`):"";this._rawWrite(`${ct} ${N.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:o}=r,i=o?N.dim(` ${ft(o)}`):"";this._rawWrite(`${Me} ${N.red(t)}`),this._rawWrite(`${ct} ${N.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(N.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},M=new Pe;var Se=".zibby/output",gt="sessions",ee=".session-info.json",mt=".zibby-stop";var Rr=Object.freeze(["codebase-memory","code-scan","artifact"]),yt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var mn=Object.freeze({authentication_failed:"deterministic",oauth_org_not_allowed:"deterministic",billing_error:"deterministic",invalid_request:"deterministic",max_output_tokens:"deterministic",rate_limit:"transient",server_error:"transient",unknown:"inconclusive"}),yn=Object.freeze([/stream idle timeout/i,/partial response received/i,/no chunks received/i,/stream ended without receiving any events/i,/stream completed without receiving/i,/socket hang up/i,/premature close/i,/\b(?:ECONNRESET|ECONNABORTED|ECONNREFUSED|EPIPE|ETIMEDOUT|EAI_AGAIN|ENETUNREACH|ENETRESET|EHOSTUNREACH)\b/,/\bfetch failed\b/i,/\bnetwork (?:error|timeout)\b/i,/request timed out/i,/\brequest timeout\b/i,/\boverloaded(?:_error)?\b/i,/\brate[_ ]limit(?:_error|ed)?\b/i,/\b(?:HTTP|http_status|status(?:\s*code)?)[:= ]\s*(?:429|5\d\d)\b/i,/\b(?:429|500|502|503|504|529)\s+(?:too many requests|internal server error|bad gateway|service unavailable|gateway time-?out|overloaded)\b/i]),Sn=Object.freeze([/\bAbortError\b/,/\bAPIUserAbortError\b/,/\boperation was aborted\b/i,/\bcanceled by parent abort\b/i,/\bstopped by operator\b/i]),_t=/provider error \[([a-z_]+)(?:\s+http\s+(\d{3}))?\]/i;function Be(n){if(n==null)return"";if(typeof n=="string")return n;if(typeof n!="object")return String(n);let e=n;return[e.message,e.name,e.code,e.providerErrorText,e.cause?.message??(typeof e.cause=="string"?e.cause:void 0),e.cause?.code].filter(r=>typeof r=="string"||typeof r=="number").join(" | ")}function wn(n){if(n&&typeof n=="object"){let t=n.providerErrorKind;if(typeof t=="string"&&t.trim())return t.trim()}let e=_t.exec(Be(n));return e?e[1].toLowerCase():null}function _n(n){if(n&&typeof n=="object"){let r=Number(n.providerErrorStatus);if(Number.isInteger(r)&&r>=100&&r<=599)return r}let e=_t.exec(Be(n)),t=e&&e[2]?Number(e[2]):NaN;return Number.isInteger(t)?t:null}function bn(n){let e=Be(n);if(!e)return"deterministic";for(let o of Sn)if(o.test(e))return"deterministic";let t=wn(n);if(t){let o=mn[t];if(o==="transient"||o==="deterministic")return o}let r=_n(n);if(r===429||r>=500&&r<=599)return"transient";for(let o of yn)if(o.test(e))return"transient";return"deterministic"}var St=2,En=5;function In(n=process.env){let e=n?.AGENT_TRANSIENT_RETRIES;if(e==null||String(e).trim()==="")return St;let t=Number(e);return!Number.isFinite(t)||t<0?St:Math.min(En,Math.floor(t))}var Ce=5e3,bt=3e4;function Tn(n=process.env){let e=n?.AGENT_TRANSIENT_BACKOFF_MS;if(e==null||String(e).trim()==="")return Ce;let t=Number(e);return!Number.isFinite(t)||t<0?Ce:Math.min(bt,Math.floor(t))}function wt(n,e=Math.random,t=Ce){if(!(t>0))return 0;let r=Math.max(1,Math.floor(Number(n)||1)),o=Math.min(bt,t*2**(r-1)),i=1+(e()-.5)*.4;return Math.max(1,Math.round(o*i))}function De(n,{env:e=process.env,rand:t=Math.random}={}){let r=Math.max(0,Math.floor(Number(n)||0)),o=In(e),i=Tn(e),s=0,a=0;return{get attemptsMade(){return 1+s+a},get transientUsed(){return a},get transientMax(){return o},next(l){let u=bn(l);return s<r?(s+=1,{retry:!0,paidBy:"declared",delayMs:u==="transient"?wt(s,t,i):0,failureClass:u,index:s,of:r}):u==="transient"&&a<o?(a+=1,{retry:!0,paidBy:"transient",delayMs:wt(a,t,i),failureClass:u,index:a,of:o}):{retry:!1,delayMs:0,failureClass:u}}}}async function kt(n,e,t,r){if(!e.retry)return!1;if(r())return T.info(`[workflow] node '${n}': run aborted \u2014 not retrying`),!1;let o=t?.message??String(t??"");return e.paidBy==="transient"?T.warn(`[workflow] node '${n}': TRANSIENT provider failure \u2014 ${o}. Retrying in ${Math.round(e.delayMs/1e3)}s (transient retry ${e.index}/${e.of}; the workspace is untouched, so files this node already wrote survive into the retry).`):T.info(`[workflow] node '${n}' failed (${e.failureClass}), retrying (${e.index}/${e.of})\u2026`),e.delayMs>0&&(await new Promise(i=>setTimeout(i,e.delayMs)),r())?(T.info(`[workflow] node '${n}': run aborted during backoff \u2014 not retrying`),!1):!0}q.helpers.inc||q.registerHelper("inc",n=>Number(n)+1);q.helpers.json||q.registerHelper("json",n=>JSON.stringify(n,null,2));q.helpers.eq||q.registerHelper("eq",(n,e)=>n===e);var W=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 me(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 T.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,o=m=>t&&typeof t.get=="function"?t.get(m):e?.[m],i=()=>o("_signal")?.aborted===!0;if(typeof this.customExecute=="function"){T.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let m=De(this.retries),d=null,b=null;for(;;){try{let f=await this.customExecute(e);if(typeof f=="object"&&f!==null&&f.success===!1)b=null,d={success:!1,error:f.error||`node '${this.name}' returned { success: false } with no \`error\` field. On a custom-code node \`success\` is RESERVED: the engine reads it as "this node failed" and stops the graph. If it was meant as a DOMAIN fact (no diff to commit, a PR deliberately skipped), give that fact its own field name and return the outcome \u2014 or set \`error\` to say what actually failed.`,raw:f.raw||null};else return this.isZodSchema?(T.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(f),raw:null}):{success:!0,output:f,raw:null}}catch(f){T.error(`[workflow] node '${this.name}' failed: ${f.message}`),f.name==="ZodError"&&T.error(`Schema errors: ${JSON.stringify(f.issues||f.errors,null,2)}`),b=f,d={success:!1,error:f.message,raw:null}}let $=b??d?.error,v=m.next($);if(!await kt(this.name,v,$,i))break}return d&&(d.attempts=m.attemptsMade),d}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=q.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let a=o("_skillHints");a&&(s=`${a}
33
33
 
34
- ${s}`);let l=r(),u=l.cwd||process.cwd(),S=l.sessionPath;try{if(S){let y=Ge(S,ee);if($t(y)){let b=JSON.parse(vt(y,"utf-8"));b.currentNode=this.name,Fe(y,JSON.stringify(b,null,2),"utf-8")}let p=Ge(S,"..",ee);if($t(p))try{let b=JSON.parse(vt(p,"utf-8"));b.currentNode=this.name,Fe(p,JSON.stringify(b,null,2),"utf-8")}catch{}}}catch(y){T.debug(`[workflow] could not update session info: ${y.message}`)}let d=De(this.retries),c=null;for(;;)try{T.debug(`[workflow] node '${this.name}' attempt ${d.attemptsMade-1}`);let y=r().config||{},p=y.agents||{},b=this.config.agent??p[this.name]??null,v={state:r()};b&&(v.preferredAgent=b);let $={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:S,config:y,nodeName:this.name,timeout:this.config?.timeout||3e5},f=e?._coreInvokeAgent;f||(f=(await Promise.resolve().then(()=>(ce(),ae))).invokeAgent);let I=await f(s,v,$),A,m;if(typeof I=="string"?(A=I,m=null):I.structured?(A=I.raw||JSON.stringify(I.structured,null,2),m=I.structured):(A=I.raw||JSON.stringify(I,null,2),m=I.extracted||null),S)try{let g=Ge(S,this.name,"raw_stream_output.txt");Mn(Rn(g),{recursive:!0}),Fe(g,typeof A=="string"?A:JSON.stringify(A),"utf-8")}catch(g){T.debug(`[workflow] could not save raw output: ${g.message}`)}if(this.isZodSchema&&m){T.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let g=m;if(typeof this.onComplete=="function")try{g=await this.onComplete(r(),m)}catch(h){T.warn(`[workflow] onComplete hook failed: ${h.message}`)}return{success:!0,output:g,raw:A}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:A}),raw:A}}catch(g){throw new Error(`onComplete failed: ${g.message}`,{cause:g})}if(this.parser){let g=this.parser.parse(A);return T.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(g,null,2)}`),R.step("Output parsed"),{success:!0,output:g,raw:A}}return{success:!0,output:A,raw:A}}catch(y){c=y;let p=d.next(y);if(!await xt(this.name,p,y,i))break}return{success:!1,error:c.message,raw:null,attempts:d.attemptsMade}}};J();J();import{mkdirSync as Un,existsSync as V,statSync as Ut,readdirSync as jt,rmSync as jn}from"node:fs";import{spawn as Ct}from"node:child_process";import{join as H}from"node:path";import{pathToFileURL as Ln}from"node:url";import{AsyncLocalStorage as Fn}from"node:async_hooks";import{AsyncLocalStorage as Pn}from"node:async_hooks";var le=new Pn;function te(){let n=le.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 Ot(n,e){let t=le.getStore()||te(),r=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 le.run(r,e)}function kt(n,e,t){let r=le.getStore()||te(),o=Object.freeze({...r,agent:n??r.agent??null,signal:e??r.signal??null});return le.run(o,t)}var We=new Map,He=new Map,Nt=new Map;function Mt(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");We.set(n,e),He.set(n,"ready"),Nt.set(n,{...t,cachedAt:Date.now()})}function Rt(n,e){He.set(n,"failed"),Nt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),We.delete(n)}function Pt(n){return He.get(n)==="ready"?We.get(n):null}function ue(n,e,t=process.env){let r=Number(t[n]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):e}function ze(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function de(n,e){return ze(ue(n,e),n)}function U(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}var _e=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Gn(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var M=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"}};function be(n,e,t,r="timeout",o=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${r})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=r,o&&(i.subgraphTransportError=o),i}function Wn(n,e=process.env,t=process.uptime()){let r=Number.isFinite(n)?Number(n):null,o=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,s=Number.isFinite(o)&&o>0?o-i:null;if(r===null&&s===null)return null;let a=r===null?s:s===null?r:Math.min(r,s);return Math.max(1,a)}function Hn(n,e){let t=new AbortController,r=!1,o=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(o=setTimeout(()=>{r=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof o.unref=="function"&&o.unref()),{signal:t.signal,timedOut:()=>r,dispose(){o&&(clearTimeout(o),o=null),n&&n.removeEventListener("abort",i)}}}var Bt=new Fn,Dt=Promise.resolve();async function zn(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 r=Bt.getStore()===!0,o=null;if(!r){let s=Dt;Dt=new Promise(a=>{o=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 T.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await Bt.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;o&&o()}}function Jn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!t||!r||!o)throw new M("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:o}}async function Yn({apiBase:n,authToken:e,body:t}){let r=de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal})}catch(s){throw new M(U(s)?"begin-timeout":"network",U(s)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${s.message}`)}let i=null;try{i=await o.json()}catch(s){if(U(s))throw new M("begin-timeout",`begin body read TIMED OUT ${r.label}`)}if(!o.ok){if(o.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(o.status===429){let s=i?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=s,a}if(o.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new M("begin-status",`begin returned ${o.status}`)}return i?.data||i}async function K({apiBase:n,authToken:e,payload:t}){let r=de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal});o.ok||T.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){T.warn(`[in-process subgraph] finalize ${U(o)?`TIMED OUT ${r.label}`:`failed: ${o.message}`}`)}}async function Zn(n,e){let t=H(e,".ready"),r=H(e,"graph.mjs");if(V(t)&&V(r))return;Un(e,{recursive:!0});let o=H(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),l=s(o,"wx");a(l),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(V(t)&&V(r))return;await new Promise(a=>setTimeout(a,100))}throw new M("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let S=Math.ceil(1e4/1e3),d=Math.ceil(ue("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=Ct("curl",["-fsSL","--connect-timeout",String(S),"--max-time",String(d),n],{stdio:["ignore","pipe","inherit"]}),y=Ct("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(y.stdin);let p,b,v=()=>{if(p!==void 0&&b!==void 0){if(p!==0)return u(new Error(`curl exited ${p}`));if(b!==0)return u(new Error(`tar exited ${b}`));l()}};c.on("close",$=>{p=$,v()}),y.on("close",$=>{b=$,v()}),c.on("error",u),y.on("error",u)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(o)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(o)}catch{}throw new M("bundle-extract-failed",s.message)}}async function qn(n){let e=H(n,"graph.mjs");if(!V(e))throw new M("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(Ln(e).href)}catch(o){throw new M("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=t.default||Object.values(t).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new M("entry-class-missing","no buildGraph() class export found");return r}async function Lt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=te(),r;try{r=Jn()}catch(h){throw h}T.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let o=await Yn({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:S,bundleReady:d,nodeConfigs:c}=o,y=Gn();if(s&&s!==y)throw await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new M("runtime-mismatch",`${y} vs ${s}`);if(!d||!a)throw await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new M("no-bundle","workflow bundle not built yet");let p=Pt(n);if(!p){let h=H(_e,`${S}@${u||"0"}`);try{await Zn(a,h);try{Vn()}catch{}}catch(w){throw w.fallback&&await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:w.message,code:w.reason}}}),w}try{p=await qn(h),Mt(n,p,{workflowUuid:S,version:u,runtimeTag:s,cacheDir:h})}catch(w){throw Rt(n,w),await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:w.message,code:w.reason||"IMPORT_FAILED"}}}),w.fallback?w:new M("import-failed",w.message)}}let b=Date.now(),v=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,$=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...$?{nodeConfigs:c}:{}},I=Wn(e.timeoutMs),A=Hn(e.signal,I),m,g;try{m=await zn(v,async()=>{let w=await(typeof p=="function"&&p.prototype?.buildGraph?new p:p).buildGraph();return Ot({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>w.run(e.parentAgent,f,{signal:A.signal}))}),g=m&&typeof m=="object"&&"state"in m?m.state:m}catch(h){let w=A.timedOut();throw await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:w?"timeout":"failed",error:w?{message:`aborted at the declared ${Math.round(I/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:h.message,code:h.code||"CHILD_THREW",stack:h.stack},durationMs:Date.now()-b}}),w?be(n,i,I):h}finally{A.dispose()}if(m&&typeof m=="object"&&m.stoppedExternally){let h=A.timedOut();if(await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:h?"timeout":"canceled",finalState:g,durationMs:Date.now()-b}}),h)throw be(n,i,I);let w=new Error(`Sub-graph '${n}' canceled by parent abort`);throw w.code="SUBGRAPH_CANCELED",w.subgraphJobId=i,w}return await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:g,durationMs:Date.now()-b}}),{finalState:g,executionId:i}}function Kn(n){let e=0,t=[n];for(;t.length;){let r=t.pop(),o;try{o=Ut(r)}catch{continue}if(o.isDirectory()){let i;try{i=jt(r)}catch{continue}for(let s of i)t.push(H(r,s))}else e+=o.size}return e}function Vn({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!V(_e))return{evicted:0,freedBytes:0};let e=jt(_e),t=[],r=0;for(let a of e){let l=H(_e,a),u;try{u=Ut(l)}catch{continue}let S=u.isDirectory()?Kn(l):u.size;r+=S,t.push({name:a,full:l,size:S,mtimeMs:u.mtimeMs})}if(r<=n)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let o=Math.floor(n*.7),i=0,s=0;for(let a of t){if(r-i<=o)break;if(!V(H(a.full,".lock")))try{jn(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(l){T.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return s>0&&T.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:r-i}}catch(e){return T.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Qn=2e3,er=600*1e3,tr=new Set(["completed","failed","canceled","timeout"]);var nr=()=>de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function rr(n){let e=ue("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return ze(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function or(){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 sr(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function ir(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function ar(){return process.env.EXECUTION_ID||null}function Ft(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],n):n}async function Gt(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=te();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(e.timeoutMs)?e.timeoutMs:er;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{T.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:m}=await Lt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:o}),g=Ft(m,e.output);return T.info(`[sub-graph] '${n}' completed in-process`),g}catch(m){if(m instanceof M||m?.fallback)T.info(`[sub-graph] in-process fallback for '${n}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let i=or(),s=sr(),a=ir(),l=ar(),u=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(n)}/trigger`,S={input:e.input||{},...l?{parentExecutionId:l}:{},...e.conversationId?{conversationId:e.conversationId}:{}};T.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let d=nr(),c;try{c=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(S),signal:d.signal})}catch(m){if(!U(m))throw m;let g=new Error(`Sub-graph '${n}' trigger TIMED OUT ${d.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=m,g}if(!c.ok){let m=null,g="";try{m=await c.json(),g=m?.error||m?.message||JSON.stringify(m)}catch{g=await c.text().catch(()=>"")}if(c.status===429){let w=m?.quotaInfo||{},O=new Error(`Sub-graph '${n}' blocked by execution quota (${w.used??"?"}/${w.limit??"?"} on plan ${w.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw O.code="SUBGRAPH_QUOTA_EXCEEDED",O.status=429,O.subgraph=n,O.quotaInfo=w,O}if(c.status===400){let w=new Error(`Sub-graph '${n}' rejected input: ${g}`);throw w.code="SUBGRAPH_INVALID_INPUT",w.status=400,w.subgraph=n,w.validationErrors=m?.validationErrors||null,w.missing=m?.missing||null,w}let h=new Error(`Sub-graph '${n}' trigger rejected (${c.status}): ${g}`);throw h.code="SUBGRAPH_TRIGGER_FAILED",h.status=c.status,h.subgraph=n,h}let y;try{y=await c.json()}catch(m){if(!U(m))throw m;let g=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${d.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=m,g}let p=y?.data?.jobId||y?.jobId;if(!p)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(y).slice(0,200)}`);if(e.async)return T.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:n};let b=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Qn,v=`${i}/executions/${encodeURIComponent(p)}`,$=Date.now()+o,f="accepted",I=0,A=null;for(;Date.now()<$;){await new Promise(O=>setTimeout(O,b)),I+=1;let m=rr($),g;try{g=await fetch(v,{headers:{Authorization:`Bearer ${a}`},signal:m.signal})}catch(O){A=U(O)?`poll TIMED OUT ${m.label}`:O?.message||String(O),T.warn(`[sub-graph] status poll for ${p} could not reach the API (${A}), will retry`);continue}if(!g.ok){if(g.status>=500){T.warn(`[sub-graph] status poll for ${p} returned ${g.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${g.status}`)}let h;try{h=await g.json()}catch(O){A=U(O)?`poll body read TIMED OUT ${m.label}`:O?.message||String(O),T.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${A}), will retry`);continue}let w=h?.data||h?.execution||h;if(f=w?.status||f,tr.has(f)){if(f!=="completed"){let z=new Error(`Sub-graph '${n}' (${p}) ended in status '${f}'`);throw z.subgraphJobId=p,z.subgraphStatus=f,z}let O=w?.finalState||w?.state||{},G=Ft(O,e.output);return T.info(`[sub-graph] '${n}' (${p}) completed after ${I} polls`),G}}throw be(n,p,o,f,A)}import{existsSync as Wt,readFileSync as cr}from"node:fs";import{join as Je,dirname as Ht}from"node:path";var Ie=class{static async loadContext(e,t,r={}){let o={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Ht(Je(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let S=l.replace(/\.[^.]+$/,"").toLowerCase();o[S]=u}}}let s=r.discovery||{};for(let[a,l]of Object.entries(s))try{let u=Je(t,l);Wt(u)&&(o[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return o}static async findAndMergeContextFiles(e,t,r){let o=[],i=t;for(;i.startsWith(r);){let s=Je(i,e);if(Wt(s))try{o.unshift(await this.loadFile(s))}catch(l){console.warn(`[workflow] could not load ${e} from ${s}: ${l.message}`)}let a=Ht(i);if(a===i)break;i=a}return o.length===0?null:o.every(s=>typeof s=="string")?o.join(`
34
+ ${s}`);let l=r(),u=l.cwd||process.cwd(),S=l.sessionPath;try{if(S){let m=We(S,ee);if(Ot(m)){let b=JSON.parse(xt(m,"utf-8"));b.currentNode=this.name,Ge(m,JSON.stringify(b,null,2),"utf-8")}let d=We(S,"..",ee);if(Ot(d))try{let b=JSON.parse(xt(d,"utf-8"));b.currentNode=this.name,Ge(d,JSON.stringify(b,null,2),"utf-8")}catch{}}}catch(m){T.debug(`[workflow] could not update session info: ${m.message}`)}let p=De(this.retries),c=null;for(;;)try{T.debug(`[workflow] node '${this.name}' attempt ${p.attemptsMade-1}`);let m=r().config||{},d=m.agents||{},b=this.config.agent??d[this.name]??null,$={state:r()};b&&($.preferredAgent=b);let v={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:S,config:m,nodeName:this.name,timeout:this.config?.timeout||3e5},f=e?._coreInvokeAgent;f||(f=(await Promise.resolve().then(()=>(ce(),ae))).invokeAgent);let A=await f(s,$,v),E,w;if(typeof A=="string"?(E=A,w=null):A.structured?(E=A.raw||JSON.stringify(A.structured,null,2),w=A.structured):(E=A.raw||JSON.stringify(A,null,2),w=A.extracted||null),S)try{let y=We(S,this.name,"raw_stream_output.txt");Pn(Cn(y),{recursive:!0}),Ge(y,typeof E=="string"?E:JSON.stringify(E),"utf-8")}catch(y){T.debug(`[workflow] could not save raw output: ${y.message}`)}if(this.isZodSchema&&w){T.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(w,null,2)}`);let y=w;if(typeof this.onComplete=="function")try{y=await this.onComplete(r(),w)}catch(h){T.warn(`[workflow] onComplete hook failed: ${h.message}`)}return{success:!0,output:y,raw:E}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:E}),raw:E}}catch(y){throw new Error(`onComplete failed: ${y.message}`,{cause:y})}if(this.parser){let y=this.parser.parse(E);return T.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(y,null,2)}`),M.step("Output parsed"),{success:!0,output:y,raw:E}}return{success:!0,output:E,raw:E}}catch(m){c=m;let d=p.next(m);if(!await kt(this.name,d,m,i))break}return{success:!1,error:c.message,raw:null,attempts:p.attemptsMade}}};J();J();import{mkdirSync as Ln,existsSync as V,statSync as Lt,readdirSync as Ft,rmSync as Fn}from"node:fs";import{spawn as Dt}from"node:child_process";import{join as H}from"node:path";import{pathToFileURL as Gn}from"node:url";import{AsyncLocalStorage as Wn}from"node:async_hooks";import{AsyncLocalStorage as Bn}from"node:async_hooks";var le=new Bn;function te(){let n=le.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 Nt(n,e){let t=le.getStore()||te(),r=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 le.run(r,e)}function Rt(n,e,t){let r=le.getStore()||te(),o=Object.freeze({...r,agent:n??r.agent??null,signal:e??r.signal??null});return le.run(o,t)}var He=new Map,ze=new Map,Mt=new Map;function Pt(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");He.set(n,e),ze.set(n,"ready"),Mt.set(n,{...t,cachedAt:Date.now()})}function Ct(n,e){ze.set(n,"failed"),Mt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),He.delete(n)}function Bt(n){return ze.get(n)==="ready"?He.get(n):null}function ue(n,e,t=process.env){let r=Number(t[n]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):e}function Je(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function de(n,e){return Je(ue(n,e),n)}function j(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}var _e=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Hn(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var R=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"}};function be(n,e,t,r="timeout",o=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${r})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=r,o&&(i.subgraphTransportError=o),i}function zn(n,e=process.env,t=process.uptime()){let r=Number.isFinite(n)?Number(n):null,o=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,s=Number.isFinite(o)&&o>0?o-i:null;if(r===null&&s===null)return null;let a=r===null?s:s===null?r:Math.min(r,s);return Math.max(1,a)}function Jn(n,e){let t=new AbortController,r=!1,o=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(o=setTimeout(()=>{r=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof o.unref=="function"&&o.unref()),{signal:t.signal,timedOut:()=>r,dispose(){o&&(clearTimeout(o),o=null),n&&n.removeEventListener("abort",i)}}}var Ut=new Wn,jt=Promise.resolve();async function Yn(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 r=Ut.getStore()===!0,o=null;if(!r){let s=jt;jt=new Promise(a=>{o=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 T.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await Ut.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;o&&o()}}function Zn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!t||!r||!o)throw new R("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:o}}async function qn({apiBase:n,authToken:e,body:t}){let r=de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal})}catch(s){throw new R(j(s)?"begin-timeout":"network",j(s)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${s.message}`)}let i=null;try{i=await o.json()}catch(s){if(j(s))throw new R("begin-timeout",`begin body read TIMED OUT ${r.label}`)}if(!o.ok){if(o.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(o.status===429){let s=i?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=s,a}if(o.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new R("begin-status",`begin returned ${o.status}`)}return i?.data||i}async function K({apiBase:n,authToken:e,payload:t}){let r=de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal});o.ok||T.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){T.warn(`[in-process subgraph] finalize ${j(o)?`TIMED OUT ${r.label}`:`failed: ${o.message}`}`)}}async function Kn(n,e){let t=H(e,".ready"),r=H(e,"graph.mjs");if(V(t)&&V(r))return;Ln(e,{recursive:!0});let o=H(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),l=s(o,"wx");a(l),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(V(t)&&V(r))return;await new Promise(a=>setTimeout(a,100))}throw new R("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let S=Math.ceil(1e4/1e3),p=Math.ceil(ue("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=Dt("curl",["-fsSL","--connect-timeout",String(S),"--max-time",String(p),n],{stdio:["ignore","pipe","inherit"]}),m=Dt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(m.stdin);let d,b,$=()=>{if(d!==void 0&&b!==void 0){if(d!==0)return u(new Error(`curl exited ${d}`));if(b!==0)return u(new Error(`tar exited ${b}`));l()}};c.on("close",v=>{d=v,$()}),m.on("close",v=>{b=v,$()}),c.on("error",u),m.on("error",u)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(o)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(o)}catch{}throw new R("bundle-extract-failed",s.message)}}async function Vn(n){let e=H(n,"graph.mjs");if(!V(e))throw new R("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(Gn(e).href)}catch(o){throw new R("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=t.default||Object.values(t).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new R("entry-class-missing","no buildGraph() class export found");return r}async function Gt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=te(),r;try{r=Zn()}catch(h){throw h}T.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let o=await qn({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:S,bundleReady:p,nodeConfigs:c}=o,m=Hn();if(s&&s!==m)throw await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new R("runtime-mismatch",`${m} vs ${s}`);if(!p||!a)throw await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new R("no-bundle","workflow bundle not built yet");let d=Bt(n);if(!d){let h=H(_e,`${S}@${u||"0"}`);try{await Kn(a,h);try{Qn()}catch{}}catch(g){throw g.fallback&&await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:g.message,code:g.reason}}}),g}try{d=await Vn(h),Pt(n,d,{workflowUuid:S,version:u,runtimeTag:s,cacheDir:h})}catch(g){throw Ct(n,g),await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:g.message,code:g.reason||"IMPORT_FAILED"}}}),g.fallback?g:new R("import-failed",g.message)}}let b=Date.now(),$=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,v=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...v?{nodeConfigs:c}:{}},A=zn(e.timeoutMs),E=Jn(e.signal,A),w,y;try{w=await Yn($,async()=>{let g=await(typeof d=="function"&&d.prototype?.buildGraph?new d:d).buildGraph();return Nt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>g.run(e.parentAgent,f,{signal:E.signal}))}),y=w&&typeof w=="object"&&"state"in w?w.state:w}catch(h){let g=E.timedOut();throw await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:g?"timeout":"failed",error:g?{message:`aborted at the declared ${Math.round(A/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:h.message,code:h.code||"CHILD_THREW",stack:h.stack},durationMs:Date.now()-b}}),g?be(n,i,A):h}finally{E.dispose()}if(w&&typeof w=="object"&&w.stoppedExternally){let h=E.timedOut();if(await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:h?"timeout":"canceled",finalState:y,durationMs:Date.now()-b}}),h)throw be(n,i,A);let g=new Error(`Sub-graph '${n}' canceled by parent abort`);throw g.code="SUBGRAPH_CANCELED",g.subgraphJobId=i,g}return await K({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:y,durationMs:Date.now()-b}}),{finalState:y,executionId:i}}function Xn(n){let e=0,t=[n];for(;t.length;){let r=t.pop(),o;try{o=Lt(r)}catch{continue}if(o.isDirectory()){let i;try{i=Ft(r)}catch{continue}for(let s of i)t.push(H(r,s))}else e+=o.size}return e}function Qn({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!V(_e))return{evicted:0,freedBytes:0};let e=Ft(_e),t=[],r=0;for(let a of e){let l=H(_e,a),u;try{u=Lt(l)}catch{continue}let S=u.isDirectory()?Xn(l):u.size;r+=S,t.push({name:a,full:l,size:S,mtimeMs:u.mtimeMs})}if(r<=n)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let o=Math.floor(n*.7),i=0,s=0;for(let a of t){if(r-i<=o)break;if(!V(H(a.full,".lock")))try{Fn(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(l){T.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return s>0&&T.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:r-i}}catch(e){return T.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var tr=2e3,nr=600*1e3,rr=new Set(["completed","failed","canceled","timeout"]);var or=()=>de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function sr(n){let e=ue("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return Je(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function ir(){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 ar(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function cr(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function lr(){return process.env.EXECUTION_ID||null}function Wt(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],n):n}async function Ht(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=te();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(e.timeoutMs)?e.timeoutMs:nr;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{T.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:w}=await Gt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:o}),y=Wt(w,e.output);return T.info(`[sub-graph] '${n}' completed in-process`),y}catch(w){if(w instanceof R||w?.fallback)T.info(`[sub-graph] in-process fallback for '${n}': ${w.reason||"unknown"} \u2014 using HTTP`);else throw w}let i=ir(),s=ar(),a=cr(),l=lr(),u=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(n)}/trigger`,S={input:e.input||{},...l?{parentExecutionId:l}:{},...e.conversationId?{conversationId:e.conversationId}:{}};T.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let p=or(),c;try{c=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(S),signal:p.signal})}catch(w){if(!j(w))throw w;let y=new Error(`Sub-graph '${n}' trigger TIMED OUT ${p.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw y.code="SUBGRAPH_TRIGGER_TIMEOUT",y.subgraph=n,y.timedOut=!0,y.cause=w,y}if(!c.ok){let w=null,y="";try{w=await c.json(),y=w?.error||w?.message||JSON.stringify(w)}catch{y=await c.text().catch(()=>"")}if(c.status===429){let g=w?.quotaInfo||{},x=new Error(`Sub-graph '${n}' blocked by execution quota (${g.used??"?"}/${g.limit??"?"} on plan ${g.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw x.code="SUBGRAPH_QUOTA_EXCEEDED",x.status=429,x.subgraph=n,x.quotaInfo=g,x}if(c.status===400){let g=new Error(`Sub-graph '${n}' rejected input: ${y}`);throw g.code="SUBGRAPH_INVALID_INPUT",g.status=400,g.subgraph=n,g.validationErrors=w?.validationErrors||null,g.missing=w?.missing||null,g}let h=new Error(`Sub-graph '${n}' trigger rejected (${c.status}): ${y}`);throw h.code="SUBGRAPH_TRIGGER_FAILED",h.status=c.status,h.subgraph=n,h}let m;try{m=await c.json()}catch(w){if(!j(w))throw w;let y=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${p.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw y.code="SUBGRAPH_TRIGGER_TIMEOUT",y.subgraph=n,y.timedOut=!0,y.cause=w,y}let d=m?.data?.jobId||m?.jobId;if(!d)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(m).slice(0,200)}`);if(e.async)return T.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${d} (not waiting)`),{jobId:d,status:"accepted",workflow:n};let b=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:tr,$=`${i}/executions/${encodeURIComponent(d)}`,v=Date.now()+o,f="accepted",A=0,E=null;for(;Date.now()<v;){await new Promise(x=>setTimeout(x,b)),A+=1;let w=sr(v),y;try{y=await fetch($,{headers:{Authorization:`Bearer ${a}`},signal:w.signal})}catch(x){E=j(x)?`poll TIMED OUT ${w.label}`:x?.message||String(x),T.warn(`[sub-graph] status poll for ${d} could not reach the API (${E}), will retry`);continue}if(!y.ok){if(y.status>=500){T.warn(`[sub-graph] status poll for ${d} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${d}: ${y.status}`)}let h;try{h=await y.json()}catch(x){E=j(x)?`poll body read TIMED OUT ${w.label}`:x?.message||String(x),T.warn(`[sub-graph] status poll for ${d} returned an unreadable body (${E}), will retry`);continue}let g=h?.data||h?.execution||h;if(f=g?.status||f,rr.has(f)){if(f!=="completed"){let z=new Error(`Sub-graph '${n}' (${d}) ended in status '${f}'`);throw z.subgraphJobId=d,z.subgraphStatus=f,z}let x=g?.finalState||g?.state||{},P=Wt(x,e.output);return T.info(`[sub-graph] '${n}' (${d}) completed after ${A} polls`),P}}throw be(n,d,o,f,E)}import{existsSync as zt,readFileSync as ur}from"node:fs";import{join as Ye,dirname as Jt}from"node:path";var Ie=class{static async loadContext(e,t,r={}){let o={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Jt(Ye(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let S=l.replace(/\.[^.]+$/,"").toLowerCase();o[S]=u}}}let s=r.discovery||{};for(let[a,l]of Object.entries(s))try{let u=Ye(t,l);zt(u)&&(o[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return o}static async findAndMergeContextFiles(e,t,r){let o=[],i=t;for(;i.startsWith(r);){let s=Ye(i,e);if(zt(s))try{o.unshift(await this.loadFile(s))}catch(l){console.warn(`[workflow] could not load ${e} from ${s}: ${l.message}`)}let a=Jt(i);if(a===i)break;i=a}return o.length===0?null:o.every(s=>typeof s=="string")?o.join(`
35
35
 
36
36
  ---
37
37
 
38
- `):o.every(s=>typeof s=="object")?Object.assign({},...o):o[o.length-1]}static async loadFile(e){let t=cr(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),o=await import(r(e).href);return o.default||o}return t}};import{mkdirSync as Yt,existsSync as Ye,writeFileSync as zt,unlinkSync as lr}from"node:fs";import{join as X,resolve as Zt}from"node:path";import{config as ur}from"dotenv";import{zodToJsonSchema as Jt}from"zod-to-json-schema";import{z as Te}from"zod";import dr from"handlebars";function pr({traceFrom:n,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:o}){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=${r} mkdir=${o?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let S=(new Error("session trace").stack||"").split(`
38
+ `):o.every(s=>typeof s=="object")?Object.assign({},...o):o[o.length-1]}static async loadFile(e){let t=ur(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),o=await import(r(e).href);return o.default||o}return t}};import{mkdirSync as qt,existsSync as Ze,writeFileSync as Yt,unlinkSync as dr}from"node:fs";import{join as X,resolve as Kt}from"node:path";import{config as pr}from"dotenv";import{zodToJsonSchema as Zt}from"zod-to-json-schema";import{z as Te}from"zod";import fr from"handlebars";function hr({traceFrom:n,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:o}){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=${r} mkdir=${o?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let S=(new Error("session trace").stack||"").split(`
39
39
  `).slice(2,14).join(`
40
40
  `);console.log(`[zibby:session] stack (${n}):
41
- ${S}`)}}function fr(){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 hr(){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 Zt(String(e).trim())}catch{return String(e).trim()}}function gr(){fr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function mr({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 yr(n={}){let e=mt.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,o=n.paths?.sessionPrefix;return o?`${o}_${r}`:r}function Sr({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let o=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let u=Zt(String(process.env.ZIBBY_SESSION_PATH));u&&(o=u,s="ZIBBY_SESSION_PATH")}catch{}let a;if(o)a=String(o).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,s="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,s="config.sessionId"):(a=yr(e),s="generated")}i=i??Date.now();let S=e.paths?.output||Se;o=X(n,S,ht,a)}let l=!Ye(o);return l&&Yt(o,{recursive:!0}),(l||s!=="initialState.sessionPath")&&pr({traceFrom:r,sessionId:a,sessionPath:o,idSource:s,mkdirFresh:l}),mr({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var Ae=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,r={}){if(!(t instanceof W)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async u=>{let S=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof s.input=="function"?d=s.input(S):s.input&&typeof s.input=="object"?d=s.input:d={},Gt(s.workflow,{input:d,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(S):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:S?._signal,parentAgent:u?.agent})}},l=new W(a);return l.name=e,this.nodes.set(e,l),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let o=!(t instanceof W)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof W?t:new W(o?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){let r=this.edges.get(e);return r===void 0?this.edges.set(e,t):typeof r=="string"?r!==t&&this.edges.set(e,[r,t]):Array.isArray(r)?r.includes(t)||r.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:r}={}){let o=this.edges.get(e);return o!==void 0&&!o.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(o)?o.join(", "):o}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_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,r=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&&r(s)}t.set(i,2)};this.entryPoint&&r(this.entryPoint);let o=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||o.set(s,(o.get(s)||0)+1);return{backEdges:e,joinDegree:o}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,o,i){let s=r;for(let a=e.length-1;a>=0;a--){let l=e[a],u=s;s=()=>l(t,u,o,i)}return s()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let y=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:y,data:{nodeType:y,label:d}});let p={};c._isCustomCode&&typeof c.execute=="function"&&(p.customCode=c.execute.toString());let b=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;b&&(p.description=b);let v=this.nodePrompts.get(d);if(v)p.prompt=v;else if(typeof c.prompt=="function")try{let h=c.prompt({});typeof h=="string"&&h.trim()&&(p.prompt=h,p.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(p.executeCode=c.customExecute.toString());let $=c?.config?.dispatchesWorkflow;if(typeof $=="string"&&$.trim())p.dispatchesWorkflow=$.trim();else if(Array.isArray($)){let h=[...new Set($.filter(w=>typeof w=="string").map(w=>w.trim()).filter(Boolean))];h.length&&(p.dispatchesWorkflow=h)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(p.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let h=null;if(typeof Te?.toJSONSchema=="function")try{h=Te.toJSONSchema(c.outputSchema)}catch{}if(!h)try{h=Jt(c.outputSchema,{target:"openApi3"})}catch{}p.outputSchema=h?{jsonSchema:h,variables:this._flattenJsonSchemaToVariables(h)}:{schema:c.outputSchema}}else p.outputSchema={schema:c.outputSchema};let f=(this.resolvedToolsMap||{})[d];f?.toolIds&&(p.tools=f.toolIds);let I=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;I&&I.length>0&&(p.skills=[...I]);let A=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;A&&A.length>0&&(p.plugins=A.map(h=>h&&typeof h=="object"?{...h}:h));let m=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;m&&m.length>0&&(p.stores=m.map(h=>h&&typeof h=="object"?{...h}:h));let g=Array.isArray(c?.config?.uses)?c.config.uses:typeof c?.config?.uses=="string"?[c.config.uses]:Array.isArray(c?.uses)?c.uses:typeof c?.uses=="string"?[c.uses]:null;if(g&&g.length>0){let h=new Set,w=[];for(let O of g){let G=typeof O=="string"?O.trim():"";!G||h.has(G)||(h.add(G),w.push(G))}w.length>0&&(p.uses=w)}Object.keys(p).length>0&&(t[d]=p)}let r=[];for(let[d,c]of this.edges)if(typeof c=="string")r.push({source:d,target:c});else if(Array.isArray(c))for(let y of c)r.push({source:d,target:y});else if(c.conditional){let y=this.conditionalCodeMap.get(d)||c.routes.toString(),p=this._inferConditionalTargets(c.routes,c.labels),b=c.labels||{},v=this.nodes.get(d),$=v?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!v,f=d;if(!$){let I=`${d}__branch`;e.push({id:I,type:"decision",data:{nodeType:"decision",label:I}}),r.push({source:d,target:I}),f=I}for(let I of p){let A={source:f,target:I,data:{conditionalCode:y}};b[I]&&(A.label=b[I]),r.push(A)}}let o=d=>{if(!d)return null;if(typeof Te?.toJSONSchema=="function")try{return Te.toJSONSchema(d)}catch{}try{return Jt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of r)if(d.target==="END"){i+=1;let c=`END__${i}`;d.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:d,target:c})}let s=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=o(a||this.stateSchema),u=o(this.inputSchema),S=o(this.contextSchema);return{nodes:s,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:S}}_topoOrderNodes(e,t){let r=new Map(e.map((d,c)=>[d.id,c])),o=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),s=new Map(e.map(d=>[d.id,[]]));for(let d of t)s.has(d.source)&&i.has(d.target)&&(s.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(r.keys()),u=[...l].filter(d=>i.get(d)===0),S=[];for(;S.length<e.length;){let d;if(u.length>0){if(u.sort((c,y)=>r.get(c)-r.get(y)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,y)=>r.get(c)-r.get(y))[0];a.add(d),l.delete(d),S.push(o.get(d));for(let c of s.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return S}_inferConditionalTargets(e,t){let r=e.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(r))!==null;){let u=s[2]!==void 0?s[2]:s[3];u!==void 0&&u!==""&&o.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of o)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,S;for(;(S=u.exec(r))!==null;)l.add(S[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let o=e.$ref.replace("#/definitions/","");r=e.definitions[o]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],o=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(o)){let l=t?`${t}.${s}`:s;r.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${l}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[o,i]of Object.entries(t))if(!(o==="success"||o==="raw"||o==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${o}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);r.push(l?`${o}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${o}: ${s} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){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(E){let _=new Error(`agent.normalizeInput() rejected the trigger input: ${E?.message||E}`);throw _.cause=E,_.code=E?.code||"NORMALIZE_INPUT_FAILED",_}let o=new AbortController;r.signal&&(r.signal.aborted?o.abort():r.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();ur({path:X(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let E=X(s,".zibby.config.js");Ye(E)&&(a=(await import(E)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let E=a?.agent;E?.provider?l=E.provider:E?.gemini?l="gemini":E?.claude?l="claude":E?.cursor?l="cursor":E?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},S=this._runtimeSchema();if(S){let E=S.safeParse(t);if(!E.success){let _=E.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),_.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${_.join(", ")}`)}R.step("State validated against schema")}let d=hr(),c=t.sessionPath||d;c||gr();let{sessionPath:y,sessionTimestamp:p,sessionId:b}=Sr({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});R.step(`Session ${b}`);let v=await Ie.loadContext(t.specPath||"",s,u);Object.keys(v).length>0&&R.step(`Context loaded: ${Object.keys(v).join(", ")}`);let $=t.outputPath;!$&&t.specPath&&(e?.calculateOutputPath?$=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ge({...t,config:a,agentType:l,outputPath:$,sessionPath:y,sessionTimestamp:p,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),I=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:A}=await Promise.resolve().then(()=>(we(),Et)),m=a.skills&&typeof a.skills=="object"?a.skills:{},g=Object.values(m).filter(E=>E&&typeof E=="object"&&typeof E.id=="string"),h=E=>{for(let _ of g)if(_.id===E)return _;return A(E)},w=new Set;for(let[,E]of this.nodes)for(let _ of E.config?.skills||[])w.add(_);for(let E of w){let _=h(E);if(typeof _?.middleware=="function")try{let C=await _.middleware();typeof C=="function"&&I.set(E,C)}catch{}}let{backEdges:O,joinDegree:G}=this._analyzeFlow(),z=new Map,ne=[],$e=(E,_,C)=>{if(!E||E==="END")return;let L=G.get(E)||0;if(C&&L>1&&!O.has(`${_}->${E}`)){let re=(z.get(E)||0)+1;if(re<L){z.set(E,re);return}z.set(E,0)}ne.includes(E)||ne.push(E)};this.entryPoint&&ne.push(this.entryPoint);let pe=[],Ve=a?.recursionLimit??100,Qt=0;try{for(;ne.length>0;){let _=ne.pop();if(!_||_==="END")continue;if(++Qt>Ve)throw new Error(`Workflow exceeded recursion limit (${Ve}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let C=X(y,gt);if(Ye(C)){try{lr(C)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
42
- \u{1F6D1} External stop requested \u2014 ending workflow.`),R.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:pe,stoppedExternally:!0};let L=this.nodes.get(_);if(!L)throw new Error(`Node '${_}' not found in graph`);let re=JSON.stringify({sessionPath:y,sessionTimestamp:p,currentNode:_,createdAt:new Date().toISOString(),config:f.get("config")}),en=X(y,ee);zt(en,re,"utf-8");let Xe=f.get("config")?.paths?.output||Se,tn=X(s,Xe,ee);Yt(X(s,Xe),{recursive:!0});try{zt(tn,re,"utf-8")}catch{}let Qe=t.onPipelineProgress;if(typeof Qe=="function")try{Qe({cwd:s,sessionPath:y,sessionId:b,outputBase:f.get("config")?.paths?.output||Se,currentNode:_})}catch{}let nn=(this.resolvedToolsMap||{})[_]||null;f.set("_currentNodeTools",nn);let rn=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",rn[_]||{}),R.nodeStart(_);let et=Date.now(),fe=this.nodePrompts.get(_);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(ce(),ae));this._invokeAgent=k.invokeAgent}let on=this._invokeAgent,xe={},sn=L.config?.skills||[];for(let k of sn){let P=h(k);if(typeof P?.invokeAgentOptions=="function")try{let x=P.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:_});x&&typeof x=="object"&&(xe={...xe,...x})}catch(x){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${x.message}`)}}let tt=async(k,P,x={})=>{let B=on(k,P,{...xe,...x,signal:o.signal});return B.catch(()=>{}),o.signal.aborted?B:Promise.race([B,new Promise((Q,F)=>{let D=()=>{setTimeout(()=>{let ot=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);ot.name="AbortError",F(ot)},i)};o.signal.addEventListener("abort",D,{once:!0})})])},an=async(k={},P={})=>{let x=P.prompt||"";if(fe){let B=this._compiledPrompts.get(_);B||(B=dr.compile(fe,{noEscape:!0}),this._compiledPrompts.set(_,B));try{x=B(k)}catch(Q){throw console.error(`\u274C Template rendering failed for node '${_}':`,Q.message),new Error(`Template rendering failed: ${Q.message}`,{cause:Q})}}else if(!x)throw new Error(`No prompt template configured for node '${_}' and no prompt provided in options`);return tt(x,{state:f.getAll(),images:P.images||[]},{model:P.model||f.get("model"),workspace:f.get("workspace"),schema:P.schema,...P,signal:o.signal,nodeName:_})},nt=f.getAll(),cn=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of cn)Object.prototype.hasOwnProperty.call(nt,k)&&console.warn(`[workflow] node "${_}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let rt={...nt,state:f,invokeAgent:an,_coreInvokeAgent:tt,agent:e,nodeId:_,promptTemplate:fe,getPromptTemplate:()=>fe};try{let k=(L.config?.skills||[]).map(D=>I.get(D)).filter(Boolean),P=[...this.middleware,...k],x;x=await kt(e,o.signal,async()=>P.length>0?this._composeMiddleware(P,_,async()=>L.execute(rt,f),f.getAll(),f):L.execute(rt,f));let B=Date.now()-et;if(pe.push({node:_,success:x.success,duration:B,timestamp:new Date().toISOString()}),!x.success){if(o.signal.aborted)return R.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:pe,stoppedExternally:!0};f.append("errors",{node:_,error:x.error});let D=Number.isInteger(x.attempts)&&x.attempts>0?x.attempts:(L.config?.retries||0)+1;throw R.nodeFailed(_,x.error,{duration:B}),new Error(`Node '${_}' failed after ${D} attempt(s): ${x.error}`)}f.update({[_]:x.output});let Q=this._summarizeNodeOutput(_,x.output);R.nodeComplete(_,{duration:B,details:Q});let F=this.edges.get(_);if(F)if(F.conditional){let D=F.routes(f.getAll());R.route(_,D),$e(D,_,!1)}else if(Array.isArray(F))for(let D=F.length-1;D>=0;D--)$e(F[D],_,!0);else $e(F,_,!0)}catch(k){throw R.isInsideNode&&R.nodeFailed(_,k.message,{duration:Date.now()-et}),f.set("failed",!0),f.set("failedAt",_),k}}R.graphComplete();let E={success:!0,state:f.getAll(),executionLog:pe};return e&&typeof e.onComplete=="function"&&await e.onComplete(E),E}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(E){console.warn(`[workflow] agent.cleanup() failed: ${E.message}`)}}}};var Ze=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Ze]||(globalThis[Ze]=new Map);var qe=globalThis[Ze];function wr(n,e){qe.set(n,e)}function qt(n){return qe.get(n)}function Ke(n){return qe.has(n)}wr("ai_agent",{name:"ai_agent",factory:!0,create:(n,e={})=>({name:n,_isCustomCode:!0,execute:async t=>{let r=t?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(ce(),ae))).invokeAgent);let o=e.extraPromptInstructions||"Execute the task based on the current state.",i=_r(o,t),s=await r(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 _r(n,e){let t=/@([\w.]+)/g,r=new Set,o;for(;(o=t.exec(n))!==null;)r.add(o[1]);if(r.size===0)return n;let i=[],s=new Set;for(let a of r){let l=a.split(".")[0];if(s.has(l))continue;let u=a.split(".").reduce((c,y)=>c?.[y],e);if(u===void 0)continue;let S=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),d=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${d}
41
+ ${S}`)}}function gr(){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 mr(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Kt(String(e).trim())}catch{return String(e).trim()}}function yr(){gr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Sr({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 wr(n={}){let e=yt.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,o=n.paths?.sessionPrefix;return o?`${o}_${r}`:r}function _r({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let o=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let u=Kt(String(process.env.ZIBBY_SESSION_PATH));u&&(o=u,s="ZIBBY_SESSION_PATH")}catch{}let a;if(o)a=String(o).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,s="ZIBBY_SESSION_ID";else{let p=e.sessionId!=null?String(e.sessionId).trim():"";p&&p!=="last"?(a=p,s="config.sessionId"):(a=wr(e),s="generated")}i=i??Date.now();let S=e.paths?.output||Se;o=X(n,S,gt,a)}let l=!Ze(o);return l&&qt(o,{recursive:!0}),(l||s!=="initialState.sessionPath")&&hr({traceFrom:r,sessionId:a,sessionPath:o,idSource:s,mkdirFresh:l}),Sr({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var Ae=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,r={}){if(!(t instanceof W)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async u=>{let S=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,p;return typeof s.input=="function"?p=s.input(S):s.input&&typeof s.input=="object"?p=s.input:p={},Ht(s.workflow,{input:p,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(S):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:S?._signal,parentAgent:u?.agent})}},l=new W(a);return l.name=e,this.nodes.set(e,l),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let o=!(t instanceof W)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof W?t:new W(o?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){let r=this.edges.get(e);return r===void 0?this.edges.set(e,t):typeof r=="string"?r!==t&&this.edges.set(e,[r,t]):Array.isArray(r)?r.includes(t)||r.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:r}={}){let o=this.edges.get(e);return o!==void 0&&!o.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(o)?o.join(", "):o}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_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,r=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&&r(s)}t.set(i,2)};this.entryPoint&&r(this.entryPoint);let o=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||o.set(s,(o.get(s)||0)+1);return{backEdges:e,joinDegree:o}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,o,i){let s=r;for(let a=e.length-1;a>=0;a--){let l=e[a],u=s;s=()=>l(t,u,o,i)}return s()}serialize(){let e=[],t={};for(let[p,c]of this.nodes){let m=this.nodeTypeMap.get(p)||(c?.config?._isRouter===!0?"decision":p);e.push({id:p,type:m,data:{nodeType:m,label:p}});let d={};c._isCustomCode&&typeof c.execute=="function"&&(d.customCode=c.execute.toString());let b=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;b&&(d.description=b);let $=this.nodePrompts.get(p);if($)d.prompt=$;else if(typeof c.prompt=="function")try{let h=c.prompt({});typeof h=="string"&&h.trim()&&(d.prompt=h,d.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(d.executeCode=c.customExecute.toString());let v=c?.config?.dispatchesWorkflow;if(typeof v=="string"&&v.trim())d.dispatchesWorkflow=v.trim();else if(Array.isArray(v)){let h=[...new Set(v.filter(g=>typeof g=="string").map(g=>g.trim()).filter(Boolean))];h.length&&(d.dispatchesWorkflow=h)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(d.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let h=null;if(typeof Te?.toJSONSchema=="function")try{h=Te.toJSONSchema(c.outputSchema)}catch{}if(!h)try{h=Zt(c.outputSchema,{target:"openApi3"})}catch{}d.outputSchema=h?{jsonSchema:h,variables:this._flattenJsonSchemaToVariables(h)}:{schema:c.outputSchema}}else d.outputSchema={schema:c.outputSchema};let f=(this.resolvedToolsMap||{})[p];f?.toolIds&&(d.tools=f.toolIds);let A=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;A&&A.length>0&&(d.skills=[...A]);let E=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;E&&E.length>0&&(d.plugins=E.map(h=>h&&typeof h=="object"?{...h}:h));let w=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;w&&w.length>0&&(d.stores=w.map(h=>h&&typeof h=="object"?{...h}:h));let y=Array.isArray(c?.config?.uses)?c.config.uses:typeof c?.config?.uses=="string"?[c.config.uses]:Array.isArray(c?.uses)?c.uses:typeof c?.uses=="string"?[c.uses]:null;if(y&&y.length>0){let h=new Set,g=[];for(let x of y){let P=typeof x=="string"?x.trim():"";!P||h.has(P)||(h.add(P),g.push(P))}g.length>0&&(d.uses=g)}Object.keys(d).length>0&&(t[p]=d)}let r=[];for(let[p,c]of this.edges)if(typeof c=="string")r.push({source:p,target:c});else if(Array.isArray(c))for(let m of c)r.push({source:p,target:m});else if(c.conditional){let m=this.conditionalCodeMap.get(p)||c.routes.toString(),d=this._inferConditionalTargets(c.routes,c.labels),b=c.labels||{},$=this.nodes.get(p),v=$?.config?._isRouter===!0||this.nodeTypeMap.get(p)==="decision"||!$,f=p;if(!v){let A=`${p}__branch`;e.push({id:A,type:"decision",data:{nodeType:"decision",label:A}}),r.push({source:p,target:A}),f=A}for(let A of d){let E={source:f,target:A,data:{conditionalCode:m}};b[A]&&(E.label=b[A]),r.push(E)}}let o=p=>{if(!p)return null;if(typeof Te?.toJSONSchema=="function")try{return Te.toJSONSchema(p)}catch{}try{return Zt(p,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let i=0;for(let p of r)if(p.target==="END"){i+=1;let c=`END__${i}`;p.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let p of this.nodes.keys())if(!this.edges.has(p)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:p,target:c})}let s=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=o(a||this.stateSchema),u=o(this.inputSchema),S=o(this.contextSchema);return{nodes:s,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:S}}_topoOrderNodes(e,t){let r=new Map(e.map((p,c)=>[p.id,c])),o=new Map(e.map(p=>[p.id,p])),i=new Map(e.map(p=>[p.id,0])),s=new Map(e.map(p=>[p.id,[]]));for(let p of t)s.has(p.source)&&i.has(p.target)&&(s.get(p.source).push(p.target),i.set(p.target,i.get(p.target)+1));let a=new Set,l=new Set(r.keys()),u=[...l].filter(p=>i.get(p)===0),S=[];for(;S.length<e.length;){let p;if(u.length>0){if(u.sort((c,m)=>r.get(c)-r.get(m)),p=u.shift(),a.has(p))continue}else p=[...l].sort((c,m)=>r.get(c)-r.get(m))[0];a.add(p),l.delete(p),S.push(o.get(p));for(let c of s.get(p)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return S}_inferConditionalTargets(e,t){let r=e.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(r))!==null;){let u=s[2]!==void 0?s[2]:s[3];u!==void 0&&u!==""&&o.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of o)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,S;for(;(S=u.exec(r))!==null;)l.add(S[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let o=e.$ref.replace("#/definitions/","");r=e.definitions[o]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],o=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(o)){let l=t?`${t}.${s}`:s;r.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${l}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[o,i]of Object.entries(t))if(!(o==="success"||o==="raw"||o==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${o}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);r.push(l?`${o}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${o}: ${s} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){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(I){let _=new Error(`agent.normalizeInput() rejected the trigger input: ${I?.message||I}`);throw _.cause=I,_.code=I?.code||"NORMALIZE_INPUT_FAILED",_}let o=new AbortController;r.signal&&(r.signal.aborted?o.abort():r.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();pr({path:X(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let I=X(s,".zibby.config.js");Ze(I)&&(a=(await import(I)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let I=a?.agent;I?.provider?l=I.provider:I?.gemini?l="gemini":I?.claude?l="claude":I?.cursor?l="cursor":I?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},S=this._runtimeSchema();if(S){let I=S.safeParse(t);if(!I.success){let _=I.error.issues.map(B=>`${B.path.join(".")}: ${B.message}`);throw console.error("\u274C Initial state validation failed:"),_.forEach(B=>console.error(` - ${B}`)),new Error(`State validation failed: ${_.join(", ")}`)}M.step("State validated against schema")}let p=mr(),c=t.sessionPath||p;c||yr();let{sessionPath:m,sessionTimestamp:d,sessionId:b}=_r({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});M.step(`Session ${b}`);let $=await Ie.loadContext(t.specPath||"",s,u);Object.keys($).length>0&&M.step(`Context loaded: ${Object.keys($).join(", ")}`);let v=t.outputPath;!v&&t.specPath&&(e?.calculateOutputPath?v=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ge({...t,config:a,agentType:l,outputPath:v,sessionPath:m,sessionTimestamp:d,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),A=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:E}=await Promise.resolve().then(()=>(we(),It)),w=a.skills&&typeof a.skills=="object"?a.skills:{},y=Object.values(w).filter(I=>I&&typeof I=="object"&&typeof I.id=="string"),h=I=>{for(let _ of y)if(_.id===I)return _;return E(I)},g=new Set;for(let[,I]of this.nodes)for(let _ of I.config?.skills||[])g.add(_);for(let I of g){let _=h(I);if(typeof _?.middleware=="function")try{let B=await _.middleware();typeof B=="function"&&A.set(I,B)}catch{}}let{backEdges:x,joinDegree:P}=this._analyzeFlow(),z=new Map,ne=[],$e=(I,_,B)=>{if(!I||I==="END")return;let F=P.get(I)||0;if(B&&F>1&&!x.has(`${_}->${I}`)){let re=(z.get(I)||0)+1;if(re<F){z.set(I,re);return}z.set(I,0)}ne.includes(I)||ne.push(I)};this.entryPoint&&ne.push(this.entryPoint);let pe=[],Xe=a?.recursionLimit??100,tn=0;try{for(;ne.length>0;){let _=ne.pop();if(!_||_==="END")continue;if(++tn>Xe)throw new Error(`Workflow exceeded recursion limit (${Xe}) \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=X(m,mt);if(Ze(B)){try{dr(B)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
42
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),M.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:pe,stoppedExternally:!0};let F=this.nodes.get(_);if(!F)throw new Error(`Node '${_}' not found in graph`);let re=JSON.stringify({sessionPath:m,sessionTimestamp:d,currentNode:_,createdAt:new Date().toISOString(),config:f.get("config")}),nn=X(m,ee);Yt(nn,re,"utf-8");let Qe=f.get("config")?.paths?.output||Se,rn=X(s,Qe,ee);qt(X(s,Qe),{recursive:!0});try{Yt(rn,re,"utf-8")}catch{}let et=t.onPipelineProgress;if(typeof et=="function")try{et({cwd:s,sessionPath:m,sessionId:b,outputBase:f.get("config")?.paths?.output||Se,currentNode:_})}catch{}let on=(this.resolvedToolsMap||{})[_]||null;f.set("_currentNodeTools",on);let sn=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",sn[_]||{}),M.nodeStart(_);let tt=Date.now(),fe=this.nodePrompts.get(_);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(ce(),ae));this._invokeAgent=k.invokeAgent}let an=this._invokeAgent,xe={},cn=F.config?.skills||[];for(let k of cn){let C=h(k);if(typeof C?.invokeAgentOptions=="function")try{let O=C.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:_});O&&typeof O=="object"&&(xe={...xe,...O})}catch(O){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${O.message}`)}}let nt=async(k,C,O={})=>{let D=an(k,C,{...xe,...O,signal:o.signal});return D.catch(()=>{}),o.signal.aborted?D:Promise.race([D,new Promise((Q,G)=>{let U=()=>{setTimeout(()=>{let st=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);st.name="AbortError",G(st)},i)};o.signal.addEventListener("abort",U,{once:!0})})])},ln=async(k={},C={})=>{let O=C.prompt||"";if(fe){let D=this._compiledPrompts.get(_);D||(D=fr.compile(fe,{noEscape:!0}),this._compiledPrompts.set(_,D));try{O=D(k)}catch(Q){throw console.error(`\u274C Template rendering failed for node '${_}':`,Q.message),new Error(`Template rendering failed: ${Q.message}`,{cause:Q})}}else if(!O)throw new Error(`No prompt template configured for node '${_}' and no prompt provided in options`);return nt(O,{state:f.getAll(),images:C.images||[]},{model:C.model||f.get("model"),workspace:f.get("workspace"),schema:C.schema,...C,signal:o.signal,nodeName:_})},rt=f.getAll(),un=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of un)Object.prototype.hasOwnProperty.call(rt,k)&&console.warn(`[workflow] node "${_}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let ot={...rt,state:f,invokeAgent:ln,_coreInvokeAgent:nt,agent:e,nodeId:_,promptTemplate:fe,getPromptTemplate:()=>fe};try{let k=(F.config?.skills||[]).map(U=>A.get(U)).filter(Boolean),C=[...this.middleware,...k],O;O=await Rt(e,o.signal,async()=>C.length>0?this._composeMiddleware(C,_,async()=>F.execute(ot,f),f.getAll(),f):F.execute(ot,f));let D=Date.now()-tt;if(pe.push({node:_,success:O.success,duration:D,timestamp:new Date().toISOString()}),!O.success){if(o.signal.aborted)return M.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:pe,stoppedExternally:!0};f.append("errors",{node:_,error:O.error});let U=Number.isInteger(O.attempts)&&O.attempts>0?O.attempts:(F.config?.retries||0)+1;throw M.nodeFailed(_,O.error,{duration:D}),new Error(`Node '${_}' failed after ${U} attempt(s): ${O.error}`)}f.update({[_]:O.output});let Q=this._summarizeNodeOutput(_,O.output);M.nodeComplete(_,{duration:D,details:Q});let G=this.edges.get(_);if(G)if(G.conditional){let U=G.routes(f.getAll());M.route(_,U),$e(U,_,!1)}else if(Array.isArray(G))for(let U=G.length-1;U>=0;U--)$e(G[U],_,!0);else $e(G,_,!0)}catch(k){throw M.isInsideNode&&M.nodeFailed(_,k.message,{duration:Date.now()-tt}),f.set("failed",!0),f.set("failedAt",_),k}}M.graphComplete();let I={success:!0,state:f.getAll(),executionLog:pe};return e&&typeof e.onComplete=="function"&&await e.onComplete(I),I}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(I){console.warn(`[workflow] agent.cleanup() failed: ${I.message}`)}}}};var qe=Symbol.for("@zibby/agent-workflow.nodes");globalThis[qe]||(globalThis[qe]=new Map);var Ke=globalThis[qe];function br(n,e){Ke.set(n,e)}function Vt(n){return Ke.get(n)}function Ve(n){return Ke.has(n)}br("ai_agent",{name:"ai_agent",factory:!0,create:(n,e={})=>({name:n,_isCustomCode:!0,execute:async t=>{let r=t?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(ce(),ae))).invokeAgent);let o=e.extraPromptInstructions||"Execute the task based on the current state.",i=Er(o,t),s=await r(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 Er(n,e){let t=/@([\w.]+)/g,r=new Set,o;for(;(o=t.exec(n))!==null;)r.add(o[1]);if(r.size===0)return n;let i=[],s=new Set;for(let a of r){let l=a.split(".")[0];if(s.has(l))continue;let u=a.split(".").reduce((c,m)=>c?.[m],e);if(u===void 0)continue;let S=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),p=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${p}
43
43
  ${S}`),a.includes(".")||s.add(l)}return i.length===0?n:`${n}
44
44
 
45
45
  ---
@@ -47,4 +47,4 @@ ${S}`),a.includes(".")||s.add(l)}return i.length===0?n:`${n}
47
47
 
48
48
  ${i.join(`
49
49
 
50
- `)}`}we();J();var br={};function Vt(n,e){if(Array.isArray(e))return Kt(e);let t=br[n];return!t||t.length===0?null:Kt(t)}function Kt(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},r=[];for(let o of n){let i=ie(o);if(!i){T.warn(`[workflow] unknown skill "${o}" \u2014 skipping`);continue}r.push(o);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:o})}else{let s={};for(let a of i.envKeys||[]){let l=process.env[a];l&&(s[a]=l)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:s,toolPrefix:o}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}J();function Bo(n,e={}){let{nodes:t,edges:r,nodeConfigs:o={}}=n;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(r))throw new j("Graph edges must be an array");let i=new Ae(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let s=new Set,a=new Map,l={};for(let c of t){let y=ve(c);a.set(c.id,{...c,resolvedType:y}),y==="decision"&&s.add(c.id)}for(let[c,y]of a){if(s.has(c))continue;let p=y.resolvedType,b=o[c]||{},v=Vt(p,b.tools);v&&(l[c]=v);let $={};b.prompt&&($.prompt=b.prompt);let f=Ke(p);if(T.debug(`[workflow] compiler: node "${c}" type="${p}" registered=${f}`),b.customCode&&!f)i.addNode(c,Xt(c,b.customCode,b),$),i.setNodeType(c,p);else if(f){let I=qt(p);I.factory?i.addNode(c,I.create(c,{...b,resolvedTools:v}),$):i.addNode(c,I,$),i.setNodeType(c,p)}else if(b.executeCode)i.addNode(c,Xt(c,b.executeCode,b),$),i.setNodeType(c,p);else throw new j(`Unknown node type "${p}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=l;let u=new Set;for(let c of r)s.has(c.target)||u.add(c.target);let S=t.find(c=>!s.has(c.id)&&!u.has(c.id));if(!S)throw new j("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(S.id);let d=Er(r,"source");for(let c of r)if(!s.has(c.source))if(s.has(c.target)){let y=c.target,p=d.get(y)||[];if(p.length===0)throw new j(`Decision node "${y}" has no outgoing edges`);let b=Ir(y,p,s);i.addConditionalEdges(c.source,b)}else i.addEdge(c.source,c.target);return i}function Do(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 l=ve(a);if(l==="decision"||Ke(l))continue;let u=t[a.id]||{};u.customCode||u.executeCode||e.push(`Unknown node type "${l}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let r=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)r.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),r.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let o=new Set(n.nodes.filter(a=>ve(a)==="decision").map(a=>a.id)),i=new Set;for(let a of n.edges)o.has(a.target)||i.add(a.target);let s=n.nodes.filter(a=>!o.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 o){let l=n.edges.filter(S=>S.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(S=>S.data?.conditionalCode||S.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Uo(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>ve(e)!=="decision").map(e=>e.id)}function ve(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function Er(n,e){let t=new Map;for(let r of n){let o=r[e];t.has(o)||t.set(o,[]),t.get(o).push(r)}return t}function Ir(n,e,t){let r=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!r)throw new j(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let o=r.data?.conditionalCode||r.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),s;try{let l=new Function(`return (${o})`)();s=u=>{let S=l(u);return i.has(S)||T.warn(`[workflow] conditional route from "${n}" returned "${S}" which is not in valid targets: ${[...i].join(", ")}`),S}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return s}function Xt(n,e,t={}){let r;try{r=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new j(`Failed to compile customCode for node "${n}": ${s.message}`)}let o=r(async(...s)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(ce(),ae));return a(...s)},typeof Oe<"u"?Oe: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 o(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,Bo as compileGraph,Uo as extractSteps,Do as validateGraphConfig};
50
+ `)}`}we();J();var Ir={};function Qt(n,e){if(Array.isArray(e))return Xt(e);let t=Ir[n];return!t||t.length===0?null:Xt(t)}function Xt(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},r=[];for(let o of n){let i=ie(o);if(!i){T.warn(`[workflow] unknown skill "${o}" \u2014 skipping`);continue}r.push(o);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:o})}else{let s={};for(let a of i.envKeys||[]){let l=process.env[a];l&&(s[a]=l)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:s,toolPrefix:o}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}J();function Uo(n,e={}){let{nodes:t,edges:r,nodeConfigs:o={}}=n;if(!Array.isArray(t)||t.length===0)throw new L("Graph must have at least one node");if(!Array.isArray(r))throw new L("Graph edges must be an array");let i=new Ae(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let s=new Set,a=new Map,l={};for(let c of t){let m=ve(c);a.set(c.id,{...c,resolvedType:m}),m==="decision"&&s.add(c.id)}for(let[c,m]of a){if(s.has(c))continue;let d=m.resolvedType,b=o[c]||{},$=Qt(d,b.tools);$&&(l[c]=$);let v={};b.prompt&&(v.prompt=b.prompt);let f=Ve(d);if(T.debug(`[workflow] compiler: node "${c}" type="${d}" registered=${f}`),b.customCode&&!f)i.addNode(c,en(c,b.customCode,b),v),i.setNodeType(c,d);else if(f){let A=Vt(d);A.factory?i.addNode(c,A.create(c,{...b,resolvedTools:$}),v):i.addNode(c,A,v),i.setNodeType(c,d)}else if(b.executeCode)i.addNode(c,en(c,b.executeCode,b),v),i.setNodeType(c,d);else throw new L(`Unknown node type "${d}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=l;let u=new Set;for(let c of r)s.has(c.target)||u.add(c.target);let S=t.find(c=>!s.has(c.id)&&!u.has(c.id));if(!S)throw new L("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(S.id);let p=Tr(r,"source");for(let c of r)if(!s.has(c.source))if(s.has(c.target)){let m=c.target,d=p.get(m)||[];if(d.length===0)throw new L(`Decision node "${m}" has no outgoing edges`);let b=Ar(m,d,s);i.addConditionalEdges(c.source,b)}else i.addEdge(c.source,c.target);return i}function jo(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 l=ve(a);if(l==="decision"||Ve(l))continue;let u=t[a.id]||{};u.customCode||u.executeCode||e.push(`Unknown node type "${l}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let r=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)r.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),r.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let o=new Set(n.nodes.filter(a=>ve(a)==="decision").map(a=>a.id)),i=new Set;for(let a of n.edges)o.has(a.target)||i.add(a.target);let s=n.nodes.filter(a=>!o.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 o){let l=n.edges.filter(S=>S.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(S=>S.data?.conditionalCode||S.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Lo(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>ve(e)!=="decision").map(e=>e.id)}function ve(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function Tr(n,e){let t=new Map;for(let r of n){let o=r[e];t.has(o)||t.set(o,[]),t.get(o).push(r)}return t}function Ar(n,e,t){let r=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!r)throw new L(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let o=r.data?.conditionalCode||r.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),s;try{let l=new Function(`return (${o})`)();s=u=>{let S=l(u);return i.has(S)||T.warn(`[workflow] conditional route from "${n}" returned "${S}" which is not in valid targets: ${[...i].join(", ")}`),S}}catch(a){throw new L(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return s}function en(n,e,t={}){let r;try{r=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new L(`Failed to compile customCode for node "${n}": ${s.message}`)}let o=r(async(...s)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(ce(),ae));return a(...s)},typeof Oe<"u"?Oe: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 o(s);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var L=class extends Error{constructor(e){super(e),this.name="CompilationError"}};export{L as CompilationError,Uo as compileGraph,Lo as extractSteps,jo as validateGraphConfig};