@zibby/agent-workflow 0.4.17 → 0.4.19

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,29 @@
1
- var L=Object.defineProperty;var k=(e,o)=>()=>(e&&(o=e(e=0)),o);var M=(e,o)=>{for(var n in o)L(e,n,{get:o[n],enumerable:!0})};function S(e){return G.get(e)||null}var $,G,v=k(()=>{$=Symbol.for("@zibby/agent-workflow.skills");globalThis[$]||(globalThis[$]=new Map);G=globalThis[$]});var _,z,N,T,x=k(()=>{_=()=>{},z={debug:_,info:_,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},N={impl:z},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 C=k(()=>{});var j={};M(j,{getAgentStrategy:()=>I,invokeAgent:()=>Y,listStrategies:()=>B,registerStrategy:()=>F});function F(e){if(!e||typeof e.getName!="function"||typeof e.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let o=m.findIndex(n=>n.getName()===e.getName());o>=0?m[o]=e:m.push(e)}function B(){return m.map(e=>e.getName())}function I(e={}){let{state:o={},preferredAgent:n=null}=e,r=n||o.agentType||process.env.AGENT_TYPE;if(!r){let s=m.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=m.find(s=>s.getName()===r);if(!i){let s=m.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=I(o),i=o.state?.config||n.config||{},s=i.models||{},t=n.nodeName&&s[n.nodeName]||null,a=s.default||null,c=i.agent?.[r.name]?.model||null,l=t||a||c||n.model||null,p={...n,model:l,workspace:o.state?.workspace||n.workspace,schema:n.schema||o.schema,images:n.images||o.images||[],skills:n.skills||o.skills||[],config:i},u=e,g=p.skills||[];if(g.length>0&&!n.skipPromptFragments){let d=g.map(y=>{let f=S(y)?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);d.length>0&&(u+=`
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+=`
2
2
 
3
- ${d.join(`
3
+ ${f.join(`
4
4
 
5
- `)}`)}let h=o.state?._currentNodeConfig?.extraPromptInstructions?.trim();return h&&(u+=`
5
+ `)}`)}let y=r._currentNodeConfig?.extraPromptInstructions?.trim();return y&&(g+=`
6
6
 
7
7
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\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
8
  PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
9
9
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\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
10
 
11
- ${h}
12
- `),T.debug(`[workflow] prompt length: ${u.length} chars`),r.invoke(u,p)}var E,m,O=k(()=>{C();x();v();E=Symbol.for("@zibby/agent-workflow.strategies");globalThis[E]||(globalThis[E]=[]);m=globalThis[E]});v();x();var A={};var b=Symbol.for("@zibby/agent-workflow.nodes");globalThis[b]||(globalThis[b]=new Map);var R=globalThis[b];function U(e,o){R.set(e,o)}function P(e){let o=R.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(()=>(O(),j))).invokeAgent);let i=o.extraPromptInstructions||"Execute the task based on the current state.",s=V(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 V(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((g,h)=>g?.[h],o);if(l===void 0)continue;let p=typeof l=="string"?l:l?.raw??JSON.stringify(l,null,2),u=a.replace(/_/g," ").replace(/\b\w/g,g=>g.toUpperCase());s.push(`## ${u}
13
- ${p}`),a.includes(".")||t.add(c)}return s.length===0?e:`${e}
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}
14
14
 
15
15
  ---
16
16
  # Referenced Context
17
17
 
18
18
  ${s.join(`
19
19
 
20
- `)}`}function me(e,o={}){let{nodes:n,edges:r,nodeConfigs:i={}}=e,s=new Set,t=[],a=new Map;for(let f of n){let w=f.data?.nodeType||f.type;a.set(f.id,w),w==="decision"?s.add(f.id):t.push({id:f.id,nodeType:w,label:f.data?.label||f.id})}let c=t.some(f=>{let w=i[f.id]||{};return!w.customCode&&!w.executeCode}),{toolsPerNode:l,toolIdsByVar:p}=Q(t,i),{simpleEdges:u,conditionalEdges:g}=X(r,s),h=ee(t,r,s),d=[],y=o.workflowType||"workflow";return d.push(H(o)),d.push(K(y,{usesRegisteredNodes:c})),d.push(W(p)),d.push(J(y)),d.push(Z(t,i)),d.push(q(t,h,u,g,l,y)),d.filter(Boolean).join(`
21
- `)}function he(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 H(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 K(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 W(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 J(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 Z(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=D(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=P(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=D(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((p,u)=>u===0?p:` ${p}`).join(`
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(`
28
28
  `);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 Q(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=A[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 X(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 ee(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 D(e){return e.replace(/[^a-zA-Z0-9]/g,"_")}export{he as generateNodeConfigsJson,me as generateWorkflowCode};
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};
@@ -22,6 +22,7 @@ export namespace SKILLS {
22
22
  let FIGMA: string;
23
23
  let OPEN_DESIGN: string;
24
24
  let GIT: string;
25
+ let GIT_WRITE: string;
25
26
  let SLACK: string;
26
27
  let LARK: string;
27
28
  let CHAT_NOTIFY: string;
@@ -40,6 +41,23 @@ export namespace SKILLS {
40
41
  let NOTION: string;
41
42
  let LINEAR: string;
42
43
  let PLANE: string;
44
+ let CODEBASE_MEMORY: string;
43
45
  }
46
+ /**
47
+ * No-connection toggleable skills — skills that require NO integration/token
48
+ * (they run purely locally in the agent runtime) but are still USER-TOGGLEABLE
49
+ * per-agent, reusing the SAME `enabledIntegrations` allowlist that integration
50
+ * providers use. Default ON (absence of an allowlist = "everything on"); when the
51
+ * deployed workflow carries an explicit allowlist (surfaced to the runtime as the
52
+ * comma-separated WORKFLOW_ENABLED_INTEGRATIONS env), membership decides on/off,
53
+ * and the strategy's skill resolver SKIPS a non-member so its tools never load.
54
+ *
55
+ * Kept here (not in @zibby/skills) so the strategy can gate without coupling to
56
+ * any specific skill package. MUST stay in sync with the backend's
57
+ * NO_INTEGRATION_TOGGLEABLE_IDS (backend/src/services/skill-integrations.js) —
58
+ * the backend accepts these as valid allowlist ids + surfaces them in the
59
+ * /workflows/{uuid}/integrations/status feed.
60
+ */
61
+ export const NO_INTEGRATION_TOGGLEABLE_SKILL_IDS: readonly string[];
44
62
  /** CI env vars checked when generating session IDs. */
45
63
  export const CI_ENV_VARS: string[];
package/dist/constants.js CHANGED
@@ -1 +1 @@
1
- var o=".zibby/output",t="sessions",I=".session-info.json",_=".zibby-stop",s="result.json",n="raw_stream_output.txt",E="events.json",e={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",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"},r=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];export{r as CI_ENV_VARS,o as DEFAULT_OUTPUT_BASE,E as EVENTS_FILE,n as RAW_OUTPUT_FILE,s as RESULT_FILE,t as SESSIONS_DIR,I as SESSION_INFO_FILE,e as SKILLS,_ as STOP_REQUEST_FILE};
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,18 +1,18 @@
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,le,y,F=ae(()=>{Je=()=>{},Lt={debug:Je,info:Je,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},le={impl:Lt},y={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:()=>Yt,getAllSkills:()=>Ht,getSkill:()=>Q,hasSkill:()=>Gt,listSkillIds:()=>Jt,registerSkill:()=>Wt});function Wt(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 Gt(o){return q.has(o)}function Ht(){return new Map(q)}function Jt(){return Array.from(q.keys())}function Yt(){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:()=>Kt,listStrategies:()=>zt,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 zt(){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}`)}y.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 y.debug(`[workflow] using agent: ${s.getName()}`),s}async function Kt(o,e={},t={}){let r=nt(e),s=e.state?.config||t.config||{},n=s.models||{},a=t.nodeName&&n[t.nodeName]||null,i=n.default||null,u=s.agent?.[r.name]?.model||null,l=a||i||u||t.model||null,p={...t,model:l,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:s},c=o,d=p.skills||[];if(d.length>0&&!t.skipPromptFragments){let w=d.map(_=>{let $=Q(_)?.promptFragment;return typeof $=="function"?$():$}).filter(Boolean);w.length>0&&(c+=`
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,y,F=ae(()=>{Je=()=>{},jt={debug:Je,info:Je,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},le={impl:jt},y={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}`)}y.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 y.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||{},c=t.nodeName&&i[t.nodeName]||null,l=i.default||null,p=a.agent?.[n.name]?.model||null,u=c||l||p||t.model||null,d={...t,model:u,workspace:r.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:a},h=o,w=d.skills||[];if(w.length>0&&!t.skipPromptFragments){let $=w.map(I=>{let f=Q(I)?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);$.length>0&&(h+=`
2
2
 
3
- ${w.join(`
3
+ ${$.join(`
4
4
 
5
- `)}`)}let h=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return h&&(c+=`
5
+ `)}`)}let _=r._currentNodeConfig?.extraPromptInstructions?.trim();return _&&(h+=`
6
6
 
7
7
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\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
8
  PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
9
9
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\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
10
 
11
- ${h}
12
- `),y.debug(`[workflow] prompt length: ${c.length} chars`),r.invoke(c,p)}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 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:
11
+ ${_}
12
+ `),y.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:
13
13
  ${t.join(`
14
- `)}`);return e}};F();import{writeFileSync as ve,readFileSync as st,existsSync as it,mkdirSync as qt}from"node:fs";import{join as Ae,dirname as Vt}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 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+=`
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 c=t[i];e.lineStart&&(a+=Ke,e.col=qe,e.lineStart=!1),c===`
15
+ `?(a+=c,e.lineStart=!0,e.col=0,e.inEsc=!1):c==="\x1B"?(e.inEsc=!0,a+=c):e.inEsc?(a+=c,(c>="A"&&c<="Z"||c>="a"&&c<="z")&&(e.inEsc=!1)):(e.col++,a+=c,e.col>=n&&(a+=`
16
16
  ${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
17
  `),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
18
18
  `),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
@@ -22,24 +22,24 @@ ${Ke}`,e.col=qe))}return o(a,r,s)}}var be=class{constructor(){this._currentNode=
22
22
  `)):process.stdout.write.bind(process.stdout)(`${e} ${t}
23
23
  `)}step(e){this._origStdoutWrite?this._writeDot(Ie,e):process.stdout.write.bind(process.stdout)(`${X} ${Ie} ${e}
24
24
  `)}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=k.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,k.red(e)):process.stdout.write.bind(process.stdout)(`${X} ${Ee} ${k.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?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 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 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"){y.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?(y.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 y.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&y.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}
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=u=>t&&typeof t.get=="function"?t.get(u):e?.[u];if(typeof this.customExecute=="function"){y.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let u=await this.customExecute(e);return typeof u=="object"&&u!==null&&u.success===!1?{success:!1,error:u.error||"Node execution failed",raw:u.raw||null}:this.isZodSchema?(y.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(u),raw:null}):{success:!0,output:u,raw:null}}catch(u){return y.error(`[workflow] node '${this.name}' failed: ${u.message}`),u.name==="ZodError"&&y.error(`Schema errors: ${JSON.stringify(u.issues||u.errors,null,2)}`),{success:!1,error:u.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
28
 
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){y.debug(`[workflow] could not update session info: ${c.message}`)}let p=null;for(let c=0;c<=this.retries;c++)try{y.debug(`[workflow] node '${this.name}' attempt ${c}`);let d=r().config||{},h=d.agents||{},w=this.config.agent??h[this.name]??null,_={state:r()};w&&(_.preferredAgent=w);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},b=e?._coreInvokeAgent;b||(b=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let f=await b(n,_,$),I,g;if(typeof f=="string"?(I=f,g=null):f.structured?(I=f.raw||JSON.stringify(f.structured,null,2),g=f.structured):(I=f.raw||JSON.stringify(f,null,2),g=f.extracted||null),l)try{let m=Ae(l,this.name,"raw_stream_output.txt");qt(Vt(m),{recursive:!0}),ve(m,typeof I=="string"?I:JSON.stringify(I),"utf-8")}catch(m){y.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&g){y.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){y.warn(`[workflow] onComplete hook failed: ${R.message}`)}return{success:!0,output:m,raw:I}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:I}),raw:I}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(I);return y.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),x.step("Output parsed"),{success:!0,output:m,raw:I}}return{success:!0,output:I,raw:I}}catch(d){p=d,c<this.retries&&y.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 eo,existsSync as J,statSync as ft,readdirSync as ht,rmSync as to}from"node:fs";import{spawn as pt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as oo}from"node:url";import{AsyncLocalStorage as Xt}from"node:async_hooks";var ke=new Xt;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 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");xe.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()}),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 ro(){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 no(){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 so({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||y.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){y.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function io(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(J(t)&&J(r))return;eo(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,w=()=>{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",_=>{d=_,w()}),c.on("close",_=>{h=_,w()}),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 ao(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(oo(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=no()}catch(g){throw g}y.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let s=await so({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=ro();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 io(i,g);try{uo()}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 ao(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 w=Date.now(),$=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph(),b={...e.input||{}},f,I;try{f=await at({executionId:n,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,b,{signal:e.signal})),I=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()-w}}),g}if(f&&typeof f=="object"&&f.stoppedExternally){await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",finalState:I,durationMs:Date.now()-w}});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:I,durationMs:Date.now()-w}}),{finalState:I,executionId:n}}function co(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 u=U(fe,i),l;try{l=ft(u)}catch{continue}let p=l.isDirectory()?co(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{to(i.full,{recursive:!0,force:!0}),n+=i.size,a+=1}catch(u){y.debug(`[sub-graph cache] evict skip ${i.name}: ${u.message}`)}}return a>0&&y.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 y.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var lo=2e3,po=600*1e3,fo=new Set(["completed","failed","canceled","timeout"]);function ho(){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 go(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function mo(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function So(){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{y.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 y.info(`[sub-graph] '${o}' completed in-process`),m}catch(g){if(g instanceof O||g?.fallback)y.info(`[sub-graph] in-process fallback for '${o}': ${g.reason||"unknown"} \u2014 using HTTP`);else throw g}let s=ho(),n=go(),a=mo(),i=So(),u=`${s}/projects/${encodeURIComponent(n)}/workflows/${encodeURIComponent(o)}/trigger`,l={input:e.input||{},...i?{parentExecutionId:i}:{},...e.conversationId?{conversationId:e.conversationId}:{}};y.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 y.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:po,w=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:lo,_=`${s}/executions/${encodeURIComponent(d)}`,$=Date.now()+h,b="accepted",f=0;for(;Date.now()<$;){await new Promise(v=>setTimeout(v,w)),f+=1;let g=await fetch(_,{headers:{Authorization:`Bearer ${a}`}});if(!g.ok){if(g.status>=500){y.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(b=R?.status||b,fo.has(b)){if(b!=="completed"){let S=new Error(`Sub-graph '${o}' (${d}) ended in status '${b}'`);throw S.subgraphJobId=d,S.subgraphStatus=b,S}let v=R?.finalState||R?.state||{},M=mt(v,e.output);return y.info(`[sub-graph] '${o}' (${d}) completed after ${f} polls`),M}}let I=new Error(`Sub-graph '${o}' (${d}) timed out after ${Math.round(h/1e3)}s (last status: ${b})`);throw I.subgraphJobId=d,I.subgraphStatus=b,I}import{existsSync as yt,readFileSync as yo}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(`
29
+ ${n}`);let i=r(),c=i.cwd||process.cwd(),l=i.sessionPath;try{if(l){let u=Ae(l,K);if(it(u)){let h=JSON.parse(st(u,"utf-8"));h.currentNode=this.name,ve(u,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(u){y.debug(`[workflow] could not update session info: ${u.message}`)}let p=null;for(let u=0;u<=this.retries;u++)try{y.debug(`[workflow] node '${this.name}' attempt ${u}`);let d=r().config||{},h=d.agents||{},w=this.config.agent??h[this.name]??null,_={state:r()};w&&(_.preferredAgent=w);let $={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:l,config:d,nodeName:this.name,timeout:this.config?.timeout||3e5},I=e?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let f=await I(n,_,$),E,g;if(typeof f=="string"?(E=f,g=null):f.structured?(E=f.raw||JSON.stringify(f.structured,null,2),g=f.structured):(E=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 E=="string"?E:JSON.stringify(E),"utf-8")}catch(m){y.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&g){y.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){y.warn(`[workflow] onComplete hook failed: ${R.message}`)}return{success:!0,output:m,raw:E}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:E}),raw:E}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(E);return y.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),k.step("Output parsed"),{success:!0,output:m,raw:E}}return{success:!0,output:E,raw:E}}catch(d){p=d,u<this.retries&&y.info(`[workflow] node '${this.name}' failed, retrying (${u+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||y.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){y.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"),c=a(s,"wx");i(c),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((c,l)=>{let p=pt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),u=pt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(u.stdin);let d,h,w=()=>{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}`));c()}};p.on("close",_=>{d=_,w()}),u.on("close",_=>{h=_,w()}),p.on("error",l),u.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}y.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:c,workflowVersion:l,workflowUuid:p,bundleReady:u}=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(!u||!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 w=Date.now(),$=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph(),I={...e.input||{}},f,E;try{f=await at({executionId:n,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,I,{signal:e.signal})),E=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()-w}}),g}if(f&&typeof f=="object"&&f.stoppedExternally){await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",finalState:E,durationMs:Date.now()-w}});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:E,durationMs:Date.now()-w}}),{finalState:E,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 c=U(fe,i),l;try{l=ft(c)}catch{continue}let p=l.isDirectory()?uo(c):l.size;r+=p,t.push({name:i,full:c,size:p,mtimeMs:l.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((i,c)=>i.mtimeMs-c.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(c){y.debug(`[sub-graph cache] evict skip ${i.name}: ${c.message}`)}}return a>0&&y.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 y.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{y.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 y.info(`[sub-graph] '${o}' completed in-process`),m}catch(g){if(g instanceof O||g?.fallback)y.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(),c=`${s}/projects/${encodeURIComponent(n)}/workflows/${encodeURIComponent(o)}/trigger`,l={input:e.input||{},...i?{parentExecutionId:i}:{},...e.conversationId?{conversationId:e.conversationId}:{}};y.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${i||"<none>"}`);let p=await fetch(c,{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 u=await p.json(),d=u?.data?.jobId||u?.jobId;if(!d)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(u).slice(0,200)}`);if(e.async)return y.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,w=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:po,_=`${s}/executions/${encodeURIComponent(d)}`,$=Date.now()+h,I="accepted",f=0;for(;Date.now()<$;){await new Promise(v=>setTimeout(v,w)),f+=1;let g=await fetch(_,{headers:{Authorization:`Bearer ${a}`}});if(!g.ok){if(g.status>=500){y.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(I=R?.status||I,ho.has(I)){if(I!=="completed"){let S=new Error(`Sub-graph '${o}' (${d}) ended in status '${I}'`);throw S.subgraphJobId=d,S.subgraphStatus=I,S}let v=R?.finalState||R?.state||{},M=mt(v,e.output);return y.info(`[sub-graph] '${o}' (${d}) completed after ${f} polls`),M}}let E=new Error(`Sub-graph '${o}' (${d}) timed out after ${Math.round(h/1e3)}s (last status: ${I})`);throw E.subgraphJobId=d,E.subgraphStatus=I,E}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 c of n){let l=await this.findAndMergeContextFiles(c,i,t);if(l){let p=c.replace(/\.[^.]+$/,"").toLowerCase();s[p]=l}}}let a=r.discovery||{};for(let[i,c]of Object.entries(a))try{let l=Ne(t,c);yt(l)&&(s[i]=await this.loadFile(l))}catch(l){console.warn(`[workflow] could not load context '${i}' from '${c}': ${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(c){console.warn(`[workflow] could not load ${e} from ${a}: ${c.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
30
 
31
31
  ---
32
32
 
33
- `):s.every(a=>typeof a=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=yo(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 wo}from"node:fs";import{join as Y,resolve as bt}from"node:path";import{config as _o}from"dotenv";import{zodToJsonSchema as It}from"zod-to-json-schema";import{z as ge}from"zod";import Io from"handlebars";function Eo({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(`
33
+ `):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
34
  `).slice(2,14).join(`
35
35
  `);console.log(`[zibby:session] stack (${o}):
36
- ${p}`)}}function bo(){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 $o(){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 To(){bo()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function vo({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 Ao(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=Ao(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")&&Eo({traceFrom:r,sessionId:i,sessionPath:s,idSource:a,mkdirFresh:u}),vo({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 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 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 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 w=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;w&&(h.description=w);let _=this.nodePrompts.get(p);if(_)h.prompt=_;else if(typeof c.prompt=="function")try{let f=c.prompt({});typeof f=="string"&&f.trim()&&(h.prompt=f,h.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(h.executeCode=c.customExecute.toString()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let f=null;if(typeof ge?.toJSONSchema=="function")try{f=ge.toJSONSchema(c.outputSchema)}catch{}if(!f)try{f=It(c.outputSchema,{target:"openApi3"})}catch{}h.outputSchema=f?{jsonSchema:f,variables:this._flattenJsonSchemaToVariables(f)}:{schema:c.outputSchema}}else h.outputSchema={schema:c.outputSchema};let $=(this.resolvedToolsMap||{})[p];$?.toolIds&&(h.tools=$.toolIds);let b=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;b&&b.length>0&&(h.skills=[...b]),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),w=c.labels||{};for(let _ of h){let $={source:p,target:_,data:{conditionalCode:d}};w[_]&&($.label=w[_]),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();_o({path:Y(a,".env")});let i=t.config||{};if(!i||Object.keys(i).length===0)try{let E=Y(a,".zibby.config.js");Pe(E)&&(i=(await import(E)).default||{})}catch{}process.env.EXECUTION_ID&&!i.agent?.strictMode&&(i.agent={...i.agent,strictMode:!0});let u=t.agentType;if(!u){let E=i?.agent;E?.provider?u=E.provider:E?.gemini?u="gemini":E?.claude?u="claude":E?.cursor?u="cursor":E?.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 E=p.safeParse(t);if(!E.success){let N=E.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(", ")}`)}x.step("State validated against schema")}let c=$o(),d=t.sessionPath||c;d||To();let{sessionPath:h,sessionTimestamp:w,sessionId:_}=ko({cwd:a,config:i,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:d,sessionTimestamp:t.sessionTimestamp}});x.step(`Session ${_}`);let $=await he.loadContext(t.specPath||"",a,l);Object.keys($).length>0&&x.step(`Context loaded: ${Object.keys($).join(", ")}`);let b=t.outputPath;!b&&t.specPath&&(e?.calculateOutputPath?b=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ce({...t,config:i,agentType:u,outputPath:b,sessionPath:h,sessionTimestamp:w,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),I=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(E=>E&&typeof E=="object"&&typeof E.id=="string"),v=E=>{for(let N of R)if(N.id===E)return N;return g(E)},M=new Set;for(let[,E]of this.nodes)for(let N of E.config?.skills||[])M.add(N);for(let E of M){let N=v(E);if(typeof N?.middleware=="function")try{let P=await N.middleware();typeof P=="function"&&I.set(E,P)}catch{}}let S=this.entryPoint,ne=[],Me=i?.recursionLimit??100,kt=0;try{for(;S&&S!=="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 N=Y(h,et);if(Pe(N)){try{wo(N)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
37
- \u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ne,stoppedExternally:!0};let P=this.nodes.get(S);if(!P)throw new Error(`Node '${S}' not found in graph`);let De=JSON.stringify({sessionPath:h,sessionTimestamp:w,currentNode:S,createdAt:new Date().toISOString(),config:f.get("config")}),xt=Y(h,K);_t(xt,De,"utf-8");let je=f.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:h,sessionId:_,outputBase:f.get("config")?.paths?.output||de,currentNode:S})}catch{}let Nt=(this.resolvedToolsMap||{})[S]||null;f.set("_currentNodeTools",Nt);let Pt=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Pt[S]||{}),x.nodeStart(S);let Ue=Date.now(),se=this.nodePrompts.get(S);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:S});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 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={},C={})=>{let T=C.prompt||"";if(se){let B=this._compiledPrompts.get(S);B||(B=Io.compile(se,{noEscape:!0}),this._compiledPrompts.set(S,B));try{T=B(A)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${S}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}}else if(!T)throw new Error(`No prompt template configured for node '${S}' 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 "${S}": 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:S,promptTemplate:se,getPromptTemplate:()=>se};try{let A=(P.config?.skills||[]).map(j=>I.get(j)).filter(Boolean),C=[...this.middleware,...A],T;C.length>0?T=await this._composeMiddleware(C,S,async()=>P.execute(Ge,f),f.getAll(),f):T=await P.execute(Ge,f);let B=Date.now()-Ue;if(ne.push({node:S,success:T.success,duration:B,timestamp:new Date().toISOString()}),!T.success){if(s.signal.aborted)return x.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ne,stoppedExternally:!0};f.append("errors",{node:S,error:T.error});let j=P.config?.retries||0,V=`${S}_retries`,ie=f.getAll()[V]||0;if(ie<j){x.stepInfo(`Retrying (attempt ${ie+1}/${j})`),f.update({[V]:ie+1,[`${S}_raw`]:T.raw});continue}throw x.nodeFailed(S,T.error,{duration:B}),new Error(`Node '${S}' failed after ${ie} attempts: ${T.error}`)}f.update({[S]:T.output});let Z=this._summarizeNodeOutput(S,T.output);x.nodeComplete(S,{duration:B,details:Z});let z=this.edges.get(S);if(!z)S="END";else if(z.conditional){let j=z.routes(f.getAll());x.route(S,j),S=j}else S=z}catch(A){throw x.isInsideNode&&x.nodeFailed(S,A.message,{duration:Date.now()-Ue}),f.set("failed",!0),f.set("failedAt",S),A}}x.graphComplete();let E={success:!0,state:f.getAll(),executionLog:ne};return e&&typeof e.onComplete=="function"&&await e.onComplete(E),E}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(E){console.warn(`[workflow] agent.cleanup() failed: ${E.message}`)}}}};var Ce=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Ce]||(globalThis[Ce]=new Map);var Re=globalThis[Ce];function xo(o,e){Re.set(o,e)}function $t(o){return Re.get(o)}function Be(o){return Re.has(o)}xo("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=Oo(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 Oo(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}
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 u=e.sessionId!=null?String(e.sessionId).trim():"";u&&u!=="last"?(i=u,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 c=!Pe(s);return c&&Et(s,{recursive:!0}),(c||a!=="initialState.sessionPath")&&bo({traceFrom:r,sessionId:i,sessionPath:s,idSource:a,mkdirFresh:c}),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 c=>{let l=c?.state&&typeof c.state.getAll=="function"?c.state.getAll():c,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:c?.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 c=e[i],l=a;a=()=>c(t,l,s,n)}return a()}serialize(){let e=[],t={};for(let[p,u]of this.nodes){let d=this.nodeTypeMap.get(p)||(u instanceof oe?"decision":p);e.push({id:p,type:d,data:{nodeType:d,label:p}});let h={};u._isCustomCode&&typeof u.execute=="function"&&(h.customCode=u.execute.toString());let w=typeof u?.config?.description=="string"&&u.config.description.trim()?u.config.description:typeof u?.description=="string"&&u.description.trim()?u.description:null;w&&(h.description=w);let _=this.nodePrompts.get(p);if(_)h.prompt=_;else if(typeof u.prompt=="function")try{let f=u.prompt({});typeof f=="string"&&f.trim()&&(h.prompt=f,h.promptIsCode=!0)}catch{}if(typeof u.customExecute=="function"&&(h.executeCode=u.customExecute.toString()),u.outputSchema)if(typeof u.outputSchema._def<"u"){let f=null;if(typeof ge?.toJSONSchema=="function")try{f=ge.toJSONSchema(u.outputSchema)}catch{}if(!f)try{f=It(u.outputSchema,{target:"openApi3"})}catch{}h.outputSchema=f?{jsonSchema:f,variables:this._flattenJsonSchemaToVariables(f)}:{schema:u.outputSchema}}else h.outputSchema={schema:u.outputSchema};let $=(this.resolvedToolsMap||{})[p];$?.toolIds&&(h.tools=$.toolIds);let I=Array.isArray(u?.config?.skills)?u.config.skills:Array.isArray(u?.skills)?u.skills:null;I&&I.length>0&&(h.skills=[...I]),Object.keys(h).length>0&&(t[p]=h)}let r=[];for(let[p,u]of this.edges)if(typeof u=="string")r.push({source:p,target:u});else if(u.conditional){let d=this.conditionalCodeMap.get(p)||u.routes.toString(),h=this._inferConditionalTargets(u.routes,u.labels),w=u.labels||{};for(let _ of h){let $={source:p,target:_,data:{conditionalCode:d}};w[_]&&($.label=w[_]),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 u=`END__${n}`;p.target=u,e.push({id:u,type:"end",data:{nodeType:"end",label:"End"}})}for(let p of this.nodes.keys())if(!this.edges.has(p)){n+=1;let u=`END__${n}`;e.push({id:u,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:p,target:u})}let a=this._runtimeSchema(),i=s(a||this.stateSchema),c=s(this.inputSchema),l=s(this.contextSchema);return{nodes:e,edges:r,nodeConfigs:t,stateSchema:i,inputSchema:c,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 c=new Set;for(let l of s)i.has(l)&&c.add(l);if(c.size===0){let l=/return\s+['"]([^'"]+)['"]/g,p;for(;(p=l.exec(r))!==null;)c.add(p[1])}return[...c]}_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 c=t?`${t}.${a}`:a;r.push({path:c,type:i.type||"unknown",label:i.description||this._formatLabel(a),optional:!n.includes(a)}),i.type==="object"&&i.properties&&r.push(...this._flattenSchema(i,c)),i.type==="array"&&i.items?.type==="object"&&i.items.properties&&r.push(...this._flattenSchema(i.items,`${c}[]`))}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,c=n.some(l=>l?.passed!==void 0);r.push(c?`${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 c=t.agentType;if(!c){let b=i?.agent;b?.provider?c=b.provider:b?.gemini?c="gemini":b?.claude?c="claude":b?.cursor?c="cursor":b?.codex?c="codex":c=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 u=To(),d=t.sessionPath||u;d||vo();let{sessionPath:h,sessionTimestamp:w,sessionId:_}=ko({cwd:a,config:i,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:d,sessionTimestamp:t.sessionTimestamp}});k.step(`Session ${_}`);let $=await he.loadContext(t.specPath||"",a,l);Object.keys($).length>0&&k.step(`Context loaded: ${Object.keys($).join(", ")}`);let I=t.outputPath;!I&&t.specPath&&(e?.calculateOutputPath?I=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ce({...t,config:i,agentType:c,outputPath:I,sessionPath:h,sessionTimestamp:w,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),E=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"&&E.set(b,P)}catch{}}let S=this.entryPoint,ne=[],Me=i?.recursionLimit??100,xt=0;try{for(;S&&S!=="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(S);if(!P)throw new Error(`Node '${S}' not found in graph`);let De=JSON.stringify({sessionPath:h,sessionTimestamp:w,currentNode:S,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:_,outputBase:f.get("config")?.paths?.output||de,currentNode:S})}catch{}let Nt=(this.resolvedToolsMap||{})[S]||null;f.set("_currentNodeTools",Nt);let Pt=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Pt[S]||{}),k.nodeStart(S);let Ue=Date.now(),se=this.nodePrompts.get(S);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:S});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(S);B||(B=Eo.compile(se,{noEscape:!0}),this._compiledPrompts.set(S,B));try{T=B(A)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${S}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}}else if(!T)throw new Error(`No prompt template configured for node '${S}' 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 "${S}": 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:S,promptTemplate:se,getPromptTemplate:()=>se};try{let A=(P.config?.skills||[]).map(L=>E.get(L)).filter(Boolean),C=[...this.middleware,...A],T;C.length>0?T=await this._composeMiddleware(C,S,async()=>P.execute(Ge,f),f.getAll(),f):T=await P.execute(Ge,f);let B=Date.now()-Ue;if(ne.push({node:S,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:S,error:T.error});let L=P.config?.retries||0,V=`${S}_retries`,ie=f.getAll()[V]||0;if(ie<L){k.stepInfo(`Retrying (attempt ${ie+1}/${L})`),f.update({[V]:ie+1,[`${S}_raw`]:T.raw});continue}throw k.nodeFailed(S,T.error,{duration:B}),new Error(`Node '${S}' failed after ${ie} attempts: ${T.error}`)}f.update({[S]:T.output});let Z=this._summarizeNodeOutput(S,T.output);k.nodeComplete(S,{duration:B,details:Z});let z=this.edges.get(S);if(!z)S="END";else if(z.conditional){let L=z.routes(f.getAll());k.route(S,L),S=L}else S=z}catch(A){throw k.isInsideNode&&k.nodeFailed(S,A.message,{duration:Date.now()-Ue}),f.set("failed",!0),f.set("failedAt",S),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 c=i.split(".")[0];if(a.has(c))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),u=i.replace(/_/g," ").replace(/\b\w/g,d=>d.toUpperCase());n.push(`## ${u}
38
+ ${p}`),i.includes(".")||a.add(c)}return n.length===0?o:`${o}
39
39
 
40
40
  ---
41
41
  # Referenced Context
42
42
 
43
43
  ${n.join(`
44
44
 
45
- `)}`}pe();F();var No={};function vt(o,e){if(Array.isArray(e))return Tt(e);let t=No[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){y.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 Dr(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 w=h.resolvedType,_=s[d]||{},$=vt(w,_.tools);$&&(u[d]=$);let b={};_.prompt&&(b.prompt=_.prompt);let f=Be(w);if(y.debug(`[workflow] compiler: node "${d}" type="${w}" registered=${f}`),_.customCode&&!f)n.addNode(d,At(d,_.customCode,_),b),n.setNodeType(d,w);else if(f){let I=$t(w);I.factory?n.addNode(d,I.create(d,{..._,resolvedTools:$}),b):n.addNode(d,I,b),n.setNodeType(d,w)}else if(_.executeCode)n.addNode(d,At(d,_.executeCode,_),b),n.setNodeType(d,w);else throw new D(`Unknown node type "${w}" 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=Po(r,"source");for(let d of r)if(!a.has(d.source))if(a.has(d.target)){let h=d.target,w=c.get(h)||[];if(w.length===0)throw new D(`Decision node "${h}" has no outgoing edges`);let _=Co(h,w,a);n.addConditionalEdges(d.source,_)}else n.addEdge(d.source,d.target);return n}function jr(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 Lr(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 Po(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 Co(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)||y.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,Dr as compileGraph,Lr as extractSteps,jr as validateGraphConfig};
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){y.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 c=process.env[i];c&&(a[i]=c)}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,c={};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 w=h.resolvedType,_=s[d]||{},$=vt(w,_.tools);$&&(c[d]=$);let I={};_.prompt&&(I.prompt=_.prompt);let f=Be(w);if(y.debug(`[workflow] compiler: node "${d}" type="${w}" registered=${f}`),_.customCode&&!f)n.addNode(d,At(d,_.customCode,_),I),n.setNodeType(d,w);else if(f){let E=$t(w);E.factory?n.addNode(d,E.create(d,{..._,resolvedTools:$}),I):n.addNode(d,E,I),n.setNodeType(d,w)}else if(_.executeCode)n.addNode(d,At(d,_.executeCode,_),I),n.setNodeType(d,w);else throw new D(`Unknown node type "${w}" for node "${d}". Did you forget to register it?`)}n.resolvedToolsMap=c;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 u=Co(r,"source");for(let d of r)if(!a.has(d.source))if(a.has(d.target)){let h=d.target,w=u.get(h)||[];if(w.length===0)throw new D(`Decision node "${h}" has no outgoing edges`);let _=Ro(h,w,a);n.addConditionalEdges(d.source,_)}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 c=Se(i);if(c==="decision"||Be(c))continue;let l=t[i.id]||{};l.customCode||l.executeCode||e.push(`Unknown node type "${c}" 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 c=o.edges.filter(p=>p.source===i);c.length===0&&e.push(`Decision node "${i}" has no outgoing edges`),c.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 c=new Function(`return (${s})`)();a=l=>{let p=c(l);return n.has(p)||y.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};