@zibby/agent-workflow 0.4.36 → 0.4.37

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,12 +1,12 @@
1
- var U=Object.defineProperty;var N=(e,o)=>()=>(e&&(o=e(e=0)),o);var H=(e,o)=>{for(var n in o)U(e,n,{get:o[n],enumerable:!0})};function v(e){return K.get(e)||null}var b,K,E=N(()=>{b=Symbol.for("@zibby/agent-workflow.skills");globalThis[b]||(globalThis[b]=new Map);K=globalThis[b]});var O,W,$,T,_=N(()=>{O=()=>{},W={debug:O,info:O,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},$={impl:W},T={debug:(...e)=>$.impl.debug?.(...e),info:(...e)=>$.impl.info?.(...e),warn:(...e)=>$.impl.warn?.(...e),error:(...e)=>$.impl.error?.(...e)}});var P=N(()=>{});var L={};H(L,{getAgentStrategy:()=>D,invokeAgent:()=>q,listStrategies:()=>Z,registerStrategy:()=>J});function J(e){if(!e||typeof e.getName!="function"||typeof e.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let o=k.findIndex(n=>n.getName()===e.getName());o>=0?k[o]=e:k.push(e)}function Z(){return k.map(e=>e.getName())}function D(e={}){let{state:o={},preferredAgent:n=null}=e,r=n||o.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}`)}T.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 T.debug(`[workflow] using agent: ${i.getName()}`),i}async function q(e,o={},n={}){let r=o.state&&typeof o.state.getAll=="function"?o.state.getAll():o.state||{},i={...o,state:r},s=D(i),t=r.config||n.config||{},a=t.models||{},c=n.nodeName&&a[n.nodeName]||null,l=a.default||null,h=t.agent?.[s.name]?.model||null,y=c||l||h||n.model||null,w={...n,model:y,workspace:r.workspace||n.workspace,schema:n.schema||o.schema,images:n.images||o.images||[],skills:n.skills||o.skills||[],plugins:n.plugins||o.plugins||[],config:t},g=e,p=w.skills||[];if(p.length>0&&!n.skipPromptFragments){let u=p.map(S=>{let f=v(S)?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);u.length>0&&(g+=`
1
+ var K=Object.defineProperty;var b=(e,o)=>()=>(e&&(o=e(e=0)),o);var H=(e,o)=>{for(var n in o)K(e,n,{get:o[n],enumerable:!0})};function E(e){return W.get(e)||null}var N,v,W,de,x=b(()=>{N=Symbol.for("@zibby/agent-workflow.skills"),v=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[N]||(globalThis[N]=new Map);globalThis[v]||(globalThis[v]=new Map);W=globalThis[N],de=globalThis[v]});var R,J,S,T,_=b(()=>{R=()=>{},J={debug:R,info:R,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},S={impl:J},T={debug:(...e)=>S.impl.debug?.(...e),info:(...e)=>S.impl.info?.(...e),warn:(...e)=>S.impl.warn?.(...e),error:(...e)=>S.impl.error?.(...e)}});var L=b(()=>{});var M={};H(M,{getAgentStrategy:()=>D,invokeAgent:()=>Q,listStrategies:()=>Z,registerStrategy:()=>q});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 o=k.findIndex(n=>n.getName()===e.getName());o>=0?k[o]=e:k.push(e)}function Z(){return k.map(e=>e.getName())}function D(e={}){let{state:o={},preferredAgent:n=null}=e,r=n||o.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}`)}T.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 T.debug(`[workflow] using agent: ${i.getName()}`),i}async function Q(e,o={},n={}){let r=o.state&&typeof o.state.getAll=="function"?o.state.getAll():o.state||{},i={...o,state:r},s=D(i),t=r.config||n.config||{},a=t.models||{},c=n.nodeName&&a[n.nodeName]||null,l=a.default||null,h=t.agent?.[s.name]?.model||null,y=c||l||h||n.model||null,w={...n,model:y,workspace:r.workspace||n.workspace,schema:n.schema||o.schema,images:n.images||o.images||[],skills:n.skills||o.skills||[],plugins:n.plugins||o.plugins||[],config:t},g=e,p=w.skills||[];if(p.length>0&&!n.skipPromptFragments){let u=p.map($=>{let f=E($)?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);u.length>0&&(g+=`
2
2
 
3
3
  ${u.join(`
4
4
 
5
- `)}`)}let m=r._currentNodeConfig?.stores;if(Array.isArray(m)&&m.length>0&&typeof m[0]=="object"){let u=m.length<=8,S=m.map(f=>{let j=f?.id??f?.storeId??"",F=(f?.name??"").toString().trim()||j,V=f?.type?` \xB7 ${f.type}`:"",Y=(f?.description||"").toString().replace(/\s+/g," ").trim(),I=`- ${F} \xB7 ${Y||"(no description)"}${V} (id: ${j})`;if(u&&f?.schema&&typeof f.schema=="object"){let C=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);C.length&&(I+=`
6
- fields: ${C.join(", ")}`)}return I});g+=`
5
+ `)}`)}let m=r._currentNodeConfig?.stores;if(Array.isArray(m)&&m.length>0&&typeof m[0]=="object"){let u=m.length<=8,$=m.map(f=>{let I=f?.id??f?.storeId??"",V=(f?.name??"").toString().trim()||I,Y=f?.type?` \xB7 ${f.type}`:"",U=(f?.description||"").toString().replace(/\s+/g," ").trim(),C=`- ${V} \xB7 ${U||"(no description)"}${Y} (id: ${I})`;if(u&&f?.schema&&typeof f.schema=="object"){let O=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);O.length&&(C+=`
6
+ fields: ${O.join(", ")}`)}return C});g+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
9
- ${S.join(`
9
+ ${$.join(`
10
10
  `)}`}let d=r._currentNodeConfig?.extraPromptInstructions?.trim();return d&&(g+=`
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
@@ -14,7 +14,7 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
14
14
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
15
15
 
16
16
  ${d}
17
- `),T.debug(`[workflow] prompt length: ${g.length} chars`),s.invoke(g,w)}var x,k,M=N(()=>{P();_();E();x=Symbol.for("@zibby/agent-workflow.strategies");globalThis[x]||(globalThis[x]=[]);k=globalThis[x]});E();_();var R={};var A=Symbol.for("@zibby/agent-workflow.nodes");globalThis[A]||(globalThis[A]=new Map);var G=globalThis[A];function Q(e,o){G.set(e,o)}function z(e){let o=G.get(e);return o?o.factory&&typeof o.create=="function"?o.create.toString():typeof o.execute=="function"?o.execute.toString():typeof o=="function"?o.toString():null:null}Q("ai_agent",{name:"ai_agent",factory:!0,create:(e,o={})=>({name:e,_isCustomCode:!0,execute:async n=>{let r=n?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(M(),L))).invokeAgent);let i=o.extraPromptInstructions||"Execute the task based on the current state.",s=X(i,n),t=await r(s,{cwd:n.workspace||process.cwd(),model:n.model,tools:o.resolvedTools||null});return{success:!0,output:{raw:t,nodeId:e},raw:typeof t=="string"?t:t.raw}}})});function X(e,o){let n=/@([\w.]+)/g,r=new Set,i;for(;(i=n.exec(e))!==null;)r.add(i[1]);if(r.size===0)return e;let s=[],t=new Set;for(let a of r){let c=a.split(".")[0];if(t.has(c))continue;let l=a.split(".").reduce((w,g)=>w?.[g],o);if(l===void 0)continue;let h=typeof l=="string"?l:l?.raw??JSON.stringify(l,null,2),y=a.replace(/_/g," ").replace(/\b\w/g,w=>w.toUpperCase());s.push(`## ${y}
17
+ `),T.debug(`[workflow] prompt length: ${g.length} chars`),s.invoke(g,w)}var A,k,z=b(()=>{L();_();x();A=Symbol.for("@zibby/agent-workflow.strategies");globalThis[A]||(globalThis[A]=[]);k=globalThis[A]});x();_();var P={};var j=Symbol.for("@zibby/agent-workflow.nodes");globalThis[j]||(globalThis[j]=new Map);var G=globalThis[j];function X(e,o){G.set(e,o)}function B(e){let o=G.get(e);return o?o.factory&&typeof o.create=="function"?o.create.toString():typeof o.execute=="function"?o.execute.toString():typeof o=="function"?o.toString():null:null}X("ai_agent",{name:"ai_agent",factory:!0,create:(e,o={})=>({name:e,_isCustomCode:!0,execute:async n=>{let r=n?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(z(),M))).invokeAgent);let i=o.extraPromptInstructions||"Execute the task based on the current state.",s=ee(i,n),t=await r(s,{cwd:n.workspace||process.cwd(),model:n.model,tools:o.resolvedTools||null});return{success:!0,output:{raw:t,nodeId:e},raw:typeof t=="string"?t:t.raw}}})});function ee(e,o){let n=/@([\w.]+)/g,r=new Set,i;for(;(i=n.exec(e))!==null;)r.add(i[1]);if(r.size===0)return e;let s=[],t=new Set;for(let a of r){let c=a.split(".")[0];if(t.has(c))continue;let l=a.split(".").reduce((w,g)=>w?.[g],o);if(l===void 0)continue;let h=typeof l=="string"?l:l?.raw??JSON.stringify(l,null,2),y=a.replace(/_/g," ").replace(/\b\w/g,w=>w.toUpperCase());s.push(`## ${y}
18
18
  ${h}`),a.includes(".")||t.add(c)}return s.length===0?e:`${e}
19
19
 
20
20
  ---
@@ -22,13 +22,13 @@ ${h}`),a.includes(".")||t.add(c)}return s.length===0?e:`${e}
22
22
 
23
23
  ${s.join(`
24
24
 
25
- `)}`}function Se(e,o={}){let{nodes:n,edges:r,nodeConfigs:i={}}=e,s=new Set,t=[],a=new Map;for(let d of n){let u=d.data?.nodeType||d.type;a.set(d.id,u),u==="decision"?s.add(d.id):t.push({id:d.id,nodeType:u,label:d.data?.label||d.id})}let c=t.some(d=>{let u=i[d.id]||{};return!u.customCode&&!u.executeCode}),{toolsPerNode:l,toolIdsByVar:h}=ie(t,i),{simpleEdges:y,conditionalEdges:w}=ce(r,s),g=ae(t,r,s),p=[],m=o.workflowType||"workflow";return p.push(ee(o)),p.push(oe(m,{usesRegisteredNodes:c})),p.push(te(h)),p.push(ne(m)),p.push(re(t,i)),p.push(se(t,g,y,w,l,m)),p.filter(Boolean).join(`
26
- `)}function be(e){let o={};for(let[n,r]of Object.entries(e)){let{tools:i,...s}=r;Object.keys(s).length>0&&(o[n]=s)}return o}function ee(e){let o=e.workflowType||"workflow";return["// Generated workflow",`// ${e.projectId?`Project: ${e.projectId} | `:""}Type: ${o} | Version: ${e.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
27
- `)}function oe(e,{usesRegisteredNodes:o=!0}={}){let n=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return o&&n.push("// import './register-nodes.js'; // register custom node types here"),n.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),n.join(`
28
- `)}function te(e){if(e.size===0)return"";let o=["// \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[n,r]of e)o.push(`const ${n} = getResolvedToolDefinitions(${JSON.stringify(r)}); // ${r.join(", ")}`);return o.push(""),o.join(`
29
- `)}function ne(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 re(e,o){let n=["// \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=B(r.id),s=o[r.id]?.customCode;if(s)n.push(`// @custom \u2014 modified from default "${r.nodeType}" template`),n.push(`const ${i}_execute = ${s};`);else{let t=z(r.nodeType);t?(n.push(`// Default "${r.nodeType}" implementation`),n.push(`const ${i}_execute = ${t};`)):(n.push(`// No template for "${r.nodeType}" \u2014 passthrough`),n.push(`const ${i}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}n.push("")}return n.join(`
31
- `)}function se(e,o,n,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 c of e){let l=B(c.id);t.push(` graph.addNode('${c.id}', { name: '${c.id}', execute: ${l}_execute });`),t.push(` graph.setNodeType('${c.id}', '${c.nodeType}');`)}t.push("",` graph.setEntryPoint('${o}');`,""),(n.length>0||r.length>0)&&t.push(" // Edges");for(let c of n)t.push(` graph.addEdge('${c.source}', '${c.target}');`);for(let c of r){let l=c.code.split(`
25
+ `)}`}function ve(e,o={}){let{nodes:n,edges:r,nodeConfigs:i={}}=e,s=new Set,t=[],a=new Map;for(let d of n){let u=d.data?.nodeType||d.type;a.set(d.id,u),u==="decision"?s.add(d.id):t.push({id:d.id,nodeType:u,label:d.data?.label||d.id})}let c=t.some(d=>{let u=i[d.id]||{};return!u.customCode&&!u.executeCode}),{toolsPerNode:l,toolIdsByVar:h}=ce(t,i),{simpleEdges:y,conditionalEdges:w}=ae(r,s),g=le(t,r,s),p=[],m=o.workflowType||"workflow";return p.push(oe(o)),p.push(te(m,{usesRegisteredNodes:c})),p.push(ne(h)),p.push(re(m)),p.push(se(t,i)),p.push(ie(t,g,y,w,l,m)),p.filter(Boolean).join(`
26
+ `)}function Ee(e){let o={};for(let[n,r]of Object.entries(e)){let{tools:i,...s}=r;Object.keys(s).length>0&&(o[n]=s)}return o}function oe(e){let o=e.workflowType||"workflow";return["// Generated workflow",`// ${e.projectId?`Project: ${e.projectId} | `:""}Type: ${o} | Version: ${e.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
27
+ `)}function te(e,{usesRegisteredNodes:o=!0}={}){let n=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return o&&n.push("// import './register-nodes.js'; // register custom node types here"),n.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),n.join(`
28
+ `)}function ne(e){if(e.size===0)return"";let o=["// \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[n,r]of e)o.push(`const ${n} = getResolvedToolDefinitions(${JSON.stringify(r)}); // ${r.join(", ")}`);return o.push(""),o.join(`
29
+ `)}function re(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 se(e,o){let n=["// \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=F(r.id),s=o[r.id]?.customCode;if(s)n.push(`// @custom \u2014 modified from default "${r.nodeType}" template`),n.push(`const ${i}_execute = ${s};`);else{let t=B(r.nodeType);t?(n.push(`// Default "${r.nodeType}" implementation`),n.push(`const ${i}_execute = ${t};`)):(n.push(`// No template for "${r.nodeType}" \u2014 passthrough`),n.push(`const ${i}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}n.push("")}return n.join(`
31
+ `)}function ie(e,o,n,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 c of e){let l=F(c.id);t.push(` graph.addNode('${c.id}', { name: '${c.id}', execute: ${l}_execute });`),t.push(` graph.setNodeType('${c.id}', '${c.nodeType}');`)}t.push("",` graph.setEntryPoint('${o}');`,""),(n.length>0||r.length>0)&&t.push(" // Edges");for(let c of n)t.push(` graph.addEdge('${c.source}', '${c.target}');`);for(let c of r){let l=c.code.split(`
32
32
  `).map((h,y)=>y===0?h:` ${h}`).join(`
33
33
  `);t.push(` graph.addConditionalEdges('${c.source}', ${l});`)}let a=[];for(let c of e){let l=i.get(c.id);l&&a.push(` '${c.id}': ${l},`)}return a.length>0&&t.push(""," graph.resolvedToolsMap = {",...a," };"),t.push(""," return graph;","}",""),t.push("export { nodeConfigs };",""),t.join(`
34
- `)}function ie(e,o){let n=new Map,r=new Map;for(let i of e){let s=o[i.id]?.tools,t;if(Array.isArray(s)&&s.length>0)t=[...s].sort();else{let a=R[i.nodeType];a?.length>0&&(t=[...a].sort())}if(t){let a=`${t.map(c=>c.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;n.set(i.id,a),r.has(a)||r.set(a,t)}}return{toolsPerNode:n,toolIdsByVar:r}}function ce(e,o){let n=[],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(!o.has(t.source))if(o.has(t.target)){if(s.has(t.target))continue;s.add(t.target);let c=(i.get(t.target)||[]).find(l=>l.data?.conditionalCode||l.conditionalCode);c&&r.push({source:t.source,code:c.data?.conditionalCode||c.conditionalCode})}else n.push({source:t.source,target:t.target});return{simpleEdges:n,conditionalEdges:r}}function ae(e,o,n){let r=new Set;for(let s of o)n.has(s.target)||r.add(s.target);let i=e.find(s=>!r.has(s.id));return i?i.id:e[0]?.id}function B(e){return e.replace(/[^a-zA-Z0-9]/g,"_")}export{be as generateNodeConfigsJson,Se as generateWorkflowCode};
34
+ `)}function ce(e,o){let n=new Map,r=new Map;for(let i of e){let s=o[i.id]?.tools,t;if(Array.isArray(s)&&s.length>0)t=[...s].sort();else{let a=P[i.nodeType];a?.length>0&&(t=[...a].sort())}if(t){let a=`${t.map(c=>c.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;n.set(i.id,a),r.has(a)||r.set(a,t)}}return{toolsPerNode:n,toolIdsByVar:r}}function ae(e,o){let n=[],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(!o.has(t.source))if(o.has(t.target)){if(s.has(t.target))continue;s.add(t.target);let c=(i.get(t.target)||[]).find(l=>l.data?.conditionalCode||l.conditionalCode);c&&r.push({source:t.source,code:c.data?.conditionalCode||c.conditionalCode})}else n.push({source:t.source,target:t.target});return{simpleEdges:n,conditionalEdges:r}}function le(e,o,n){let r=new Set;for(let s of o)n.has(s.target)||r.add(s.target);let i=e.find(s=>!r.has(s.id));return i?i.id:e[0]?.id}function F(e){return e.replace(/[^a-zA-Z0-9]/g,"_")}export{Ee as generateNodeConfigsJson,ve as generateWorkflowCode};
@@ -14,44 +14,14 @@ export const STOP_REQUEST_FILE: ".zibby-stop";
14
14
  export const RESULT_FILE: "result.json";
15
15
  export const RAW_OUTPUT_FILE: "raw_stream_output.txt";
16
16
  export const EVENTS_FILE: "events.json";
17
- export namespace SKILLS {
18
- let BROWSER: string;
19
- let JIRA: string;
20
- let GITHUB: string;
21
- let GITLAB: string;
22
- let FIGMA: string;
23
- let OPEN_DESIGN: string;
24
- let GIT: string;
25
- let GIT_WRITE: string;
26
- let SLACK: string;
27
- let LARK: string;
28
- let DISCORD: string;
29
- let CHAT_NOTIFY: string;
30
- let SENTRY: string;
31
- let MEMORY: string;
32
- let CHAT_MEMORY: string;
33
- let KV_MEMORY: string;
34
- let RUNNER: string;
35
- let SKILL_INSTALLER: string;
36
- let CORE_TOOLS: string;
37
- let WORKFLOW_BUILDER: string;
38
- let SESSION: string;
39
- let OPENAI_BILLING: string;
40
- let ANTHROPIC_BILLING: string;
41
- let CURSOR_ADMIN: string;
42
- let NOTION: string;
43
- let GOOGLE_DOCS: string;
44
- let LARK_DOCS: string;
45
- let DOC_SOURCE: string;
46
- let LINEAR: string;
47
- let PLANE: string;
48
- let CODEBASE_MEMORY: string;
49
- let DATASET_STORE: string;
50
- let LINKEDIN: string;
51
- let CIRCLECI: string;
52
- let TRIGGER_AGENT: string;
53
- let CODE_SCAN: string;
54
- }
17
+ /**
18
+ * Well-known skill IDs no longer live here. The single authoritative map moved
19
+ * to the zero-dep leaf @zibby/skill-ids (SKILL_IDS), re-exported as SKILLS by
20
+ * @zibby/skills and @zibby/core. The engine never needed a SKILLS.X value — it
21
+ * binds skills by string id via the registry (graph.js -> getSkill(id)) — so
22
+ * agent-workflow deliberately does NOT depend on skill-ids or enumerate ids.
23
+ * See strategy/skills-platform-architecture.md.
24
+ */
55
25
  /**
56
26
  * No-connection toggleable skills — skills that require NO integration/token
57
27
  * (they run purely locally in the agent runtime) but are still USER-TOGGLEABLE
package/dist/constants.js CHANGED
@@ -1 +1 @@
1
- var E=".zibby/output",I="sessions",_=".session-info.json",t=".zibby-stop",e="result.json",O="raw_stream_output.txt",s="events.json",o={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",DISCORD:"discord",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder",SESSION:"session",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE_DOCS:"google-docs",LARK_DOCS:"lark-docs",DOC_SOURCE:"doc_source",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent",CODE_SCAN:"code-scan"},r=Object.freeze([o.CODEBASE_MEMORY,o.CODE_SCAN]),n=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];export{n as CI_ENV_VARS,E as DEFAULT_OUTPUT_BASE,s as EVENTS_FILE,r as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,O as RAW_OUTPUT_FILE,e as RESULT_FILE,I as SESSIONS_DIR,_ as SESSION_INFO_FILE,o as SKILLS,t as STOP_REQUEST_FILE};
1
+ var o=".zibby/output",t="sessions",_=".session-info.json",s=".zibby-stop",e="result.json",I="raw_stream_output.txt",E="events.json",n=Object.freeze(["codebase-memory","code-scan"]),S=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];export{S as CI_ENV_VARS,o as DEFAULT_OUTPUT_BASE,E as EVENTS_FILE,n as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,I as RAW_OUTPUT_FILE,e as RESULT_FILE,t as SESSIONS_DIR,_ as SESSION_INFO_FILE,s as STOP_REQUEST_FILE};
@@ -1,8 +1,8 @@
1
- var Lt=Object.defineProperty;var ye=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var ie=(o,e)=>()=>(o&&(e=o(o=0)),e);var Fe=(o,e)=>{for(var t in e)Lt(o,t,{get:e[t],enumerable:!0})};var He,Wt,le,I,W=ie(()=>{He=()=>{},Wt={debug:He,info:He,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},le={impl:Wt},I={debug:(...o)=>le.impl.debug?.(...o),info:(...o)=>le.impl.info?.(...o),warn:(...o)=>le.impl.warn?.(...o),error:(...o)=>le.impl.error?.(...o)}});var ot=ie(()=>{});var rt={};Fe(rt,{clearSkills:()=>zt,getAllSkills:()=>Yt,getSkill:()=>Q,hasSkill:()=>Jt,listSkillIds:()=>Zt,registerSkill:()=>Ht});function Ht(o){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");q.set(o.id,Object.freeze({...o}))}function Q(o){return q.get(o)||null}function Jt(o){return q.has(o)}function Yt(){return new Map(q)}function Zt(){return Array.from(q.keys())}function zt(){q.clear()}var be,q,de=ie(()=>{be=Symbol.for("@zibby/agent-workflow.skills");globalThis[be]||(globalThis[be]=new Map);q=globalThis[be]});var ee={};Fe(ee,{getAgentStrategy:()=>nt,invokeAgent:()=>Vt,listStrategies:()=>qt,registerStrategy:()=>Kt});function Kt(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=G.findIndex(t=>t.getName()===o.getName());e>=0?G[e]=o:G.push(o)}function qt(){return G.map(o=>o.getName())}function nt(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let s=G.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}I.debug(`[workflow] agent selection: requested=${r}`);let a=G.find(s=>s.getName()===r);if(!a){let s=G.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${s}`)}if(!a.canHandle(o))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${a.getName()}`),a}async function Vt(o,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},a={...e,state:r},s=nt(a),n=r.config||t.config||{},i=n.models||{},u=t.nodeName&&i[t.nodeName]||null,d=i.default||null,h=n.agent?.[s.name]?.model||null,l=u||d||h||t.model||null,c={...t,model:l,workspace:r.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],plugins:t.plugins||e.plugins||[],config:n},m=o,S=c.skills||[];if(S.length>0&&!t.skipPromptFragments){let E=S.map(g=>{let f=Q(g)?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);E.length>0&&(m+=`
1
+ var Ut=Object.defineProperty;var we=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var ae=(o,e)=>()=>(o&&(e=o(o=0)),e);var Je=(o,e)=>{for(var t in e)Ut(o,t,{get:e[t],enumerable:!0})};var Ye,Ft,ue,b,W=ae(()=>{Ye=()=>{},Ft={debug:Ye,info:Ye,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},ue={impl:Ft},b={debug:(...o)=>ue.impl.debug?.(...o),info:(...o)=>ue.impl.info?.(...o),warn:(...o)=>ue.impl.warn?.(...o),error:(...o)=>ue.impl.error?.(...o)}});var rt=ae(()=>{});var nt={};Je(nt,{clearSkills:()=>Kt,getAllSkills:()=>Zt,getSkill:()=>ee,getSkillSource:()=>zt,hasSkill:()=>Yt,listSkillIds:()=>qt,registerSkill:()=>Jt});function Jt(o,e={}){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:r=!1}=e,s=o.id;if(F.has(s)&&!r){let i=Q.get(s);if(!(i===t)){let a=i||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${s}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}F.set(s,Object.freeze({...o})),t===void 0?Q.delete(s):Q.set(s,t)}function ee(o){return F.get(o)||null}function Yt(o){return F.has(o)}function zt(o){return Q.get(o)||null}function Zt(){return new Map(F)}function qt(){return Array.from(F.keys())}function Kt(){F.clear(),Q.clear()}var $e,ve,F,Q,pe=ae(()=>{$e=Symbol.for("@zibby/agent-workflow.skills"),ve=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[$e]||(globalThis[$e]=new Map);globalThis[ve]||(globalThis[ve]=new Map);F=globalThis[$e],Q=globalThis[ve]});var te={};Je(te,{getAgentStrategy:()=>st,invokeAgent:()=>Qt,listStrategies:()=>Xt,registerStrategy:()=>Vt});function Vt(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=G.findIndex(t=>t.getName()===o.getName());e>=0?G[e]=o:G.push(o)}function Xt(){return G.map(o=>o.getName())}function st(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let i=G.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}b.debug(`[workflow] agent selection: requested=${r}`);let s=G.find(i=>i.getName()===r);if(!s){let i=G.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!s.canHandle(o))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return b.debug(`[workflow] using agent: ${s.getName()}`),s}async function Qt(o,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:r},i=st(s),n=r.config||t.config||{},a=n.models||{},u=t.nodeName&&a[t.nodeName]||null,d=a.default||null,h=n.agent?.[i.name]?.model||null,l=u||d||h||t.model||null,c={...t,model:l,workspace:r.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],plugins:t.plugins||e.plugins||[],config:n},m=o,y=c.skills||[];if(y.length>0&&!t.skipPromptFragments){let I=y.map(g=>{let f=ee(g)?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);I.length>0&&(m+=`
2
2
 
3
- ${E.join(`
3
+ ${I.join(`
4
4
 
5
- `)}`)}let _=r._currentNodeConfig?.stores;if(Array.isArray(_)&&_.length>0&&typeof _[0]=="object"){let E=_.length<=8,g=_.map(f=>{let y=f?.id??f?.storeId??"",p=(f?.name??"").toString().trim()||y,b=f?.type?` \xB7 ${f.type}`:"",A=(f?.description||"").toString().replace(/\s+/g," ").trim(),R=`- ${p} \xB7 ${A||"(no description)"}${b} (id: ${y})`;if(E&&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&&(R+=`
5
+ `)}`)}let _=r._currentNodeConfig?.stores;if(Array.isArray(_)&&_.length>0&&typeof _[0]=="object"){let I=_.length<=8,g=_.map(f=>{let S=f?.id??f?.storeId??"",p=(f?.name??"").toString().trim()||S,E=f?.type?` \xB7 ${f.type}`:"",k=(f?.description||"").toString().replace(/\s+/g," ").trim(),R=`- ${p} \xB7 ${k||"(no description)"}${E} (id: ${S})`;if(I&&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&&(R+=`
6
6
  fields: ${w.join(", ")}`)}return R});m+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
@@ -14,37 +14,37 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
14
14
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
15
15
 
16
16
  ${v}
17
- `),I.debug(`[workflow] prompt length: ${m.length} chars`),s.invoke(m,c)}var $e,G,te=ie(()=>{ot();W();de();$e=Symbol.for("@zibby/agent-workflow.strategies");globalThis[$e]||(globalThis[$e]=[]);G=globalThis[$e]});var Ut=new Set(["__proto__","constructor","prototype"]);function we(o){if(Ut.has(o))throw new Error(`Invalid state key: "${o}"`)}var ae=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){we(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)we(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){we(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 F from"handlebars";var ce=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(a=>a[0]);for(let a of r)try{return this.validate(JSON.parse(a))}catch(s){if(!(s instanceof SyntaxError))throw s}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,a]of Object.entries(this.schema)){if(a.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&a.type){let s=typeof e[r];s!==a.type&&t.push(`Field '${r}' expected ${a.type}, got ${s}`)}if(a.validate&&r in e){let s=a.validate(e[r]);s&&t.push(`Field '${r}': ${s}`)}}if(t.length>0)throw new Error(`Output validation failed:
17
+ `),b.debug(`[workflow] prompt length: ${m.length} chars`),i.invoke(m,c)}var Te,G,oe=ae(()=>{rt();W();pe();Te=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Te]||(globalThis[Te]=[]);G=globalThis[Te]});var Wt=new Set(["__proto__","constructor","prototype"]);function _e(o){if(Wt.has(o))throw new Error(`Invalid state key: "${o}"`)}var ce=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){_e(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)_e(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){_e(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 H from"handlebars";var le=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of r)try{return this.validate(JSON.parse(s))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,s]of Object.entries(this.schema)){if(s.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&s.type){let i=typeof e[r];i!==s.type&&t.push(`Field '${r}' expected ${s.type}, got ${i}`)}if(s.validate&&r in e){let i=s.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}};W();import{writeFileSync as ve,readFileSync as st,existsSync as it,mkdirSync as Xt}from"node:fs";import{join as Te,dirname as Qt}from"node:path";import x from"chalk";var Gt="__WORKFLOW_GRAPH_LOG__",X=x.gray("\u2502"),Ft=x.gray("\u250C"),Je=x.gray("\u2514"),_e=x.green("\u25C6"),Ye=x.hex("#c084fc")("\u25C6"),Ze=x.hex("#2dd4bf")("\u25C6"),Ie=x.red("\u25C6"),ze=`${X} `,Ke=2;function qe(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function Ve(o,e){return(t,r,a)=>{if(typeof t!="string")return o(t,r,a);let s=process.stdout.columns||120,n="";for(let i=0;i<t.length;i++){let u=t[i];e.lineStart&&(n+=ze,e.col=Ke,e.lineStart=!1),u===`
20
- `?(n+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,n+=u):e.inEsc?(n+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,n+=u,e.col>=s&&(n+=`
21
- ${ze}`,e.col=Ke))}return o(n,r,a)}}var Ee=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=Ve(this._origStdoutWrite,e),process.stderr.write=Ve(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
19
+ `)}`);return e}};W();import{writeFileSync as ke,readFileSync as it,existsSync as at,mkdirSync as eo}from"node:fs";import{join as Ae,dirname as to}from"node:path";import x from"chalk";var Gt="__WORKFLOW_GRAPH_LOG__",X=x.gray("\u2502"),Ht=x.gray("\u250C"),ze=x.gray("\u2514"),be=x.green("\u25C6"),Ze=x.hex("#c084fc")("\u25C6"),qe=x.hex("#2dd4bf")("\u25C6"),Ie=x.red("\u25C6"),Ke=`${X} `,Ve=2;function Xe(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function Qe(o,e){return(t,r,s)=>{if(typeof t!="string")return o(t,r,s);let i=process.stdout.columns||120,n="";for(let a=0;a<t.length;a++){let u=t[a];e.lineStart&&(n+=Ke,e.col=Ve,e.lineStart=!1),u===`
20
+ `?(n+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,n+=u):e.inEsc?(n+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,n+=u,e.col>=i&&(n+=`
21
+ ${Ke}`,e.col=Ve))}return o(n,r,s)}}var Ee=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=Qe(this._origStdoutWrite,e),process.stderr.write=Qe(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
22
22
  `),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
23
23
  `),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
24
24
  `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Gt}${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(_e,e):process.stdout.write.bind(process.stdout)(`${X} ${_e} ${e}
29
- `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Ye,e):process.stdout.write.bind(process.stdout)(`${X} ${Ye} ${e}
30
- `)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(Ze,t):process.stdout.write.bind(process.stdout)(`${X} ${Ze} ${t}
28
+ `)}step(e){this._origStdoutWrite?this._writeDot(be,e):process.stdout.write.bind(process.stdout)(`${X} ${be} ${e}
29
+ `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Ze,e):process.stdout.write.bind(process.stdout)(`${X} ${Ze} ${e}
30
+ `)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(qe,t):process.stdout.write.bind(process.stdout)(`${X} ${qe} ${t}
31
31
  `)}stepFail(e){this._origStdoutWrite?this._writeDot(Ie,x.red(e)):process.stdout.write.bind(process.stdout)(`${X} ${Ie} ${x.red(e)}
32
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Ft} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:a}=t;if(a)for(let n of a)this._rawWrite(`${_e} ${n}`);let s=r?x.dim(` ${qe(r)}`):"";this._rawWrite(`${Je} ${x.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:a}=r,s=a?x.dim(` ${qe(a)}`):"";this._rawWrite(`${Ie} ${x.red(t)}`),this._rawWrite(`${Je} ${x.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},O=new Ee;var ue=".zibby/output",Qe="sessions",K=".session-info.json",et=".zibby-stop";var Xe={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",DISCORD:"discord",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder",SESSION:"session",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE_DOCS:"google-docs",LARK_DOCS:"lark-docs",DOC_SOURCE:"doc_source",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent",CODE_SCAN:"code-scan"},Ho=Object.freeze([Xe.CODEBASE_MEMORY,Xe.CODE_SCAN]),tt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];F.helpers.inc||F.registerHelper("inc",o=>Number(o)+1);F.helpers.json||F.registerHelper("json",o=>JSON.stringify(o,null,2));F.helpers.eq||F.registerHelper("eq",(o,e)=>o===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new ce(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 I.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,a=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(I.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){return I.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=F.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let n=a("_skillHints");n&&(s=`${n}
32
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Ht} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:s}=t;if(s)for(let n of s)this._rawWrite(`${be} ${n}`);let i=r?x.dim(` ${Xe(r)}`):"";this._rawWrite(`${ze} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:s}=r,i=s?x.dim(` ${Xe(s)}`):"";this._rawWrite(`${Ie} ${x.red(t)}`),this._rawWrite(`${ze} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},O=new Ee;var de=".zibby/output",et="sessions",K=".session-info.json",tt=".zibby-stop";var Yo=Object.freeze(["codebase-memory","code-scan"]),ot=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];H.helpers.inc||H.registerHelper("inc",o=>Number(o)+1);H.helpers.json||H.registerHelper("json",o=>JSON.stringify(o,null,2));H.helpers.eq||H.registerHelper("eq",(o,e)=>o===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new le(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return b.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){b.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(b.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){return b.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&b.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=H.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(r())):i=this.prompt;let n=s("_skillHints");n&&(i=`${n}
33
33
 
34
- ${s}`);let i=r(),u=i.cwd||process.cwd(),d=i.sessionPath;try{if(d){let l=Te(d,K);if(it(l)){let m=JSON.parse(st(l,"utf-8"));m.currentNode=this.name,ve(l,JSON.stringify(m,null,2),"utf-8")}let c=Te(d,"..",K);if(it(c))try{let m=JSON.parse(st(c,"utf-8"));m.currentNode=this.name,ve(c,JSON.stringify(m,null,2),"utf-8")}catch{}}}catch(l){I.debug(`[workflow] could not update session info: ${l.message}`)}let h=null;for(let l=0;l<=this.retries;l++)try{I.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=r().config||{},m=c.agents||{},S=this.config.agent??m[this.name]??null,_={state:r()};S&&(_.preferredAgent=S);let v={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},E=e?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let g=await E(s,_,v),f,y;if(typeof g=="string"?(f=g,y=null):g.structured?(f=g.raw||JSON.stringify(g.structured,null,2),y=g.structured):(f=g.raw||JSON.stringify(g,null,2),y=g.extracted||null),d)try{let p=Te(d,this.name,"raw_stream_output.txt");Xt(Qt(p),{recursive:!0}),ve(p,typeof f=="string"?f:JSON.stringify(f),"utf-8")}catch(p){I.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&y){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let p=y;if(typeof this.onComplete=="function")try{p=await this.onComplete(r(),y)}catch(b){I.warn(`[workflow] onComplete hook failed: ${b.message}`)}return{success:!0,output:p,raw:f}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:f}),raw:f}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(f);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),O.step("Output parsed"),{success:!0,output:p,raw:f}}return{success:!0,output:f,raw:f}}catch(c){h=c,l<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};W();W();import{mkdirSync as oo,existsSync as J,statSync as gt,readdirSync as mt,rmSync as ro}from"node:fs";import{spawn as pt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as no}from"node:url";import{AsyncLocalStorage as so}from"node:async_hooks";import{AsyncLocalStorage as eo}from"node:async_hooks";var Ae=new eo;function oe(){let o=Ae.getStore();return o||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})}function at(o,e){let t=Ae.getStore()||oe(),r=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null});return Ae.run(r,e)}var ke=new Map,xe=new Map,ct=new Map;function lt(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");ke.set(o,e),xe.set(o,"ready"),ct.set(o,{...t,cachedAt:Date.now()})}function ut(o,e){xe.set(o,"failed"),ct.set(o,{error:e?.message||String(e),failedAt:Date.now()}),ke.delete(o)}function dt(o){return xe.get(o)==="ready"?ke.get(o):null}var pe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function io(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}},ft=new so,ht=Promise.resolve();async function ao(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([n,i])=>typeof n=="string"&&n&&typeof i=="string"):[];if(t.length===0)return e();let r=ft.getStore()===!0,a=null;if(!r){let n=ht;ht=new Promise(i=>{a=i}),await n}let s=new Map;try{for(let[n,i]of t)s.set(n,Object.prototype.hasOwnProperty.call(process.env,n)?process.env[n]:void 0),process.env[n]=i;return I.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await ft.run(!0,e)}finally{for(let[n,i]of s)i===void 0?delete process.env[n]:process.env[n]=i;a&&a()}}function co(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,r=process.env.PROJECT_ID,a=process.env.PROJECT_API_TOKEN;if(!t||!r||!a)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:a}}async function lo({apiBase:o,authToken:e,body:t}){let r;try{r=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(s){throw new N("network",`begin fetch failed: ${s.message}`)}let a=null;try{a=await r.json()}catch{}if(!r.ok){if(r.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(r.status===429){let s=a?.quotaInfo||{},n=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw n.code="SUBGRAPH_QUOTA_EXCEEDED",n.status=429,n.quotaInfo=s,n}if(r.status===400&&a?.validationErrors){let s=new Error(`Sub-graph rejected input: ${a?.error||a?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=a.validationErrors,s.missing=a.missing,s}throw new N("begin-status",`begin returned ${r.status}`)}return a?.data||a}async function H({apiBase:o,authToken:e,payload:t}){try{let r=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});r.ok||I.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){I.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function uo(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(J(t)&&J(r))return;oo(e,{recursive:!0});let a=U(e,".lock"),s=!1;try{let{openSync:n,closeSync:i}=await import("node:fs"),u=n(a,"wx");i(u),s=!0}catch(n){if(n.code!=="EEXIST")throw n}if(!s){let n=Date.now()+3e4;for(;Date.now()<n;){if(J(t)&&J(r))return;await new Promise(i=>setTimeout(i,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let h=pt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),l=pt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(l.stdin);let c,m,S=()=>{if(c!==void 0&&m!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(m!==0)return d(new Error(`tar exited ${m}`));u()}};h.on("close",_=>{c=_,S()}),l.on("close",_=>{m=_,S()}),h.on("error",d),l.on("error",d)});let{writeFileSync:n,unlinkSync:i}=await import("node:fs");n(t,"");try{i(a)}catch{}}catch(n){try{let{unlinkSync:i}=await import("node:fs");i(a)}catch{}throw new N("bundle-extract-failed",n.message)}}async function po(o){let e=U(o,"graph.mjs");if(!J(e))throw new N("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(no(e).href)}catch(a){throw new N("import-failed",`${a?.code||a?.name||"unknown"}: ${a.message}`)}let r=t.default||Object.values(t).find(a=>typeof a=="function"&&a.prototype?.buildGraph);if(!r)throw new N("entry-class-missing","no buildGraph() class export found");return r}async function St(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=oe(),r;try{r=co()}catch(p){throw p}I.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let a=await lo({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:s,runtimeTag:n,bundlePresignedUrl:i,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:h,bundleReady:l,nodeConfigs:c}=a,m=io();if(n&&n!==m)throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:`runtimeTag mismatch: parent=${m} child=${n}`,code:"RUNTIME_MISMATCH"}}}),new N("runtime-mismatch",`${m} vs ${n}`);if(!l||!i)throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new N("no-bundle","workflow bundle not built yet");let S=dt(o);if(!S){let p=U(pe,`${h}@${d||"0"}`);try{await uo(i,p);try{ho()}catch{}}catch(b){throw b.fallback&&await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:b.message,code:b.reason}}}),b}try{S=await po(p),lt(o,S,{workflowUuid:h,version:d,runtimeTag:n,cacheDir:p})}catch(b){throw ut(o,b),await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:b.message,code:b.reason||"IMPORT_FAILED"}}}),b.fallback?b:new N("import-failed",b.message)}}let _=Date.now(),v=a.env&&typeof a.env=="object"&&!Array.isArray(a.env)?a.env:null,E=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,g={...e.input||{},...E?{nodeConfigs:c}:{}},f,y;try{f=await ao(v,async()=>{let b=await(typeof S=="function"&&S.prototype?.buildGraph?new S:S).buildGraph();return at({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>b.run(e.parentAgent,g,{signal:e.signal}))}),y=f&&typeof f=="object"&&"state"in f?f.state:f}catch(p){throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-_}}),p}if(f&&typeof f=="object"&&f.stoppedExternally){await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",finalState:y,durationMs:Date.now()-_}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=s,p}return await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"completed",finalState:y,durationMs:Date.now()-_}}),{finalState:y,executionId:s}}function fo(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),a;try{a=gt(r)}catch{continue}if(a.isDirectory()){let s;try{s=mt(r)}catch{continue}for(let n of s)t.push(U(r,n))}else e+=a.size}return e}function ho({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!J(pe))return{evicted:0,freedBytes:0};let e=mt(pe),t=[],r=0;for(let i of e){let u=U(pe,i),d;try{d=gt(u)}catch{continue}let h=d.isDirectory()?fo(u):d.size;r+=h,t.push({name:i,full:u,size:h,mtimeMs:d.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((i,u)=>i.mtimeMs-u.mtimeMs);let a=Math.floor(o*.7),s=0,n=0;for(let i of t){if(r-s<=a)break;if(!J(U(i.full,".lock")))try{ro(i.full,{recursive:!0,force:!0}),s+=i.size,n+=1}catch(u){I.debug(`[sub-graph cache] evict skip ${i.name}: ${u.message}`)}}return n>0&&I.info(`[sub-graph cache] evicted ${n} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:n,freedBytes:s,totalBytes:r-s}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var go=2e3,mo=600*1e3,So=new Set(["completed","failed","canceled","timeout"]);function yo(){let o=process.env.PROGRESS_API_URL;if(!o)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 o.replace(/\/executions\/?$/,"")}function wo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function _o(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Io(){return process.env.EXECUTION_ID||null}function yt(o,e){return e==null?o:typeof e=="function"?e(o):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],o):o}async function wt(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=oe(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:y}=await St(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=yt(y,e.output);return I.info(`[sub-graph] '${o}' completed in-process`),p}catch(y){if(y instanceof N||y?.fallback)I.info(`[sub-graph] in-process fallback for '${o}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let a=yo(),s=wo(),n=_o(),i=Io(),u=`${a}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(o)}/trigger`,d={input:e.input||{},...i?{parentExecutionId:i}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${i||"<none>"}`);let h=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(d)});if(!h.ok){let y=null,p="";try{y=await h.json(),p=y?.error||y?.message||JSON.stringify(y)}catch{p=await h.text().catch(()=>"")}if(h.status===429){let A=y?.quotaInfo||{},R=new Error(`Sub-graph '${o}' blocked by execution quota (${A.used??"?"}/${A.limit??"?"} on plan ${A.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw R.code="SUBGRAPH_QUOTA_EXCEEDED",R.status=429,R.subgraph=o,R.quotaInfo=A,R}if(h.status===400){let A=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw A.code="SUBGRAPH_INVALID_INPUT",A.status=400,A.subgraph=o,A.validationErrors=y?.validationErrors||null,A.missing=y?.missing||null,A}let b=new Error(`Sub-graph '${o}' trigger rejected (${h.status}): ${p}`);throw b.code="SUBGRAPH_TRIGGER_FAILED",b.status=h.status,b.subgraph=o,b}let l=await h.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let m=Number.isFinite(e.timeoutMs)?e.timeoutMs:mo,S=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:go,_=`${a}/executions/${encodeURIComponent(c)}`,v=Date.now()+m,E="accepted",g=0;for(;Date.now()<v;){await new Promise(A=>setTimeout(A,S)),g+=1;let y=await fetch(_,{headers:{Authorization:`Bearer ${n}`}});if(!y.ok){if(y.status>=500){I.warn(`[sub-graph] status poll for ${c} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${y.status}`)}let p=await y.json(),b=p?.data||p?.execution||p;if(E=b?.status||E,So.has(E)){if(E!=="completed"){let w=new Error(`Sub-graph '${o}' (${c}) ended in status '${E}'`);throw w.subgraphJobId=c,w.subgraphStatus=E,w}let A=b?.finalState||b?.state||{},R=yt(A,e.output);return I.info(`[sub-graph] '${o}' (${c}) completed after ${g} polls`),R}}let f=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(m/1e3)}s (last status: ${E})`);throw f.subgraphJobId=c,f.subgraphStatus=E,f}import{existsSync as _t,readFileSync as Eo}from"node:fs";import{join as Oe,dirname as It}from"node:path";var fe=class{static async loadContext(e,t,r={}){let a={},s=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let i=It(Oe(t,e));for(let u of s){let d=await this.findAndMergeContextFiles(u,i,t);if(d){let h=u.replace(/\.[^.]+$/,"").toLowerCase();a[h]=d}}}let n=r.discovery||{};for(let[i,u]of Object.entries(n))try{let d=Oe(t,u);_t(d)&&(a[i]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${i}' from '${u}': ${d.message}`)}return a}static async findAndMergeContextFiles(e,t,r){let a=[],s=t;for(;s.startsWith(r);){let n=Oe(s,e);if(_t(n))try{a.unshift(await this.loadFile(n))}catch(u){console.warn(`[workflow] could not load ${e} from ${n}: ${u.message}`)}let i=It(s);if(i===s)break;s=i}return a.length===0?null:a.every(n=>typeof n=="string")?a.join(`
34
+ ${i}`);let a=r(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Ae(d,K);if(at(l)){let m=JSON.parse(it(l,"utf-8"));m.currentNode=this.name,ke(l,JSON.stringify(m,null,2),"utf-8")}let c=Ae(d,"..",K);if(at(c))try{let m=JSON.parse(it(c,"utf-8"));m.currentNode=this.name,ke(c,JSON.stringify(m,null,2),"utf-8")}catch{}}}catch(l){b.debug(`[workflow] could not update session info: ${l.message}`)}let h=null;for(let l=0;l<=this.retries;l++)try{b.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=r().config||{},m=c.agents||{},y=this.config.agent??m[this.name]??null,_={state:r()};y&&(_.preferredAgent=y);let v={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},I=e?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(oe(),te))).invokeAgent);let g=await I(i,_,v),f,S;if(typeof g=="string"?(f=g,S=null):g.structured?(f=g.raw||JSON.stringify(g.structured,null,2),S=g.structured):(f=g.raw||JSON.stringify(g,null,2),S=g.extracted||null),d)try{let p=Ae(d,this.name,"raw_stream_output.txt");eo(to(p),{recursive:!0}),ke(p,typeof f=="string"?f:JSON.stringify(f),"utf-8")}catch(p){b.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&S){b.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(S,null,2)}`);let p=S;if(typeof this.onComplete=="function")try{p=await this.onComplete(r(),S)}catch(E){b.warn(`[workflow] onComplete hook failed: ${E.message}`)}return{success:!0,output:p,raw:f}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:f}),raw:f}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(f);return b.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),O.step("Output parsed"),{success:!0,output:p,raw:f}}return{success:!0,output:f,raw:f}}catch(c){h=c,l<this.retries&&b.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};W();W();import{mkdirSync as no,existsSync as Y,statSync as mt,readdirSync as yt,rmSync as so}from"node:fs";import{spawn as ft}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as io}from"node:url";import{AsyncLocalStorage as ao}from"node:async_hooks";import{AsyncLocalStorage as oo}from"node:async_hooks";var xe=new oo;function re(){let o=xe.getStore();return o||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})}function ct(o,e){let t=xe.getStore()||re(),r=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null});return xe.run(r,e)}var Oe=new Map,Pe=new Map,lt=new Map;function ut(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Oe.set(o,e),Pe.set(o,"ready"),lt.set(o,{...t,cachedAt:Date.now()})}function dt(o,e){Pe.set(o,"failed"),lt.set(o,{error:e?.message||String(e),failedAt:Date.now()}),Oe.delete(o)}function pt(o){return Pe.get(o)==="ready"?Oe.get(o):null}var fe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function co(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var P=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"}},ht=new ao,gt=Promise.resolve();async function lo(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([n,a])=>typeof n=="string"&&n&&typeof a=="string"):[];if(t.length===0)return e();let r=ht.getStore()===!0,s=null;if(!r){let n=gt;gt=new Promise(a=>{s=a}),await n}let i=new Map;try{for(let[n,a]of t)i.set(n,Object.prototype.hasOwnProperty.call(process.env,n)?process.env[n]:void 0),process.env[n]=a;return b.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await ht.run(!0,e)}finally{for(let[n,a]of i)a===void 0?delete process.env[n]:process.env[n]=a;s&&s()}}function uo(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,r=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!r||!s)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:s}}async function po({apiBase:o,authToken:e,body:t}){let r;try{r=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(i){throw new P("network",`begin fetch failed: ${i.message}`)}let s=null;try{s=await r.json()}catch{}if(!r.ok){if(r.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(r.status===429){let i=s?.quotaInfo||{},n=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw n.code="SUBGRAPH_QUOTA_EXCEEDED",n.status=429,n.quotaInfo=i,n}if(r.status===400&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new P("begin-status",`begin returned ${r.status}`)}return s?.data||s}async function J({apiBase:o,authToken:e,payload:t}){try{let r=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});r.ok||b.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){b.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function fo(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(Y(t)&&Y(r))return;no(e,{recursive:!0});let s=U(e,".lock"),i=!1;try{let{openSync:n,closeSync:a}=await import("node:fs"),u=n(s,"wx");a(u),i=!0}catch(n){if(n.code!=="EEXIST")throw n}if(!i){let n=Date.now()+3e4;for(;Date.now()<n;){if(Y(t)&&Y(r))return;await new Promise(a=>setTimeout(a,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let h=ft("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),l=ft("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(l.stdin);let c,m,y=()=>{if(c!==void 0&&m!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(m!==0)return d(new Error(`tar exited ${m}`));u()}};h.on("close",_=>{c=_,y()}),l.on("close",_=>{m=_,y()}),h.on("error",d),l.on("error",d)});let{writeFileSync:n,unlinkSync:a}=await import("node:fs");n(t,"");try{a(s)}catch{}}catch(n){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new P("bundle-extract-failed",n.message)}}async function ho(o){let e=U(o,"graph.mjs");if(!Y(e))throw new P("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(io(e).href)}catch(s){throw new P("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let r=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!r)throw new P("entry-class-missing","no buildGraph() class export found");return r}async function St(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=re(),r;try{r=uo()}catch(p){throw p}b.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let s=await po({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:n,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:h,bundleReady:l,nodeConfigs:c}=s,m=co();if(n&&n!==m)throw await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:`runtimeTag mismatch: parent=${m} child=${n}`,code:"RUNTIME_MISMATCH"}}}),new P("runtime-mismatch",`${m} vs ${n}`);if(!l||!a)throw await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new P("no-bundle","workflow bundle not built yet");let y=pt(o);if(!y){let p=U(fe,`${h}@${d||"0"}`);try{await fo(a,p);try{mo()}catch{}}catch(E){throw E.fallback&&await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:E.message,code:E.reason}}}),E}try{y=await ho(p),ut(o,y,{workflowUuid:h,version:d,runtimeTag:n,cacheDir:p})}catch(E){throw dt(o,E),await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:E.message,code:E.reason||"IMPORT_FAILED"}}}),E.fallback?E:new P("import-failed",E.message)}}let _=Date.now(),v=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,I=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,g={...e.input||{},...I?{nodeConfigs:c}:{}},f,S;try{f=await lo(v,async()=>{let E=await(typeof y=="function"&&y.prototype?.buildGraph?new y:y).buildGraph();return ct({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>E.run(e.parentAgent,g,{signal:e.signal}))}),S=f&&typeof f=="object"&&"state"in f?f.state:f}catch(p){throw await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-_}}),p}if(f&&typeof f=="object"&&f.stoppedExternally){await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",finalState:S,durationMs:Date.now()-_}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:S,durationMs:Date.now()-_}}),{finalState:S,executionId:i}}function go(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),s;try{s=mt(r)}catch{continue}if(s.isDirectory()){let i;try{i=yt(r)}catch{continue}for(let n of i)t.push(U(r,n))}else e+=s.size}return e}function mo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(fe))return{evicted:0,freedBytes:0};let e=yt(fe),t=[],r=0;for(let a of e){let u=U(fe,a),d;try{d=mt(u)}catch{continue}let h=d.isDirectory()?go(u):d.size;r+=h,t.push({name:a,full:u,size:h,mtimeMs:d.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let s=Math.floor(o*.7),i=0,n=0;for(let a of t){if(r-i<=s)break;if(!Y(U(a.full,".lock")))try{so(a.full,{recursive:!0,force:!0}),i+=a.size,n+=1}catch(u){b.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return n>0&&b.info(`[sub-graph cache] evicted ${n} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:n,freedBytes:i,totalBytes:r-i}}catch(e){return b.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var yo=2e3,So=600*1e3,wo=new Set(["completed","failed","canceled","timeout"]);function _o(){let o=process.env.PROGRESS_API_URL;if(!o)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 o.replace(/\/executions\/?$/,"")}function bo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Io(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Eo(){return process.env.EXECUTION_ID||null}function wt(o,e){return e==null?o:typeof e=="function"?e(o):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],o):o}async function _t(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=re(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{b.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:S}=await St(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=wt(S,e.output);return b.info(`[sub-graph] '${o}' completed in-process`),p}catch(S){if(S instanceof P||S?.fallback)b.info(`[sub-graph] in-process fallback for '${o}': ${S.reason||"unknown"} \u2014 using HTTP`);else throw S}let s=_o(),i=bo(),n=Io(),a=Eo(),u=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(o)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};b.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let h=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(d)});if(!h.ok){let S=null,p="";try{S=await h.json(),p=S?.error||S?.message||JSON.stringify(S)}catch{p=await h.text().catch(()=>"")}if(h.status===429){let k=S?.quotaInfo||{},R=new Error(`Sub-graph '${o}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw R.code="SUBGRAPH_QUOTA_EXCEEDED",R.status=429,R.subgraph=o,R.quotaInfo=k,R}if(h.status===400){let k=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=o,k.validationErrors=S?.validationErrors||null,k.missing=S?.missing||null,k}let E=new Error(`Sub-graph '${o}' trigger rejected (${h.status}): ${p}`);throw E.code="SUBGRAPH_TRIGGER_FAILED",E.status=h.status,E.subgraph=o,E}let l=await h.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return b.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let m=Number.isFinite(e.timeoutMs)?e.timeoutMs:So,y=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:yo,_=`${s}/executions/${encodeURIComponent(c)}`,v=Date.now()+m,I="accepted",g=0;for(;Date.now()<v;){await new Promise(k=>setTimeout(k,y)),g+=1;let S=await fetch(_,{headers:{Authorization:`Bearer ${n}`}});if(!S.ok){if(S.status>=500){b.warn(`[sub-graph] status poll for ${c} returned ${S.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${S.status}`)}let p=await S.json(),E=p?.data||p?.execution||p;if(I=E?.status||I,wo.has(I)){if(I!=="completed"){let w=new Error(`Sub-graph '${o}' (${c}) ended in status '${I}'`);throw w.subgraphJobId=c,w.subgraphStatus=I,w}let k=E?.finalState||E?.state||{},R=wt(k,e.output);return b.info(`[sub-graph] '${o}' (${c}) completed after ${g} polls`),R}}let f=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(m/1e3)}s (last status: ${I})`);throw f.subgraphJobId=c,f.subgraphStatus=I,f}import{existsSync as bt,readFileSync as $o}from"node:fs";import{join as Ne,dirname as It}from"node:path";var he=class{static async loadContext(e,t,r={}){let s={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=It(Ne(t,e));for(let u of i){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let h=u.replace(/\.[^.]+$/,"").toLowerCase();s[h]=d}}}let n=r.discovery||{};for(let[a,u]of Object.entries(n))try{let d=Ne(t,u);bt(d)&&(s[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return s}static async findAndMergeContextFiles(e,t,r){let s=[],i=t;for(;i.startsWith(r);){let n=Ne(i,e);if(bt(n))try{s.unshift(await this.loadFile(n))}catch(u){console.warn(`[workflow] could not load ${e} from ${n}: ${u.message}`)}let a=It(i);if(a===i)break;i=a}return s.length===0?null:s.every(n=>typeof n=="string")?s.join(`
35
35
 
36
36
  ---
37
37
 
38
- `):a.every(n=>typeof n=="object")?Object.assign({},...a):a[a.length-1]}static async loadFile(e){let t=Eo(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),a=await import(r(e).href);return a.default||a}return t}};import{mkdirSync as $t,existsSync as Ne,writeFileSync as Et,unlinkSync as bo}from"node:fs";import{join as Y,resolve as vt}from"node:path";import{config as $o}from"dotenv";import{zodToJsonSchema as bt}from"zod-to-json-schema";import{z as he}from"zod";import vo from"handlebars";function To({traceFrom:o,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:a}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let n=typeof process.ppid=="number"?process.ppid:"n/a",i=`[zibby:session] from=${o} pid=${process.pid} ppid=${n} sessionId=${e} source=${r} mkdir=${a?"yes":"no"} path=${t}`;if(console.log(i),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let h=(new Error("session trace").stack||"").split(`
38
+ `):s.every(n=>typeof n=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=$o(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),s=await import(r(e).href);return s.default||s}return t}};import{mkdirSync as vt,existsSync as Ce,writeFileSync as Et,unlinkSync as vo}from"node:fs";import{join as z,resolve as Tt}from"node:path";import{config as To}from"dotenv";import{zodToJsonSchema as $t}from"zod-to-json-schema";import{z as ge}from"zod";import ko from"handlebars";function Ao({traceFrom:o,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let n=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${o} pid=${process.pid} ppid=${n} sessionId=${e} source=${r} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let h=(new Error("session trace").stack||"").split(`
39
39
  `).slice(2,14).join(`
40
40
  `);console.log(`[zibby:session] stack (${o}):
41
- ${h}`)}}function Ao(){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 ko(){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 vt(String(e).trim())}catch{return String(e).trim()}}function xo(){Ao()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Oo({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function No(o={}){let e=tt.map(s=>process.env[s]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,a=o.paths?.sessionPrefix;return a?`${a}_${r}`:r}function Po({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let a=t.sessionPath,s=t.sessionTimestamp,n="initialState.sessionPath";if(!a&&process.env.ZIBBY_SESSION_PATH)try{let d=vt(String(process.env.ZIBBY_SESSION_PATH));d&&(a=d,n="ZIBBY_SESSION_PATH")}catch{}let i;if(a)i=String(a).split(/[/\\]/).filter(Boolean).pop(),s==null&&(s=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)i=d,n="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(i=l,n="config.sessionId"):(i=No(e),n="generated")}s=s??Date.now();let h=e.paths?.output||ue;a=Y(o,h,Qe,i)}let u=!Ne(a);return u&&$t(a,{recursive:!0}),(u||n!=="initialState.sessionPath")&&To({traceFrom:r,sessionId:i,sessionPath:a,idSource:n,mkdirFresh:u}),Oo({sessionPath:a,sessionId:i}),{sessionPath:a,sessionId:i,sessionTimestamp:s}}var ge=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 L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let n=t,i={name:e,_isCustomCode:!0,dispatchesWorkflow:n.workflow,retries:n.retries,onComplete:n.onComplete,execute:async d=>{let h=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof n.input=="function"?l=n.input(h):n.input&&typeof n.input=="object"?l=n.input:l={},wt(n.workflow,{input:l,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(h):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:h?._signal,parentAgent:d?.agent})}},u=new L(i);return u.name=e,this.nodes.set(e,u),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let a=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,s=t instanceof L?t:new L(a?{...t,_isRouter:!0}:t);return s.name=e,this.nodes.set(e,s),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){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,a,s){let n=r;for(let i=e.length-1;i>=0;i--){let u=e[i],d=n;n=()=>u(t,d,a,s)}return n()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let m=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:m,data:{nodeType:m,label:l}});let S={};c._isCustomCode&&typeof c.execute=="function"&&(S.customCode=c.execute.toString());let _=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;_&&(S.description=_);let v=this.nodePrompts.get(l);if(v)S.prompt=v;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(S.prompt=p,S.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(S.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(S.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof he?.toJSONSchema=="function")try{p=he.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=bt(c.outputSchema,{target:"openApi3"})}catch{}S.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else S.outputSchema={schema:c.outputSchema};let E=(this.resolvedToolsMap||{})[l];E?.toolIds&&(S.tools=E.toolIds);let g=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;g&&g.length>0&&(S.skills=[...g]);let f=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;f&&f.length>0&&(S.plugins=f.map(p=>p&&typeof p=="object"?{...p}:p));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(S.stores=y.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(S).length>0&&(t[l]=S)}let r=[];for(let[l,c]of this.edges)if(typeof c=="string")r.push({source:l,target:c});else if(c.conditional){let m=this.conditionalCodeMap.get(l)||c.routes.toString(),S=this._inferConditionalTargets(c.routes,c.labels),_=c.labels||{},v=this.nodes.get(l),E=v?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!v,g=l;if(!E){let f=`${l}__branch`;e.push({id:f,type:"decision",data:{nodeType:"decision",label:f}}),r.push({source:l,target:f}),g=f}for(let f of S){let y={source:g,target:f,data:{conditionalCode:m}};_[f]&&(y.label=_[f]),r.push(y)}}let a=l=>{if(!l)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(l)}catch{}try{return bt(l,{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 s=0;for(let l of r)if(l.target==="END"){s+=1;let c=`END__${s}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){s+=1;let c=`END__${s}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:l,target:c})}let n=this._topoOrderNodes(e,r),i=this._runtimeSchema(),u=a(i||this.stateSchema),d=a(this.inputSchema),h=a(this.contextSchema);return{nodes:n,edges:r,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:h}}_topoOrderNodes(e,t){let r=new Map(e.map((l,c)=>[l.id,c])),a=new Map(e.map(l=>[l.id,l])),s=new Map(e.map(l=>[l.id,0])),n=new Map(e.map(l=>[l.id,[]]));for(let l of t)n.has(l.source)&&s.has(l.target)&&(n.get(l.source).push(l.target),s.set(l.target,s.get(l.target)+1));let i=new Set,u=new Set(r.keys()),d=[...u].filter(l=>s.get(l)===0),h=[];for(;h.length<e.length;){let l;if(d.length>0){if(d.sort((c,m)=>r.get(c)-r.get(m)),l=d.shift(),i.has(l))continue}else l=[...u].sort((c,m)=>r.get(c)-r.get(m))[0];i.add(l),u.delete(l),h.push(a.get(l));for(let c of n.get(l)||[])s.set(c,s.get(c)-1),s.get(c)<=0&&!i.has(c)&&d.push(c)}return h}_inferConditionalTargets(e,t){let r=e.toString(),a=new Set,s=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,n;for(;(n=s.exec(r))!==null;){let d=n[2]!==void 0?n[2]:n[3];d!==void 0&&d!==""&&a.add(d)}let i=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())i.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))i.add(d);let u=new Set;for(let d of a)i.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=d.exec(r))!==null;)u.add(h[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let a=e.$ref.replace("#/definitions/","");r=e.definitions[a]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],a=e.properties||{},s=e.required||[];for(let[n,i]of Object.entries(a)){let u=t?`${t}.${n}`:n;r.push({path:u,type:i.type||"unknown",label:i.description||this._formatLabel(n),optional:!s.includes(n)}),i.type==="object"&&i.properties&&r.push(...this._flattenSchema(i,u)),i.type==="array"&&i.items?.type==="object"&&i.items.properties&&r.push(...this._flattenSchema(i.items,`${u}[]`))}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[a,s]of Object.entries(t))if(!(a==="success"||a==="raw"||a==="nextNode")){if(typeof s=="string"&&s.length<=80)r.push(`${a}: ${s}`);else if(Array.isArray(s)){let n=s.length,i=s.filter(d=>d?.passed===!0).length,u=s.some(d=>d?.passed!==void 0);r.push(u?`${a}: ${i}/${n} passed${n-i?`, ${n-i} failed`:""}`:`${a}: ${n} 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");let a=new AbortController;r.signal&&(r.signal.aborted?a.abort():r.signal.addEventListener("abort",()=>a.abort(),{once:!0}));let s=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,n=t.cwd||process.cwd();$o({path:Y(n,".env")});let i=t.config||{};if(!i||Object.keys(i).length===0)try{let $=Y(n,".zibby.config.js");Ne($)&&(i=(await import($)).default||{})}catch{}process.env.EXECUTION_ID&&!i.agent?.strictMode&&(i.agent={...i.agent,strictMode:!0});let u=t.agentType;if(!u){let $=i?.agent;$?.provider?u=$.provider:$?.gemini?u="gemini":$?.claude?u="claude":$?.cursor?u="cursor":$?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||i?.context||{},h=this._runtimeSchema();if(h){let $=h.safeParse(t);if(!$.success){let P=$.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}O.step("State validated against schema")}let l=ko(),c=t.sessionPath||l;c||xo();let{sessionPath:m,sessionTimestamp:S,sessionId:_}=Po({cwd:n,config:i,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${_}`);let v=await fe.loadContext(t.specPath||"",n,d);Object.keys(v).length>0&&O.step(`Context loaded: ${Object.keys(v).join(", ")}`);let E=t.outputPath;!E&&t.specPath&&(e?.calculateOutputPath?E=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let g=new ae({...t,config:i,agentType:u,outputPath:E,sessionPath:m,sessionTimestamp:S,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:a.signal}),f=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(de(),rt)),p=i.skills&&typeof i.skills=="object"?i.skills:{},b=Object.values(p).filter($=>$&&typeof $=="object"&&typeof $.id=="string"),A=$=>{for(let P of b)if(P.id===$)return P;return y($)},R=new Set;for(let[,$]of this.nodes)for(let P of $.config?.skills||[])R.add(P);for(let $ of R){let P=A($);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&f.set($,C)}catch{}}let w=this.entryPoint,re=[],Be=i?.recursionLimit??100,Ot=0;try{for(;w&&w!=="END";){if(++Ot>Be)throw new Error(`Workflow exceeded recursion limit (${Be}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=Y(m,et);if(Ne(P)){try{bo(P)}catch{}a.abort()}if(a.signal.aborted)return console.warn(`
42
- \u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:g.getAll(),executionLog:re,stoppedExternally:!0};let C=this.nodes.get(w);if(!C)throw new Error(`Node '${w}' not found in graph`);let Me=JSON.stringify({sessionPath:m,sessionTimestamp:S,currentNode:w,createdAt:new Date().toISOString(),config:g.get("config")}),Nt=Y(m,K);Et(Nt,Me,"utf-8");let De=g.get("config")?.paths?.output||ue,Pt=Y(n,De,K);$t(Y(n,De),{recursive:!0});try{Et(Pt,Me,"utf-8")}catch{}let je=t.onPipelineProgress;if(typeof je=="function")try{je({cwd:n,sessionPath:m,sessionId:_,outputBase:g.get("config")?.paths?.output||ue,currentNode:w})}catch{}let Ct=(this.resolvedToolsMap||{})[w]||null;g.set("_currentNodeTools",Ct);let Rt=g.get("nodeConfigs")||{};g.set("_currentNodeConfig",Rt[w]||{}),O.nodeStart(w);let Le=Date.now(),ne=this.nodePrompts.get(w);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(te(),ee));this._invokeAgent=k.invokeAgent}let Bt=this._invokeAgent,Se={},Mt=C.config?.skills||[];for(let k of Mt){let B=A(k);if(typeof B?.invokeAgentOptions=="function")try{let T=B.invokeAgentOptions(g.getAll(),{agentType:g.get("agentType"),nodeName:w});T&&typeof T=="object"&&(Se={...Se,...T})}catch(T){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${T.message}`)}}let Ue=async(k,B,T={})=>{let M=Bt(k,B,{...Se,...T,signal:a.signal});return M.catch(()=>{}),a.signal.aborted?M:Promise.race([M,new Promise((Z,z)=>{let j=()=>{setTimeout(()=>{let V=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${s}ms`);V.name="AbortError",z(V)},s)};a.signal.addEventListener("abort",j,{once:!0})})])},Dt=async(k={},B={})=>{let T=B.prompt||"";if(ne){let M=this._compiledPrompts.get(w);M||(M=vo.compile(ne,{noEscape:!0}),this._compiledPrompts.set(w,M));try{T=M(k)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${w}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}}else if(!T)throw new Error(`No prompt template configured for node '${w}' and no prompt provided in options`);return Ue(T,{state:g.getAll(),images:B.images||[]},{model:B.model||g.get("model"),workspace:g.get("workspace"),schema:B.schema,...B,signal:a.signal})},We=g.getAll(),jt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of jt)Object.prototype.hasOwnProperty.call(We,k)&&console.warn(`[workflow] node "${w}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ge={...We,state:g,invokeAgent:Dt,_coreInvokeAgent:Ue,agent:e,nodeId:w,promptTemplate:ne,getPromptTemplate:()=>ne};try{let k=(C.config?.skills||[]).map(j=>f.get(j)).filter(Boolean),B=[...this.middleware,...k],T;B.length>0?T=await this._composeMiddleware(B,w,async()=>C.execute(Ge,g),g.getAll(),g):T=await C.execute(Ge,g);let M=Date.now()-Le;if(re.push({node:w,success:T.success,duration:M,timestamp:new Date().toISOString()}),!T.success){if(a.signal.aborted)return O.step("Workflow stopped externally"),{success:!0,state:g.getAll(),executionLog:re,stoppedExternally:!0};g.append("errors",{node:w,error:T.error});let j=C.config?.retries||0,V=`${w}_retries`,se=g.getAll()[V]||0;if(se<j){O.stepInfo(`Retrying (attempt ${se+1}/${j})`),g.update({[V]:se+1,[`${w}_raw`]:T.raw});continue}throw O.nodeFailed(w,T.error,{duration:M}),new Error(`Node '${w}' failed after ${se} attempts: ${T.error}`)}g.update({[w]:T.output});let Z=this._summarizeNodeOutput(w,T.output);O.nodeComplete(w,{duration:M,details:Z});let z=this.edges.get(w);if(!z)w="END";else if(z.conditional){let j=z.routes(g.getAll());O.route(w,j),w=j}else w=z}catch(k){throw O.isInsideNode&&O.nodeFailed(w,k.message,{duration:Date.now()-Le}),g.set("failed",!0),g.set("failedAt",w),k}}O.graphComplete();let $={success:!0,state:g.getAll(),executionLog:re};return e&&typeof e.onComplete=="function"&&await e.onComplete($),$}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch($){console.warn(`[workflow] agent.cleanup() failed: ${$.message}`)}}}};var Pe=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Pe]||(globalThis[Pe]=new Map);var Ce=globalThis[Pe];function Co(o,e){Ce.set(o,e)}function Tt(o){return Ce.get(o)}function Re(o){return Ce.has(o)}Co("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let r=t?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let a=e.extraPromptInstructions||"Execute the task based on the current state.",s=Ro(a,t),n=await r(s,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:n,nodeId:o},raw:typeof n=="string"?n:n.raw}}})});function Ro(o,e){let t=/@([\w.]+)/g,r=new Set,a;for(;(a=t.exec(o))!==null;)r.add(a[1]);if(r.size===0)return o;let s=[],n=new Set;for(let i of r){let u=i.split(".")[0];if(n.has(u))continue;let d=i.split(".").reduce((c,m)=>c?.[m],e);if(d===void 0)continue;let h=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),l=i.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());s.push(`## ${l}
43
- ${h}`),i.includes(".")||n.add(u)}return s.length===0?o:`${o}
41
+ ${h}`)}}function xo(){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 Oo(){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 Tt(String(e).trim())}catch{return String(e).trim()}}function Po(){xo()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function No({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Co(o={}){let e=ot.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,s=o.paths?.sessionPrefix;return s?`${s}_${r}`:r}function Ro({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,n="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let d=Tt(String(process.env.ZIBBY_SESSION_PATH));d&&(s=d,n="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,n="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,n="config.sessionId"):(a=Co(e),n="generated")}i=i??Date.now();let h=e.paths?.output||de;s=z(o,h,et,a)}let u=!Ce(s);return u&&vt(s,{recursive:!0}),(u||n!=="initialState.sessionPath")&&Ao({traceFrom:r,sessionId:a,sessionPath:s,idSource:n,mkdirFresh:u}),No({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var me=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 L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let n=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:n.workflow,retries:n.retries,onComplete:n.onComplete,execute:async d=>{let h=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof n.input=="function"?l=n.input(h):n.input&&typeof n.input=="object"?l=n.input:l={},_t(n.workflow,{input:l,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(h):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:h?._signal,parentAgent:d?.agent})}},u=new L(a);return u.name=e,this.nodes.set(e,u),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let s=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof L?t:new L(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),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){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,s,i){let n=r;for(let a=e.length-1;a>=0;a--){let u=e[a],d=n;n=()=>u(t,d,s,i)}return n()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let m=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:m,data:{nodeType:m,label:l}});let y={};c._isCustomCode&&typeof c.execute=="function"&&(y.customCode=c.execute.toString());let _=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;_&&(y.description=_);let v=this.nodePrompts.get(l);if(v)y.prompt=v;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(y.prompt=p,y.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(y.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(y.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof ge?.toJSONSchema=="function")try{p=ge.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=$t(c.outputSchema,{target:"openApi3"})}catch{}y.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else y.outputSchema={schema:c.outputSchema};let I=(this.resolvedToolsMap||{})[l];I?.toolIds&&(y.tools=I.toolIds);let g=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;g&&g.length>0&&(y.skills=[...g]);let f=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;f&&f.length>0&&(y.plugins=f.map(p=>p&&typeof p=="object"?{...p}:p));let S=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;S&&S.length>0&&(y.stores=S.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(y).length>0&&(t[l]=y)}let r=[];for(let[l,c]of this.edges)if(typeof c=="string")r.push({source:l,target:c});else if(c.conditional){let m=this.conditionalCodeMap.get(l)||c.routes.toString(),y=this._inferConditionalTargets(c.routes,c.labels),_=c.labels||{},v=this.nodes.get(l),I=v?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!v,g=l;if(!I){let f=`${l}__branch`;e.push({id:f,type:"decision",data:{nodeType:"decision",label:f}}),r.push({source:l,target:f}),g=f}for(let f of y){let S={source:g,target:f,data:{conditionalCode:m}};_[f]&&(S.label=_[f]),r.push(S)}}let s=l=>{if(!l)return null;if(typeof ge?.toJSONSchema=="function")try{return ge.toJSONSchema(l)}catch{}try{return $t(l,{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 l of r)if(l.target==="END"){i+=1;let c=`END__${i}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:l,target:c})}let n=this._topoOrderNodes(e,r),a=this._runtimeSchema(),u=s(a||this.stateSchema),d=s(this.inputSchema),h=s(this.contextSchema);return{nodes:n,edges:r,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:h}}_topoOrderNodes(e,t){let r=new Map(e.map((l,c)=>[l.id,c])),s=new Map(e.map(l=>[l.id,l])),i=new Map(e.map(l=>[l.id,0])),n=new Map(e.map(l=>[l.id,[]]));for(let l of t)n.has(l.source)&&i.has(l.target)&&(n.get(l.source).push(l.target),i.set(l.target,i.get(l.target)+1));let a=new Set,u=new Set(r.keys()),d=[...u].filter(l=>i.get(l)===0),h=[];for(;h.length<e.length;){let l;if(d.length>0){if(d.sort((c,m)=>r.get(c)-r.get(m)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,m)=>r.get(c)-r.get(m))[0];a.add(l),u.delete(l),h.push(s.get(l));for(let c of n.get(l)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return h}_inferConditionalTargets(e,t){let r=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,n;for(;(n=i.exec(r))!==null;){let d=n[2]!==void 0?n[2]:n[3];d!==void 0&&d!==""&&s.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let u=new Set;for(let d of s)a.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=d.exec(r))!==null;)u.add(h[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");r=e.definitions[s]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],s=e.properties||{},i=e.required||[];for(let[n,a]of Object.entries(s)){let u=t?`${t}.${n}`:n;r.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(n),optional:!i.includes(n)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${u}[]`))}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[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${s}: ${i}`);else if(Array.isArray(i)){let n=i.length,a=i.filter(d=>d?.passed===!0).length,u=i.some(d=>d?.passed!==void 0);r.push(u?`${s}: ${a}/${n} passed${n-a?`, ${n-a} failed`:""}`:`${s}: ${n} 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");let s=new AbortController;r.signal&&(r.signal.aborted?s.abort():r.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,n=t.cwd||process.cwd();To({path:z(n,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let $=z(n,".zibby.config.js");Ce($)&&(a=(await import($)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let $=a?.agent;$?.provider?u=$.provider:$?.gemini?u="gemini":$?.claude?u="claude":$?.cursor?u="cursor":$?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},h=this._runtimeSchema();if(h){let $=h.safeParse(t);if(!$.success){let N=$.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),N.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${N.join(", ")}`)}O.step("State validated against schema")}let l=Oo(),c=t.sessionPath||l;c||Po();let{sessionPath:m,sessionTimestamp:y,sessionId:_}=Ro({cwd:n,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${_}`);let v=await he.loadContext(t.specPath||"",n,d);Object.keys(v).length>0&&O.step(`Context loaded: ${Object.keys(v).join(", ")}`);let I=t.outputPath;!I&&t.specPath&&(e?.calculateOutputPath?I=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let g=new ce({...t,config:a,agentType:u,outputPath:I,sessionPath:m,sessionTimestamp:y,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),f=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:S}=await Promise.resolve().then(()=>(pe(),nt)),p=a.skills&&typeof a.skills=="object"?a.skills:{},E=Object.values(p).filter($=>$&&typeof $=="object"&&typeof $.id=="string"),k=$=>{for(let N of E)if(N.id===$)return N;return S($)},R=new Set;for(let[,$]of this.nodes)for(let N of $.config?.skills||[])R.add(N);for(let $ of R){let N=k($);if(typeof N?.middleware=="function")try{let C=await N.middleware();typeof C=="function"&&f.set($,C)}catch{}}let w=this.entryPoint,ne=[],je=a?.recursionLimit??100,Pt=0;try{for(;w&&w!=="END";){if(++Pt>je)throw new Error(`Workflow exceeded recursion limit (${je}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let N=z(m,tt);if(Ce(N)){try{vo(N)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
42
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:g.getAll(),executionLog:ne,stoppedExternally:!0};let C=this.nodes.get(w);if(!C)throw new Error(`Node '${w}' not found in graph`);let De=JSON.stringify({sessionPath:m,sessionTimestamp:y,currentNode:w,createdAt:new Date().toISOString(),config:g.get("config")}),Nt=z(m,K);Et(Nt,De,"utf-8");let Le=g.get("config")?.paths?.output||de,Ct=z(n,Le,K);vt(z(n,Le),{recursive:!0});try{Et(Ct,De,"utf-8")}catch{}let Ue=t.onPipelineProgress;if(typeof Ue=="function")try{Ue({cwd:n,sessionPath:m,sessionId:_,outputBase:g.get("config")?.paths?.output||de,currentNode:w})}catch{}let Rt=(this.resolvedToolsMap||{})[w]||null;g.set("_currentNodeTools",Rt);let Bt=g.get("nodeConfigs")||{};g.set("_currentNodeConfig",Bt[w]||{}),O.nodeStart(w);let We=Date.now(),se=this.nodePrompts.get(w);if(!this._invokeAgent){let A=await Promise.resolve().then(()=>(oe(),te));this._invokeAgent=A.invokeAgent}let Mt=this._invokeAgent,Se={},jt=C.config?.skills||[];for(let A of jt){let B=k(A);if(typeof B?.invokeAgentOptions=="function")try{let T=B.invokeAgentOptions(g.getAll(),{agentType:g.get("agentType"),nodeName:w});T&&typeof T=="object"&&(Se={...Se,...T})}catch(T){console.warn(`[graph] skill '${A}' invokeAgentOptions threw: ${T.message}`)}}let Fe=async(A,B,T={})=>{let M=Mt(A,B,{...Se,...T,signal:s.signal});return M.catch(()=>{}),s.signal.aborted?M:Promise.race([M,new Promise((Z,q)=>{let D=()=>{setTimeout(()=>{let V=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);V.name="AbortError",q(V)},i)};s.signal.addEventListener("abort",D,{once:!0})})])},Dt=async(A={},B={})=>{let T=B.prompt||"";if(se){let M=this._compiledPrompts.get(w);M||(M=ko.compile(se,{noEscape:!0}),this._compiledPrompts.set(w,M));try{T=M(A)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${w}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}}else if(!T)throw new Error(`No prompt template configured for node '${w}' and no prompt provided in options`);return Fe(T,{state:g.getAll(),images:B.images||[]},{model:B.model||g.get("model"),workspace:g.get("workspace"),schema:B.schema,...B,signal:s.signal})},Ge=g.getAll(),Lt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let A of Lt)Object.prototype.hasOwnProperty.call(Ge,A)&&console.warn(`[workflow] node "${w}": state key "${A}" is shadowed by the engine context prop; read it via context.state.get('${A}')`);let He={...Ge,state:g,invokeAgent:Dt,_coreInvokeAgent:Fe,agent:e,nodeId:w,promptTemplate:se,getPromptTemplate:()=>se};try{let A=(C.config?.skills||[]).map(D=>f.get(D)).filter(Boolean),B=[...this.middleware,...A],T;B.length>0?T=await this._composeMiddleware(B,w,async()=>C.execute(He,g),g.getAll(),g):T=await C.execute(He,g);let M=Date.now()-We;if(ne.push({node:w,success:T.success,duration:M,timestamp:new Date().toISOString()}),!T.success){if(s.signal.aborted)return O.step("Workflow stopped externally"),{success:!0,state:g.getAll(),executionLog:ne,stoppedExternally:!0};g.append("errors",{node:w,error:T.error});let D=C.config?.retries||0,V=`${w}_retries`,ie=g.getAll()[V]||0;if(ie<D){O.stepInfo(`Retrying (attempt ${ie+1}/${D})`),g.update({[V]:ie+1,[`${w}_raw`]:T.raw});continue}throw O.nodeFailed(w,T.error,{duration:M}),new Error(`Node '${w}' failed after ${ie} attempts: ${T.error}`)}g.update({[w]:T.output});let Z=this._summarizeNodeOutput(w,T.output);O.nodeComplete(w,{duration:M,details:Z});let q=this.edges.get(w);if(!q)w="END";else if(q.conditional){let D=q.routes(g.getAll());O.route(w,D),w=D}else w=q}catch(A){throw O.isInsideNode&&O.nodeFailed(w,A.message,{duration:Date.now()-We}),g.set("failed",!0),g.set("failedAt",w),A}}O.graphComplete();let $={success:!0,state:g.getAll(),executionLog:ne};return e&&typeof e.onComplete=="function"&&await e.onComplete($),$}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch($){console.warn(`[workflow] agent.cleanup() failed: ${$.message}`)}}}};var Re=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Re]||(globalThis[Re]=new Map);var Be=globalThis[Re];function Bo(o,e){Be.set(o,e)}function kt(o){return Be.get(o)}function Me(o){return Be.has(o)}Bo("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let r=t?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(oe(),te))).invokeAgent);let s=e.extraPromptInstructions||"Execute the task based on the current state.",i=Mo(s,t),n=await r(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:n,nodeId:o},raw:typeof n=="string"?n:n.raw}}})});function Mo(o,e){let t=/@([\w.]+)/g,r=new Set,s;for(;(s=t.exec(o))!==null;)r.add(s[1]);if(r.size===0)return o;let i=[],n=new Set;for(let a of r){let u=a.split(".")[0];if(n.has(u))continue;let d=a.split(".").reduce((c,m)=>c?.[m],e);if(d===void 0)continue;let h=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),l=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${l}
43
+ ${h}`),a.includes(".")||n.add(u)}return i.length===0?o:`${o}
44
44
 
45
45
  ---
46
46
  # Referenced Context
47
47
 
48
- ${s.join(`
48
+ ${i.join(`
49
49
 
50
- `)}`}de();W();var Bo={};function kt(o,e){if(Array.isArray(e))return At(e);let t=Bo[o];return!t||t.length===0?null:At(t)}function At(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},r=[];for(let a of o){let s=Q(a);if(!s){I.warn(`[workflow] unknown skill "${a}" \u2014 skipping`);continue}r.push(a);for(let n of s.tools||[])e.push({name:n.name,description:n.description,input_schema:n.input_schema||{type:"object",properties:{}}});if(!t[s.serverName])if(typeof s.resolve=="function"){let n=s.resolve();n&&(t[s.serverName]={...n,toolPrefix:a})}else{let n={};for(let i of s.envKeys||[]){let u=process.env[i];u&&(n[i]=u)}t[s.serverName]={command:s.command,args:[...s.args||[]],env:n,toolPrefix:a}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}W();function Fr(o,e={}){let{nodes:t,edges:r,nodeConfigs:a={}}=o;if(!Array.isArray(t)||t.length===0)throw new D("Graph must have at least one node");if(!Array.isArray(r))throw new D("Graph edges must be an array");let s=new ge(e);e.stateSchema&&s.setStateSchema(e.stateSchema);let n=new Set,i=new Map,u={};for(let c of t){let m=me(c);i.set(c.id,{...c,resolvedType:m}),m==="decision"&&n.add(c.id)}for(let[c,m]of i){if(n.has(c))continue;let S=m.resolvedType,_=a[c]||{},v=kt(S,_.tools);v&&(u[c]=v);let E={};_.prompt&&(E.prompt=_.prompt);let g=Re(S);if(I.debug(`[workflow] compiler: node "${c}" type="${S}" registered=${g}`),_.customCode&&!g)s.addNode(c,xt(c,_.customCode,_),E),s.setNodeType(c,S);else if(g){let f=Tt(S);f.factory?s.addNode(c,f.create(c,{..._,resolvedTools:v}),E):s.addNode(c,f,E),s.setNodeType(c,S)}else if(_.executeCode)s.addNode(c,xt(c,_.executeCode,_),E),s.setNodeType(c,S);else throw new D(`Unknown node type "${S}" for node "${c}". Did you forget to register it?`)}s.resolvedToolsMap=u;let d=new Set;for(let c of r)n.has(c.target)||d.add(c.target);let h=t.find(c=>!n.has(c.id)&&!d.has(c.id));if(!h)throw new D("Could not determine entry point: no node without incoming edges found");s.setEntryPoint(h.id);let l=Mo(r,"source");for(let c of r)if(!n.has(c.source))if(n.has(c.target)){let m=c.target,S=l.get(m)||[];if(S.length===0)throw new D(`Decision node "${m}" has no outgoing edges`);let _=Do(m,S,n);s.addConditionalEdges(c.source,_)}else s.addEdge(c.source,c.target);return s}function Hr(o){let e=[];if(!o||typeof o!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(o.nodes)||o.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(o.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=o.nodeConfigs||{};for(let i of o.nodes){let u=me(i);if(u==="decision"||Re(u))continue;let d=t[i.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${u}" for node "${i.id}". Register it or provide customCode/executeCode.`)}let r=new Set(o.nodes.map(i=>i.id));for(let i of o.edges)r.has(i.source)||e.push(`Edge references unknown source node "${i.source}"`),r.has(i.target)||e.push(`Edge references unknown target node "${i.target}"`);let a=new Set(o.nodes.filter(i=>me(i)==="decision").map(i=>i.id)),s=new Set;for(let i of o.edges)a.has(i.target)||s.add(i.target);let n=o.nodes.filter(i=>!a.has(i.id)&&!s.has(i.id));n.length===0?e.push("No entry point found (every node has incoming edges)"):n.length>1&&e.push(`Multiple entry points found: ${n.map(i=>i.id).join(", ")}`);for(let i of a){let u=o.edges.filter(h=>h.source===i);u.length===0&&e.push(`Decision node "${i}" has no outgoing edges`),u.some(h=>h.data?.conditionalCode||h.conditionalCode)||e.push(`Decision node "${i}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Jr(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>me(e)!=="decision").map(e=>e.id)}function me(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function Mo(o,e){let t=new Map;for(let r of o){let a=r[e];t.has(a)||t.set(a,[]),t.get(a).push(r)}return t}function Do(o,e,t){let r=e.find(i=>i.data?.conditionalCode||i.conditionalCode);if(!r)throw new D(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let a=r.data?.conditionalCode||r.conditionalCode,s=new Set(e.map(i=>i.target).filter(i=>!t.has(i))),n;try{let u=new Function(`return (${a})`)();n=d=>{let h=u(d);return s.has(h)||I.warn(`[workflow] conditional route from "${o}" returned "${h}" which is not in valid targets: ${[...s].join(", ")}`),h}}catch(i){throw new D(`Failed to compile conditionalCode for "${o}": ${i.message}`)}return n}function xt(o,e,t={}){let r;try{r=new Function("invokeAgent","require","console",`return (${e})`)}catch(n){throw new D(`Failed to compile customCode for node "${o}": ${n.message}`)}let a=r(async(...n)=>{let{invokeAgent:i}=await Promise.resolve().then(()=>(te(),ee));return i(...n)},typeof ye<"u"?ye:void 0,console),s=null;return t.outputSchema&&(s=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:s,execute:async n=>{try{let i=await a(n);return typeof i=="object"&&"success"in i?i:{success:!0,output:i,raw:null}}catch(i){return{success:!1,error:i.message,raw:null}}}}}var D=class extends Error{constructor(e){super(e),this.name="CompilationError"}};export{D as CompilationError,Fr as compileGraph,Jr as extractSteps,Hr as validateGraphConfig};
50
+ `)}`}pe();W();var jo={};function xt(o,e){if(Array.isArray(e))return At(e);let t=jo[o];return!t||t.length===0?null:At(t)}function At(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},r=[];for(let s of o){let i=ee(s);if(!i){b.warn(`[workflow] unknown skill "${s}" \u2014 skipping`);continue}r.push(s);for(let n of i.tools||[])e.push({name:n.name,description:n.description,input_schema:n.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let n=i.resolve();n&&(t[i.serverName]={...n,toolPrefix:s})}else{let n={};for(let a of i.envKeys||[]){let u=process.env[a];u&&(n[a]=u)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:n,toolPrefix:s}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}W();function Jr(o,e={}){let{nodes:t,edges:r,nodeConfigs:s={}}=o;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 me(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let n=new Set,a=new Map,u={};for(let c of t){let m=ye(c);a.set(c.id,{...c,resolvedType:m}),m==="decision"&&n.add(c.id)}for(let[c,m]of a){if(n.has(c))continue;let y=m.resolvedType,_=s[c]||{},v=xt(y,_.tools);v&&(u[c]=v);let I={};_.prompt&&(I.prompt=_.prompt);let g=Me(y);if(b.debug(`[workflow] compiler: node "${c}" type="${y}" registered=${g}`),_.customCode&&!g)i.addNode(c,Ot(c,_.customCode,_),I),i.setNodeType(c,y);else if(g){let f=kt(y);f.factory?i.addNode(c,f.create(c,{..._,resolvedTools:v}),I):i.addNode(c,f,I),i.setNodeType(c,y)}else if(_.executeCode)i.addNode(c,Ot(c,_.executeCode,_),I),i.setNodeType(c,y);else throw new j(`Unknown node type "${y}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=u;let d=new Set;for(let c of r)n.has(c.target)||d.add(c.target);let h=t.find(c=>!n.has(c.id)&&!d.has(c.id));if(!h)throw new j("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(h.id);let l=Do(r,"source");for(let c of r)if(!n.has(c.source))if(n.has(c.target)){let m=c.target,y=l.get(m)||[];if(y.length===0)throw new j(`Decision node "${m}" has no outgoing edges`);let _=Lo(m,y,n);i.addConditionalEdges(c.source,_)}else i.addEdge(c.source,c.target);return i}function Yr(o){let e=[];if(!o||typeof o!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(o.nodes)||o.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(o.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=o.nodeConfigs||{};for(let a of o.nodes){let u=ye(a);if(u==="decision"||Me(u))continue;let d=t[a.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${u}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let r=new Set(o.nodes.map(a=>a.id));for(let a of o.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 s=new Set(o.nodes.filter(a=>ye(a)==="decision").map(a=>a.id)),i=new Set;for(let a of o.edges)s.has(a.target)||i.add(a.target);let n=o.nodes.filter(a=>!s.has(a.id)&&!i.has(a.id));n.length===0?e.push("No entry point found (every node has incoming edges)"):n.length>1&&e.push(`Multiple entry points found: ${n.map(a=>a.id).join(", ")}`);for(let a of s){let u=o.edges.filter(h=>h.source===a);u.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),u.some(h=>h.data?.conditionalCode||h.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function zr(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>ye(e)!=="decision").map(e=>e.id)}function ye(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function Do(o,e){let t=new Map;for(let r of o){let s=r[e];t.has(s)||t.set(s,[]),t.get(s).push(r)}return t}function Lo(o,e,t){let r=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!r)throw new j(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let s=r.data?.conditionalCode||r.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),n;try{let u=new Function(`return (${s})`)();n=d=>{let h=u(d);return i.has(h)||b.warn(`[workflow] conditional route from "${o}" returned "${h}" which is not in valid targets: ${[...i].join(", ")}`),h}}catch(a){throw new j(`Failed to compile conditionalCode for "${o}": ${a.message}`)}return n}function Ot(o,e,t={}){let r;try{r=new Function("invokeAgent","require","console",`return (${e})`)}catch(n){throw new j(`Failed to compile customCode for node "${o}": ${n.message}`)}let s=r(async(...n)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(oe(),te));return a(...n)},typeof we<"u"?we:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:i,execute:async n=>{try{let a=await s(n);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,Jr as compileGraph,zr as extractSteps,Yr as validateGraphConfig};