@zibby/agent-workflow 0.4.20 → 0.4.21

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