@zibby/agent-workflow 0.4.38 → 0.4.40
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.
- package/dist/code-generator.js +4 -4
- package/dist/constants.js +1 -1
- package/dist/graph-compiler.js +2 -2
- package/dist/graph.js +2 -2
- package/dist/index.js +2 -2
- package/dist/node-registry.js +8 -8
- package/dist/node.js +8 -8
- package/dist/strategy-registry.js +6 -6
- package/package.json +1 -1
package/dist/code-generator.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var V=Object.defineProperty;var T=(e,o)=>()=>(e&&(o=e(e=0)),o);var Y=(e,o)=>{for(var n in o)V(e,n,{get:o[n],enumerable:!0})};function $(e){return U.get(e)||null}var
|
|
1
|
+
var V=Object.defineProperty;var T=(e,o)=>()=>(e&&(o=e(e=0)),o);var Y=(e,o)=>{for(var n in o)V(e,n,{get:o[n],enumerable:!0})};function $(e){return U.get(e)||null}var b,N,U,ae,v=T(()=>{b=Symbol.for("@zibby/agent-workflow.skills"),N=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[b]||(globalThis[b]=new Map);globalThis[N]||(globalThis[N]=new Map);U=globalThis[b],ae=globalThis[N]});var I,K,S,k,E=T(()=>{I=()=>{},K={debug:I,info:I,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},S={impl:K},k={debug:(...e)=>S.impl.debug?.(...e),info:(...e)=>S.impl.info?.(...e),warn:(...e)=>S.impl.warn?.(...e),error:(...e)=>S.impl.error?.(...e)}});var O=T(()=>{});var M={};Y(M,{getAgentStrategy:()=>P,invokeAgent:()=>J,listStrategies:()=>W,registerStrategy:()=>H,resolveInvocationModel:()=>R});function H(e){if(!e||typeof e.getName!="function"||typeof e.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let o=y.findIndex(n=>n.getName()===e.getName());o>=0?y[o]=e:y.push(e)}function W(){return y.map(e=>e.getName())}function R({config:e={},options:o={},strategyName:n,envModel:r}={}){let i=e.models||{},s=o.nodeName&&i[o.nodeName]||null,t=i.default||null,a=e.agent?.[n]?.model||null,c=(typeof r=="string"?r.trim():"")||null;return s||t||a||o.model||c||null}function P(e={}){let{state:o={},preferredAgent:n=null}=e,r=n||o.agentType||process.env.AGENT_TYPE;if(!r){let s=y.map(t=>t.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}k.debug(`[workflow] agent selection: requested=${r}`);let i=y.find(s=>s.getName()===r);if(!i){let s=y.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 k.debug(`[workflow] using agent: ${i.getName()}`),i}async function J(e,o={},n={}){let r=o.state&&typeof o.state.getAll=="function"?o.state.getAll():o.state||{},i={...o,state:r},s=P(i),t=r.config||n.config||{},a=R({config:t,options:n,strategyName:s.name,envModel:process.env.MODEL}),c={...n,model:a,workspace:r.workspace||n.workspace,schema:n.schema||o.schema,images:n.images||o.images||[],skills:n.skills||o.skills||[],extraMcpServers:n.extraMcpServers||r.extraMcpServers||o.extraMcpServers||[],plugins:n.plugins||o.plugins||[],config:t},l=e,g=c.skills||[];if(g.length>0&&!n.skipPromptFragments){let h=g.map(p=>{let f=$(p)?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);h.length>0&&(l+=`
|
|
2
2
|
|
|
3
3
|
${h.join(`
|
|
4
4
|
|
|
@@ -14,7 +14,7 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
|
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
16
|
${m}
|
|
17
|
-
`),k.debug(`[workflow] prompt length: ${l.length} chars`),s.invoke(l,c)}var x,y,
|
|
17
|
+
`),k.debug(`[workflow] prompt length: ${l.length} chars`),s.invoke(l,c)}var x,y,L=T(()=>{O();E();v();x=Symbol.for("@zibby/agent-workflow.strategies");globalThis[x]||(globalThis[x]=[]);y=globalThis[x]});v();E();var C={};var _=Symbol.for("@zibby/agent-workflow.nodes");globalThis[_]||(globalThis[_]=new Map);var D=globalThis[_];function q(e,o){D.set(e,o)}function z(e){let o=D.get(e);return o?o.factory&&typeof o.create=="function"?o.create.toString():typeof o.execute=="function"?o.execute.toString():typeof o=="function"?o.toString():null:null}q("ai_agent",{name:"ai_agent",factory:!0,create:(e,o={})=>({name:e,_isCustomCode:!0,execute:async n=>{let r=n?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(L(),M))).invokeAgent);let i=o.extraPromptInstructions||"Execute the task based on the current state.",s=Z(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 Z(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((m,h)=>m?.[h],o);if(l===void 0)continue;let g=typeof l=="string"?l:l?.raw??JSON.stringify(l,null,2),u=a.replace(/_/g," ").replace(/\b\w/g,m=>m.toUpperCase());s.push(`## ${u}
|
|
18
18
|
${g}`),a.includes(".")||t.add(c)}return s.length===0?e:`${e}
|
|
19
19
|
|
|
20
20
|
---
|
|
@@ -22,7 +22,7 @@ ${g}`),a.includes(".")||t.add(c)}return s.length===0?e:`${e}
|
|
|
22
22
|
|
|
23
23
|
${s.join(`
|
|
24
24
|
|
|
25
|
-
`)}`}function
|
|
25
|
+
`)}`}function be(e,o={}){let{nodes:n,edges:r,nodeConfigs:i={}}=e,s=new Set,t=[],a=new Map;for(let d of n){let w=d.data?.nodeType||d.type;a.set(d.id,w),w==="decision"?s.add(d.id):t.push({id:d.id,nodeType:w,label:d.data?.label||d.id})}let c=t.some(d=>{let w=i[d.id]||{};return!w.customCode&&!w.executeCode}),{toolsPerNode:l,toolIdsByVar:g}=re(t,i),{simpleEdges:u,conditionalEdges:m}=se(r,s),h=ie(t,r,s),p=[],f=o.workflowType||"workflow";return p.push(Q(o)),p.push(X(f,{usesRegisteredNodes:c})),p.push(ee(g)),p.push(oe(f)),p.push(te(t,i)),p.push(ne(t,h,u,m,l,f)),p.filter(Boolean).join(`
|
|
26
26
|
`)}function Ne(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 Q(e){let o=e.workflowType||"workflow";return["// Generated workflow",`// ${e.projectId?`Project: ${e.projectId} | `:""}Type: ${o} | Version: ${e.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
|
|
27
27
|
`)}function X(e,{usesRegisteredNodes:o=!0}={}){let n=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return o&&n.push("// import './register-nodes.js'; // register custom node types here"),n.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),n.join(`
|
|
28
28
|
`)}function ee(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(`
|
|
@@ -31,4 +31,4 @@ ${s.join(`
|
|
|
31
31
|
`)}function ne(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=G(c.id);t.push(` graph.addNode('${c.id}', { name: '${c.id}', execute: ${l}_execute });`),t.push(` graph.setNodeType('${c.id}', '${c.nodeType}');`)}t.push("",` graph.setEntryPoint('${o}');`,""),(n.length>0||r.length>0)&&t.push(" // Edges");for(let c of n)t.push(` graph.addEdge('${c.source}', '${c.target}');`);for(let c of r){let l=c.code.split(`
|
|
32
32
|
`).map((g,u)=>u===0?g:` ${g}`).join(`
|
|
33
33
|
`);t.push(` graph.addConditionalEdges('${c.source}', ${l});`)}let a=[];for(let c of e){let l=i.get(c.id);l&&a.push(` '${c.id}': ${l},`)}return a.length>0&&t.push(""," graph.resolvedToolsMap = {",...a," };"),t.push(""," return graph;","}",""),t.push("export { nodeConfigs };",""),t.join(`
|
|
34
|
-
`)}function re(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 se(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 ie(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 G(e){return e.replace(/[^a-zA-Z0-9]/g,"_")}export{Ne as generateNodeConfigsJson,
|
|
34
|
+
`)}function re(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 se(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 ie(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 G(e){return e.replace(/[^a-zA-Z0-9]/g,"_")}export{Ne as generateNodeConfigsJson,be as generateWorkflowCode};
|
package/dist/constants.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var t=".zibby/output",o="sessions",_=".session-info.json",s=".zibby-stop",e="result.json",I="raw_stream_output.txt",E="events.json",n=Object.freeze(["codebase-memory","code-scan","artifact"]),r=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];export{r as CI_ENV_VARS,t as DEFAULT_OUTPUT_BASE,E as EVENTS_FILE,n as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,I as RAW_OUTPUT_FILE,e as RESULT_FILE,o as SESSIONS_DIR,_ as SESSION_INFO_FILE,s as STOP_REQUEST_FILE};
|
package/dist/graph-compiler.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Wt=Object.defineProperty;var we=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var ae=(o,e)=>()=>(o&&(e=o(o=0)),e);var Je=(o,e)=>{for(var t in e)Wt(o,t,{get:e[t],enumerable:!0})};var Ye,Gt,ue,b,W=ae(()=>{Ye=()=>{},Gt={debug:Ye,info:Ye,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},ue={impl:Gt},b={debug:(...o)=>ue.impl.debug?.(...o),info:(...o)=>ue.impl.info?.(...o),warn:(...o)=>ue.impl.warn?.(...o),error:(...o)=>ue.impl.error?.(...o)}});var rt=ae(()=>{});var nt={};Je(nt,{clearSkills:()=>Vt,getAllSkills:()=>qt,getSkill:()=>ee,getSkillSource:()=>Zt,hasSkill:()=>zt,listSkillIds:()=>Kt,registerSkill:()=>Yt});function Yt(o,e={}){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:r=!1}=e,s=o.id;if(F.has(s)&&!r){let i=Q.get(s);if(!(i===t)){let a=i||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${s}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}F.set(s,Object.freeze({...o})),t===void 0?Q.delete(s):Q.set(s,t)}function ee(o){return F.get(o)||null}function zt(o){return F.has(o)}function Zt(o){return Q.get(o)||null}function qt(){return new Map(F)}function Kt(){return Array.from(F.keys())}function Vt(){F.clear(),Q.clear()}var $e,ve,F,Q,pe=ae(()=>{$e=Symbol.for("@zibby/agent-workflow.skills"),ve=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[$e]||(globalThis[$e]=new Map);globalThis[ve]||(globalThis[ve]=new Map);F=globalThis[$e],Q=globalThis[ve]});var te={};Je(te,{getAgentStrategy:()=>it,invokeAgent:()=>eo,listStrategies:()=>Qt,registerStrategy:()=>Xt,resolveInvocationModel:()=>st});function Xt(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=G.findIndex(t=>t.getName()===o.getName());e>=0?G[e]=o:G.push(o)}function Qt(){return G.map(o=>o.getName())}function st({config:o={},options:e={},strategyName:t,envModel:r}={}){let s=o.models||{},i=e.nodeName&&s[e.nodeName]||null,n=s.default||null,a=o.agent?.[t]?.model||null,u=(typeof r=="string"?r.trim():"")||null;return i||n||a||e.model||u||null}function it(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let i=G.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}b.debug(`[workflow] agent selection: requested=${r}`);let s=G.find(i=>i.getName()===r);if(!s){let i=G.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!s.canHandle(o))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return b.debug(`[workflow] using agent: ${s.getName()}`),s}async function eo(o,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:r},i=it(s),n=r.config||t.config||{},a=st({config:n,options:t,strategyName:i.name,envModel:process.env.MODEL}),u={...t,model:a,workspace:r.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],plugins:t.plugins||e.plugins||[],config:n},d=o,f=u.skills||[];if(f.length>0&&!t.skipPromptFragments){let y=f.map(g=>{let m=ee(g)?.promptFragment;return typeof m=="function"?m():m}).filter(Boolean);y.length>0&&(d+=`
|
|
1
|
+
var Wt=Object.defineProperty;var we=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var ae=(o,e)=>()=>(o&&(e=o(o=0)),e);var Je=(o,e)=>{for(var t in e)Wt(o,t,{get:e[t],enumerable:!0})};var Ye,Gt,ue,b,W=ae(()=>{Ye=()=>{},Gt={debug:Ye,info:Ye,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},ue={impl:Gt},b={debug:(...o)=>ue.impl.debug?.(...o),info:(...o)=>ue.impl.info?.(...o),warn:(...o)=>ue.impl.warn?.(...o),error:(...o)=>ue.impl.error?.(...o)}});var rt=ae(()=>{});var nt={};Je(nt,{clearSkills:()=>Vt,getAllSkills:()=>qt,getSkill:()=>ee,getSkillSource:()=>Zt,hasSkill:()=>zt,listSkillIds:()=>Kt,registerSkill:()=>Yt});function Yt(o,e={}){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:r=!1}=e,s=o.id;if(F.has(s)&&!r){let i=Q.get(s);if(!(i===t)){let a=i||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${s}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}F.set(s,Object.freeze({...o})),t===void 0?Q.delete(s):Q.set(s,t)}function ee(o){return F.get(o)||null}function zt(o){return F.has(o)}function Zt(o){return Q.get(o)||null}function qt(){return new Map(F)}function Kt(){return Array.from(F.keys())}function Vt(){F.clear(),Q.clear()}var $e,ve,F,Q,pe=ae(()=>{$e=Symbol.for("@zibby/agent-workflow.skills"),ve=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[$e]||(globalThis[$e]=new Map);globalThis[ve]||(globalThis[ve]=new Map);F=globalThis[$e],Q=globalThis[ve]});var te={};Je(te,{getAgentStrategy:()=>it,invokeAgent:()=>eo,listStrategies:()=>Qt,registerStrategy:()=>Xt,resolveInvocationModel:()=>st});function Xt(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=G.findIndex(t=>t.getName()===o.getName());e>=0?G[e]=o:G.push(o)}function Qt(){return G.map(o=>o.getName())}function st({config:o={},options:e={},strategyName:t,envModel:r}={}){let s=o.models||{},i=e.nodeName&&s[e.nodeName]||null,n=s.default||null,a=o.agent?.[t]?.model||null,u=(typeof r=="string"?r.trim():"")||null;return i||n||a||e.model||u||null}function it(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let i=G.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}b.debug(`[workflow] agent selection: requested=${r}`);let s=G.find(i=>i.getName()===r);if(!s){let i=G.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!s.canHandle(o))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return b.debug(`[workflow] using agent: ${s.getName()}`),s}async function eo(o,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:r},i=it(s),n=r.config||t.config||{},a=st({config:n,options:t,strategyName:i.name,envModel:process.env.MODEL}),u={...t,model:a,workspace:r.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],extraMcpServers:t.extraMcpServers||r.extraMcpServers||e.extraMcpServers||[],plugins:t.plugins||e.plugins||[],config:n},d=o,f=u.skills||[];if(f.length>0&&!t.skipPromptFragments){let y=f.map(g=>{let m=ee(g)?.promptFragment;return typeof m=="function"?m():m}).filter(Boolean);y.length>0&&(d+=`
|
|
2
2
|
|
|
3
3
|
${y.join(`
|
|
4
4
|
|
|
@@ -29,7 +29,7 @@ ${Ke}`,e.col=Ve))}return o(n,r,s)}}var Ee=class{constructor(){this._currentNode=
|
|
|
29
29
|
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Ze,e):process.stdout.write.bind(process.stdout)(`${X} ${Ze} ${e}
|
|
30
30
|
`)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(qe,t):process.stdout.write.bind(process.stdout)(`${X} ${qe} ${t}
|
|
31
31
|
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Ie,x.red(e)):process.stdout.write.bind(process.stdout)(`${X} ${Ie} ${x.red(e)}
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Jt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:s}=t;if(s)for(let n of s)this._rawWrite(`${be} ${n}`);let i=r?x.dim(` ${Xe(r)}`):"";this._rawWrite(`${ze} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:s}=r,i=s?x.dim(` ${Xe(s)}`):"";this._rawWrite(`${Ie} ${x.red(t)}`),this._rawWrite(`${ze} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},O=new Ee;var de=".zibby/output",et="sessions",K=".session-info.json",tt=".zibby-stop";var zo=Object.freeze(["codebase-memory","code-scan"]),ot=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];H.helpers.inc||H.registerHelper("inc",o=>Number(o)+1);H.helpers.json||H.registerHelper("json",o=>JSON.stringify(o,null,2));H.helpers.eq||H.registerHelper("eq",(o,e)=>o===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new le(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return b.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){b.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(b.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){return b.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&b.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=H.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(r())):i=this.prompt;let n=s("_skillHints");n&&(i=`${n}
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Jt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:s}=t;if(s)for(let n of s)this._rawWrite(`${be} ${n}`);let i=r?x.dim(` ${Xe(r)}`):"";this._rawWrite(`${ze} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:s}=r,i=s?x.dim(` ${Xe(s)}`):"";this._rawWrite(`${Ie} ${x.red(t)}`),this._rawWrite(`${ze} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},O=new Ee;var de=".zibby/output",et="sessions",K=".session-info.json",tt=".zibby-stop";var zo=Object.freeze(["codebase-memory","code-scan","artifact"]),ot=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];H.helpers.inc||H.registerHelper("inc",o=>Number(o)+1);H.helpers.json||H.registerHelper("json",o=>JSON.stringify(o,null,2));H.helpers.eq||H.registerHelper("eq",(o,e)=>o===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new le(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return b.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){b.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(b.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){return b.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&b.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=H.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(r())):i=this.prompt;let n=s("_skillHints");n&&(i=`${n}
|
|
33
33
|
|
|
34
34
|
${i}`);let a=r(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Ae(d,K);if(ct(l)){let y=JSON.parse(at(l,"utf-8"));y.currentNode=this.name,ke(l,JSON.stringify(y,null,2),"utf-8")}let c=Ae(d,"..",K);if(ct(c))try{let y=JSON.parse(at(c,"utf-8"));y.currentNode=this.name,ke(c,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(l){b.debug(`[workflow] could not update session info: ${l.message}`)}let f=null;for(let l=0;l<=this.retries;l++)try{b.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=r().config||{},y=c.agents||{},g=this.config.agent??y[this.name]??null,m={state:r()};g&&(m.preferredAgent=g);let v={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},I=e?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(oe(),te))).invokeAgent);let h=await I(i,m,v),S,w;if(typeof h=="string"?(S=h,w=null):h.structured?(S=h.raw||JSON.stringify(h.structured,null,2),w=h.structured):(S=h.raw||JSON.stringify(h,null,2),w=h.extracted||null),d)try{let p=Ae(d,this.name,"raw_stream_output.txt");to(oo(p),{recursive:!0}),ke(p,typeof S=="string"?S:JSON.stringify(S),"utf-8")}catch(p){b.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&w){b.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(w,null,2)}`);let p=w;if(typeof this.onComplete=="function")try{p=await this.onComplete(r(),w)}catch($){b.warn(`[workflow] onComplete hook failed: ${$.message}`)}return{success:!0,output:p,raw:S}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:S}),raw:S}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(S);return b.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),O.step("Output parsed"),{success:!0,output:p,raw:S}}return{success:!0,output:S,raw:S}}catch(c){f=c,l<this.retries&&b.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:f.message,raw:null}}};W();W();import{mkdirSync as so,existsSync as Y,statSync as yt,readdirSync as St,rmSync as io}from"node:fs";import{spawn as ht}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as ao}from"node:url";import{AsyncLocalStorage as co}from"node:async_hooks";import{AsyncLocalStorage as ro}from"node:async_hooks";var xe=new ro;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 lt(o,e){let t=xe.getStore()||re(),r=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null});return xe.run(r,e)}var Oe=new Map,Pe=new Map,ut=new Map;function dt(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Oe.set(o,e),Pe.set(o,"ready"),ut.set(o,{...t,cachedAt:Date.now()})}function pt(o,e){Pe.set(o,"failed"),ut.set(o,{error:e?.message||String(e),failedAt:Date.now()}),Oe.delete(o)}function ft(o){return Pe.get(o)==="ready"?Oe.get(o):null}var fe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function lo(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var P=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}},gt=new co,mt=Promise.resolve();async function uo(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([n,a])=>typeof n=="string"&&n&&typeof a=="string"):[];if(t.length===0)return e();let r=gt.getStore()===!0,s=null;if(!r){let n=mt;mt=new Promise(a=>{s=a}),await n}let i=new Map;try{for(let[n,a]of t)i.set(n,Object.prototype.hasOwnProperty.call(process.env,n)?process.env[n]:void 0),process.env[n]=a;return b.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await gt.run(!0,e)}finally{for(let[n,a]of i)a===void 0?delete process.env[n]:process.env[n]=a;s&&s()}}function po(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,r=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!r||!s)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:s}}async function fo({apiBase:o,authToken:e,body:t}){let r;try{r=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(i){throw new P("network",`begin fetch failed: ${i.message}`)}let s=null;try{s=await r.json()}catch{}if(!r.ok){if(r.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(r.status===429){let i=s?.quotaInfo||{},n=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw n.code="SUBGRAPH_QUOTA_EXCEEDED",n.status=429,n.quotaInfo=i,n}if(r.status===400&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new P("begin-status",`begin returned ${r.status}`)}return s?.data||s}async function J({apiBase:o,authToken:e,payload:t}){try{let r=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});r.ok||b.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){b.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function ho(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(Y(t)&&Y(r))return;so(e,{recursive:!0});let s=U(e,".lock"),i=!1;try{let{openSync:n,closeSync:a}=await import("node:fs"),u=n(s,"wx");a(u),i=!0}catch(n){if(n.code!=="EEXIST")throw n}if(!i){let n=Date.now()+3e4;for(;Date.now()<n;){if(Y(t)&&Y(r))return;await new Promise(a=>setTimeout(a,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let f=ht("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),l=ht("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(l.stdin);let c,y,g=()=>{if(c!==void 0&&y!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(y!==0)return d(new Error(`tar exited ${y}`));u()}};f.on("close",m=>{c=m,g()}),l.on("close",m=>{y=m,g()}),f.on("error",d),l.on("error",d)});let{writeFileSync:n,unlinkSync:a}=await import("node:fs");n(t,"");try{a(s)}catch{}}catch(n){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new P("bundle-extract-failed",n.message)}}async function go(o){let e=U(o,"graph.mjs");if(!Y(e))throw new P("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(ao(e).href)}catch(s){throw new P("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let r=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!r)throw new P("entry-class-missing","no buildGraph() class export found");return r}async function wt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=re(),r;try{r=po()}catch(p){throw p}b.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let s=await fo({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:n,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:f,bundleReady:l,nodeConfigs:c}=s,y=lo();if(n&&n!==y)throw await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:`runtimeTag mismatch: parent=${y} child=${n}`,code:"RUNTIME_MISMATCH"}}}),new P("runtime-mismatch",`${y} vs ${n}`);if(!l||!a)throw await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new P("no-bundle","workflow bundle not built yet");let g=ft(o);if(!g){let p=U(fe,`${f}@${d||"0"}`);try{await ho(a,p);try{yo()}catch{}}catch($){throw $.fallback&&await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{g=await go(p),dt(o,g,{workflowUuid:f,version:d,runtimeTag:n,cacheDir:p})}catch($){throw pt(o,$),await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new P("import-failed",$.message)}}let m=Date.now(),v=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,I=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...I?{nodeConfigs:c}:{}},S,w;try{S=await uo(v,async()=>{let $=await(typeof g=="function"&&g.prototype?.buildGraph?new g:g).buildGraph();return lt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,h,{signal:e.signal}))}),w=S&&typeof S=="object"&&"state"in S?S.state:S}catch(p){throw await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-m}}),p}if(S&&typeof S=="object"&&S.stoppedExternally){await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",finalState:w,durationMs:Date.now()-m}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:w,durationMs:Date.now()-m}}),{finalState:w,executionId:i}}function mo(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),s;try{s=yt(r)}catch{continue}if(s.isDirectory()){let i;try{i=St(r)}catch{continue}for(let n of i)t.push(U(r,n))}else e+=s.size}return e}function yo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(fe))return{evicted:0,freedBytes:0};let e=St(fe),t=[],r=0;for(let a of e){let u=U(fe,a),d;try{d=yt(u)}catch{continue}let f=d.isDirectory()?mo(u):d.size;r+=f,t.push({name:a,full:u,size:f,mtimeMs:d.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let s=Math.floor(o*.7),i=0,n=0;for(let a of t){if(r-i<=s)break;if(!Y(U(a.full,".lock")))try{io(a.full,{recursive:!0,force:!0}),i+=a.size,n+=1}catch(u){b.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return n>0&&b.info(`[sub-graph cache] evicted ${n} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:n,freedBytes:i,totalBytes:r-i}}catch(e){return b.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var So=2e3,wo=600*1e3,_o=new Set(["completed","failed","canceled","timeout"]);function bo(){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 Io(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Eo(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function $o(){return process.env.EXECUTION_ID||null}function _t(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 bt(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=re(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{b.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:w}=await wt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=_t(w,e.output);return b.info(`[sub-graph] '${o}' completed in-process`),p}catch(w){if(w instanceof P||w?.fallback)b.info(`[sub-graph] in-process fallback for '${o}': ${w.reason||"unknown"} \u2014 using HTTP`);else throw w}let s=bo(),i=Io(),n=Eo(),a=$o(),u=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(o)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};b.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let f=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(d)});if(!f.ok){let w=null,p="";try{w=await f.json(),p=w?.error||w?.message||JSON.stringify(w)}catch{p=await f.text().catch(()=>"")}if(f.status===429){let k=w?.quotaInfo||{},M=new Error(`Sub-graph '${o}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=o,M.quotaInfo=k,M}if(f.status===400){let k=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=o,k.validationErrors=w?.validationErrors||null,k.missing=w?.missing||null,k}let $=new Error(`Sub-graph '${o}' trigger rejected (${f.status}): ${p}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=f.status,$.subgraph=o,$}let l=await f.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return b.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let y=Number.isFinite(e.timeoutMs)?e.timeoutMs:wo,g=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:So,m=`${s}/executions/${encodeURIComponent(c)}`,v=Date.now()+y,I="accepted",h=0;for(;Date.now()<v;){await new Promise(k=>setTimeout(k,g)),h+=1;let w=await fetch(m,{headers:{Authorization:`Bearer ${n}`}});if(!w.ok){if(w.status>=500){b.warn(`[sub-graph] status poll for ${c} returned ${w.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${w.status}`)}let p=await w.json(),$=p?.data||p?.execution||p;if(I=$?.status||I,_o.has(I)){if(I!=="completed"){let _=new Error(`Sub-graph '${o}' (${c}) ended in status '${I}'`);throw _.subgraphJobId=c,_.subgraphStatus=I,_}let k=$?.finalState||$?.state||{},M=_t(k,e.output);return b.info(`[sub-graph] '${o}' (${c}) completed after ${h} polls`),M}}let S=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(y/1e3)}s (last status: ${I})`);throw S.subgraphJobId=c,S.subgraphStatus=I,S}import{existsSync as It,readFileSync as vo}from"node:fs";import{join as Ne,dirname as Et}from"node:path";var he=class{static async loadContext(e,t,r={}){let s={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Et(Ne(t,e));for(let u of i){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let f=u.replace(/\.[^.]+$/,"").toLowerCase();s[f]=d}}}let n=r.discovery||{};for(let[a,u]of Object.entries(n))try{let d=Ne(t,u);It(d)&&(s[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return s}static async findAndMergeContextFiles(e,t,r){let s=[],i=t;for(;i.startsWith(r);){let n=Ne(i,e);if(It(n))try{s.unshift(await this.loadFile(n))}catch(u){console.warn(`[workflow] could not load ${e} from ${n}: ${u.message}`)}let a=Et(i);if(a===i)break;i=a}return s.length===0?null:s.every(n=>typeof n=="string")?s.join(`
|
|
35
35
|
|
package/dist/graph.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Pe=Object.defineProperty;var st=(s,t)=>()=>(s&&(t=s(s=0)),t);var Dt=(s,t)=>{for(var e in t)Pe(s,e,{get:t[e],enumerable:!0})};var Lt,Re,it,I,V=st(()=>{Lt=()=>{},Re={debug:Lt,info:Lt,warn:(...s)=>console.warn("[workflow]",...s),error:(...s)=>console.error("[workflow]",...s)},it={impl:Re},I={debug:(...s)=>it.impl.debug?.(...s),info:(...s)=>it.impl.info?.(...s),warn:(...s)=>it.impl.warn?.(...s),error:(...s)=>it.impl.error?.(...s)}});var Vt=st(()=>{});var Kt={};Dt(Kt,{clearSkills:()=>We,getAllSkills:()=>Le,getSkill:()=>yt,getSkillSource:()=>De,hasSkill:()=>je,listSkillIds:()=>Ue,registerSkill:()=>Me});function Me(s,t={}){if(!s||typeof s.id!="string")throw new Error("Skill definition must include a string id");let{source:e,override:r=!1}=t,o=s.id;if(U.has(o)&&!r){let i=X.get(o);if(!(i===e)){let a=i||"first-party",u=e||"first-party";throw new Error(`Skill id collision: "${o}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}U.set(o,Object.freeze({...s})),e===void 0?X.delete(o):X.set(o,e)}function yt(s){return U.get(s)||null}function je(s){return U.has(s)}function De(s){return X.get(s)||null}function Le(){return new Map(U)}function Ue(){return Array.from(U.keys())}function We(){U.clear(),X.clear()}var mt,St,U,X,wt=st(()=>{mt=Symbol.for("@zibby/agent-workflow.skills"),St=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[mt]||(globalThis[mt]=new Map);globalThis[St]||(globalThis[St]=new Map);U=globalThis[mt],X=globalThis[St]});var It={};Dt(It,{getAgentStrategy:()=>Qt,invokeAgent:()=>He,listStrategies:()=>Ge,registerStrategy:()=>Fe,resolveInvocationModel:()=>Xt});function Fe(s){if(!s||typeof s.getName!="function"||typeof s.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=W.findIndex(e=>e.getName()===s.getName());t>=0?W[t]=s:W.push(s)}function Ge(){return W.map(s=>s.getName())}function Xt({config:s={},options:t={},strategyName:e,envModel:r}={}){let o=s.models||{},i=t.nodeName&&o[t.nodeName]||null,n=o.default||null,a=s.agent?.[e]?.model||null,u=(typeof r=="string"?r.trim():"")||null;return i||n||a||t.model||u||null}function Qt(s={}){let{state:t={},preferredAgent:e=null}=s,r=e||t.agentType||process.env.AGENT_TYPE;if(!r){let i=W.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}I.debug(`[workflow] agent selection: requested=${r}`);let o=W.find(i=>i.getName()===r);if(!o){let i=W.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!o.canHandle(s))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${o.getName()}`),o}async function He(s,t={},e={}){let r=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},o={...t,state:r},i=Qt(o),n=r.config||e.config||{},a=Xt({config:n,options:e,strategyName:i.name,envModel:process.env.MODEL}),u={...e,model:a,workspace:r.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],plugins:e.plugins||t.plugins||[],config:n},p=s,h=u.skills||[];if(h.length>0&&!e.skipPromptFragments){let y=h.map(S=>{let w=yt(S)?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);y.length>0&&(p+=`
|
|
1
|
+
var Pe=Object.defineProperty;var st=(s,t)=>()=>(s&&(t=s(s=0)),t);var Dt=(s,t)=>{for(var e in t)Pe(s,e,{get:t[e],enumerable:!0})};var Lt,Re,it,I,V=st(()=>{Lt=()=>{},Re={debug:Lt,info:Lt,warn:(...s)=>console.warn("[workflow]",...s),error:(...s)=>console.error("[workflow]",...s)},it={impl:Re},I={debug:(...s)=>it.impl.debug?.(...s),info:(...s)=>it.impl.info?.(...s),warn:(...s)=>it.impl.warn?.(...s),error:(...s)=>it.impl.error?.(...s)}});var Vt=st(()=>{});var Kt={};Dt(Kt,{clearSkills:()=>We,getAllSkills:()=>Le,getSkill:()=>yt,getSkillSource:()=>De,hasSkill:()=>je,listSkillIds:()=>Ue,registerSkill:()=>Me});function Me(s,t={}){if(!s||typeof s.id!="string")throw new Error("Skill definition must include a string id");let{source:e,override:r=!1}=t,o=s.id;if(U.has(o)&&!r){let i=X.get(o);if(!(i===e)){let a=i||"first-party",u=e||"first-party";throw new Error(`Skill id collision: "${o}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}U.set(o,Object.freeze({...s})),e===void 0?X.delete(o):X.set(o,e)}function yt(s){return U.get(s)||null}function je(s){return U.has(s)}function De(s){return X.get(s)||null}function Le(){return new Map(U)}function Ue(){return Array.from(U.keys())}function We(){U.clear(),X.clear()}var mt,St,U,X,wt=st(()=>{mt=Symbol.for("@zibby/agent-workflow.skills"),St=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[mt]||(globalThis[mt]=new Map);globalThis[St]||(globalThis[St]=new Map);U=globalThis[mt],X=globalThis[St]});var It={};Dt(It,{getAgentStrategy:()=>Qt,invokeAgent:()=>He,listStrategies:()=>Ge,registerStrategy:()=>Fe,resolveInvocationModel:()=>Xt});function Fe(s){if(!s||typeof s.getName!="function"||typeof s.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=W.findIndex(e=>e.getName()===s.getName());t>=0?W[t]=s:W.push(s)}function Ge(){return W.map(s=>s.getName())}function Xt({config:s={},options:t={},strategyName:e,envModel:r}={}){let o=s.models||{},i=t.nodeName&&o[t.nodeName]||null,n=o.default||null,a=s.agent?.[e]?.model||null,u=(typeof r=="string"?r.trim():"")||null;return i||n||a||t.model||u||null}function Qt(s={}){let{state:t={},preferredAgent:e=null}=s,r=e||t.agentType||process.env.AGENT_TYPE;if(!r){let i=W.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}I.debug(`[workflow] agent selection: requested=${r}`);let o=W.find(i=>i.getName()===r);if(!o){let i=W.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!o.canHandle(s))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${o.getName()}`),o}async function He(s,t={},e={}){let r=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},o={...t,state:r},i=Qt(o),n=r.config||e.config||{},a=Xt({config:n,options:e,strategyName:i.name,envModel:process.env.MODEL}),u={...e,model:a,workspace:r.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],extraMcpServers:e.extraMcpServers||r.extraMcpServers||t.extraMcpServers||[],plugins:e.plugins||t.plugins||[],config:n},p=s,h=u.skills||[];if(h.length>0&&!e.skipPromptFragments){let y=h.map(S=>{let w=yt(S)?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);y.length>0&&(p+=`
|
|
2
2
|
|
|
3
3
|
${y.join(`
|
|
4
4
|
|
|
@@ -29,7 +29,7 @@ ${Gt}`,t.col=Ht))}return s(n,r,o)}}var gt=class{constructor(){this._currentNode=
|
|
|
29
29
|
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(Wt,t):process.stdout.write.bind(process.stdout)(`${K} ${Wt} ${t}
|
|
30
30
|
`)}stepMemory(t){let e=x.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(Ft,e):process.stdout.write.bind(process.stdout)(`${K} ${Ft} ${e}
|
|
31
31
|
`)}stepFail(t){this._origStdoutWrite?this._writeDot(ht,x.red(t)):process.stdout.write.bind(process.stdout)(`${K} ${ht} ${x.red(t)}
|
|
32
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Ce} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:r,details:o}=e;if(o)for(let n of o)this._rawWrite(`${ft} ${n}`);let i=r?x.dim(` ${Jt(r)}`):"";this._rawWrite(`${Ut} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,r={}){this._stopIntercepting();let{duration:o}=r,i=o?x.dim(` ${Jt(o)}`):"";this._rawWrite(`${ht} ${x.red(e)}`),this._rawWrite(`${Ut} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(x.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},O=new gt;var at=".zibby/output",Zt="sessions",z=".session-info.json",zt=".zibby-stop";var Pr=Object.freeze(["codebase-memory","code-scan"]),qt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];F.helpers.inc||F.registerHelper("inc",s=>Number(s)+1);F.helpers.json||F.registerHelper("json",s=>JSON.stringify(s,null,2));F.helpers.eq||F.registerHelper("eq",(s,t)=>s===t);var D=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode&&!t._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=t.outputSchema&&!this.isZodSchema?new nt(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){if(this.config._isRouter)return I.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>e&&typeof e.getAll=="function"?e.getAll():t,o=c=>e&&typeof e.get=="function"?e.get(c):t?.[c];if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(t);return typeof c=="object"&&c!==null&&c.success===!1?{success:!1,error:c.error||"Node execution failed",raw:c.raw||null}:this.isZodSchema?(I.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 I.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=F.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(r())):i=this.prompt;let n=o("_skillHints");n&&(i=`${n}
|
|
32
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Ce} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:r,details:o}=e;if(o)for(let n of o)this._rawWrite(`${ft} ${n}`);let i=r?x.dim(` ${Jt(r)}`):"";this._rawWrite(`${Ut} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,r={}){this._stopIntercepting();let{duration:o}=r,i=o?x.dim(` ${Jt(o)}`):"";this._rawWrite(`${ht} ${x.red(e)}`),this._rawWrite(`${Ut} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(x.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},O=new gt;var at=".zibby/output",Zt="sessions",z=".session-info.json",zt=".zibby-stop";var Pr=Object.freeze(["codebase-memory","code-scan","artifact"]),qt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];F.helpers.inc||F.registerHelper("inc",s=>Number(s)+1);F.helpers.json||F.registerHelper("json",s=>JSON.stringify(s,null,2));F.helpers.eq||F.registerHelper("eq",(s,t)=>s===t);var D=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode&&!t._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=t.outputSchema&&!this.isZodSchema?new nt(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){if(this.config._isRouter)return I.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>e&&typeof e.getAll=="function"?e.getAll():t,o=c=>e&&typeof e.get=="function"?e.get(c):t?.[c];if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(t);return typeof c=="object"&&c!==null&&c.success===!1?{success:!1,error:c.error||"Node execution failed",raw:c.raw||null}:this.isZodSchema?(I.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 I.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=F.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(r())):i=this.prompt;let n=o("_skillHints");n&&(i=`${n}
|
|
33
33
|
|
|
34
34
|
${i}`);let a=r(),u=a.cwd||process.cwd(),p=a.sessionPath;try{if(p){let c=$t(p,z);if(ee(c)){let y=JSON.parse(te(c,"utf-8"));y.currentNode=this.name,Et(c,JSON.stringify(y,null,2),"utf-8")}let l=$t(p,"..",z);if(ee(l))try{let y=JSON.parse(te(l,"utf-8"));y.currentNode=this.name,Et(l,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(c){I.debug(`[workflow] could not update session info: ${c.message}`)}let h=null;for(let c=0;c<=this.retries;c++)try{I.debug(`[workflow] node '${this.name}' attempt ${c}`);let l=r().config||{},y=l.agents||{},S=this.config.agent??y[this.name]??null,w={state:r()};S&&(w.preferredAgent=S);let T={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:p,config:l,nodeName:this.name,timeout:this.config?.timeout||3e5},$=t?._coreInvokeAgent;$||($=(await Promise.resolve().then(()=>(bt(),It))).invokeAgent);let f=await $(i,w,T),g,m;if(typeof f=="string"?(g=f,m=null):f.structured?(g=f.raw||JSON.stringify(f.structured,null,2),m=f.structured):(g=f.raw||JSON.stringify(f,null,2),m=f.extracted||null),p)try{let d=$t(p,this.name,"raw_stream_output.txt");Je(Ye(d),{recursive:!0}),Et(d,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(d){I.debug(`[workflow] could not save raw output: ${d.message}`)}if(this.isZodSchema&&m){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let d=m;if(typeof this.onComplete=="function")try{d=await this.onComplete(r(),m)}catch(E){I.warn(`[workflow] onComplete hook failed: ${E.message}`)}return{success:!0,output:d,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:g}),raw:g}}catch(d){throw new Error(`onComplete failed: ${d.message}`,{cause:d})}if(this.parser){let d=this.parser.parse(g);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(d,null,2)}`),O.step("Output parsed"),{success:!0,output:d,raw:g}}return{success:!0,output:g,raw:g}}catch(l){h=l,c<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};V();V();import{mkdirSync as qe,existsSync as H,statSync as ue,readdirSync as pe,rmSync as Ve}from"node:fs";import{spawn as ae}from"node:child_process";import{join as L}from"node:path";import{pathToFileURL as Ke}from"node:url";import{AsyncLocalStorage as Xe}from"node:async_hooks";import{AsyncLocalStorage as Ze}from"node:async_hooks";var vt=new Ze;function Q(){let s=vt.getStore();return s||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 re(s,t){let e=vt.getStore()||Q(),r=Object.freeze({executionId:s.executionId,parentExecutionId:s.parentExecutionId??e.executionId??null,depth:(e.depth||0)+(s.executionId!==e.executionId?1:0),conversationId:s.conversationId!==void 0?s.conversationId:e.conversationId??null,dispatchMode:s.dispatchMode??null});return vt.run(r,t)}var Tt=new Map,At=new Map,se=new Map;function oe(s,t,e={}){if(!s||typeof s!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");Tt.set(s,t),At.set(s,"ready"),se.set(s,{...e,cachedAt:Date.now()})}function ne(s,t){At.set(s,"failed"),se.set(s,{error:t?.message||String(t),failedAt:Date.now()}),Tt.delete(s)}function ie(s){return At.get(s)==="ready"?Tt.get(s):null}var ct=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Qe(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var P=class extends Error{constructor(t,e){super(`in-process sub-graph fallback: ${t}${e?` (${e})`:""}`),this.fallback=!0,this.reason=t,this.detail=e||null,this.name="SubgraphFallback"}},ce=new Xe,le=Promise.resolve();async function tr(s,t){let e=s&&typeof s=="object"&&!Array.isArray(s)?Object.entries(s).filter(([n,a])=>typeof n=="string"&&n&&typeof a=="string"):[];if(e.length===0)return t();let r=ce.getStore()===!0,o=null;if(!r){let n=le;le=new Promise(a=>{o=a}),await n}let i=new Map;try{for(let[n,a]of e)i.set(n,Object.prototype.hasOwnProperty.call(process.env,n)?process.env[n]:void 0),process.env[n]=a;return I.debug(`[in-process subgraph] scoped ${e.length} child env var(s)${r?" (nested)":""}`),await ce.run(!0,t)}finally{for(let[n,a]of i)a===void 0?delete process.env[n]:process.env[n]=a;o&&o()}}function er(){let s=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),e=s||t,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!e||!r||!o)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:e,projectId:r,authToken:o}}async function rr({apiBase:s,authToken:t,body:e}){let r;try{r=await fetch(`${s}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)})}catch(i){throw new P("network",`begin fetch failed: ${i.message}`)}let o=null;try{o=await r.json()}catch{}if(!r.ok){if(r.status===404){let i=new Error(`Sub-graph child '${e.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(r.status===429){let i=o?.quotaInfo||{},n=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw n.code="SUBGRAPH_QUOTA_EXCEEDED",n.status=429,n.quotaInfo=i,n}if(r.status===400&&o?.validationErrors){let i=new Error(`Sub-graph rejected input: ${o?.error||o?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=o.validationErrors,i.missing=o.missing,i}throw new P("begin-status",`begin returned ${r.status}`)}return o?.data||o}async function G({apiBase:s,authToken:t,payload:e}){try{let r=await fetch(`${s}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)});r.ok||I.warn(`[in-process subgraph] finalize returned ${r.status} for ${e.childExecutionId}`)}catch(r){I.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function sr(s,t){let e=L(t,".ready"),r=L(t,"graph.mjs");if(H(e)&&H(r))return;qe(t,{recursive:!0});let o=L(t,".lock"),i=!1;try{let{openSync:n,closeSync:a}=await import("node:fs"),u=n(o,"wx");a(u),i=!0}catch(n){if(n.code!=="EEXIST")throw n}if(!i){let n=Date.now()+3e4;for(;Date.now()<n;){if(H(e)&&H(r))return;await new Promise(a=>setTimeout(a,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,p)=>{let h=ae("curl",["-fsSL",s],{stdio:["ignore","pipe","inherit"]}),c=ae("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(c.stdin);let l,y,S=()=>{if(l!==void 0&&y!==void 0){if(l!==0)return p(new Error(`curl exited ${l}`));if(y!==0)return p(new Error(`tar exited ${y}`));u()}};h.on("close",w=>{l=w,S()}),c.on("close",w=>{y=w,S()}),h.on("error",p),c.on("error",p)});let{writeFileSync:n,unlinkSync:a}=await import("node:fs");n(e,"");try{a(o)}catch{}}catch(n){try{let{unlinkSync:a}=await import("node:fs");a(o)}catch{}throw new P("bundle-extract-failed",n.message)}}async function or(s){let t=L(s,"graph.mjs");if(!H(t))throw new P("entry-missing",`graph.mjs missing under ${s}`);let e;try{e=await import(Ke(t).href)}catch(o){throw new P("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=e.default||Object.values(e).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new P("entry-class-missing","no buildGraph() class export found");return r}async function de(s,t={}){if(!s||typeof s!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let e=Q(),r;try{r=er()}catch(d){throw d}I.debug(`[in-process subgraph] begin '${s}' parent=${e.executionId||"<root>"}`);let o=await rr({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:e.executionId,childWorkflowType:s,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:i,runtimeTag:n,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:p,workflowUuid:h,bundleReady:c,nodeConfigs:l}=o,y=Qe();if(n&&n!==y)throw await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:`runtimeTag mismatch: parent=${y} child=${n}`,code:"RUNTIME_MISMATCH"}}}),new P("runtime-mismatch",`${y} vs ${n}`);if(!c||!a)throw await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new P("no-bundle","workflow bundle not built yet");let S=ie(s);if(!S){let d=L(ct,`${h}@${p||"0"}`);try{await sr(a,d);try{ir()}catch{}}catch(E){throw E.fallback&&await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:E.message,code:E.reason}}}),E}try{S=await or(d),oe(s,S,{workflowUuid:h,version:p,runtimeTag:n,cacheDir:d})}catch(E){throw ne(s,E),await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:E.message,code:E.reason||"IMPORT_FAILED"}}}),E.fallback?E:new P("import-failed",E.message)}}let w=Date.now(),T=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,$=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,f={...t.input||{},...$?{nodeConfigs:l}:{}},g,m;try{g=await tr(T,async()=>{let E=await(typeof S=="function"&&S.prototype?.buildGraph?new S:S).buildGraph();return re({executionId:i,parentExecutionId:e.executionId,conversationId:t.conversationId!==void 0?t.conversationId:e.conversationId,dispatchMode:"inprocess"},()=>E.run(t.parentAgent,f,{signal:t.signal}))}),m=g&&typeof g=="object"&&"state"in g?g.state:g}catch(d){throw await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:d.message,code:d.code||"CHILD_THREW",stack:d.stack},durationMs:Date.now()-w}}),d}if(g&&typeof g=="object"&&g.stoppedExternally){await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",finalState:m,durationMs:Date.now()-w}});let d=new Error(`Sub-graph '${s}' canceled by parent abort`);throw d.code="SUBGRAPH_CANCELED",d.subgraphJobId=i,d}return await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:m,durationMs:Date.now()-w}}),{finalState:m,executionId:i}}function nr(s){let t=0,e=[s];for(;e.length;){let r=e.pop(),o;try{o=ue(r)}catch{continue}if(o.isDirectory()){let i;try{i=pe(r)}catch{continue}for(let n of i)e.push(L(r,n))}else t+=o.size}return t}function ir({cap:s=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!H(ct))return{evicted:0,freedBytes:0};let t=pe(ct),e=[],r=0;for(let a of t){let u=L(ct,a),p;try{p=ue(u)}catch{continue}let h=p.isDirectory()?nr(u):p.size;r+=h,e.push({name:a,full:u,size:h,mtimeMs:p.mtimeMs})}if(r<=s)return{evicted:0,freedBytes:0,totalBytes:r};e.sort((a,u)=>a.mtimeMs-u.mtimeMs);let o=Math.floor(s*.7),i=0,n=0;for(let a of e){if(r-i<=o)break;if(!H(L(a.full,".lock")))try{Ve(a.full,{recursive:!0,force:!0}),i+=a.size,n+=1}catch(u){I.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return n>0&&I.info(`[sub-graph cache] evicted ${n} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:n,freedBytes:i,totalBytes:r-i}}catch(t){return I.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var ar=2e3,cr=600*1e3,lr=new Set(["completed","failed","canceled","timeout"]);function ur(){let s=process.env.PROGRESS_API_URL;if(!s)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 s.replace(/\/executions\/?$/,"")}function pr(){let s=process.env.PROJECT_ID;if(!s)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return s}function dr(){let s=process.env.PROJECT_API_TOKEN;if(!s)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return s}function fr(){return process.env.EXECUTION_ID||null}function fe(s,t){return t==null?s:typeof t=="function"?t(s):typeof t=="string"?t.split(".").reduce((e,r)=>e==null?e:e[r],s):s}async function he(s,t={}){if(!s||typeof s!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let e=Q(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((e.depth||0)>=r)throw new Error(`dispatchSubgraph('${s}'): sub-graph depth ${e.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{I.debug(`[sub-graph] trying in-process for '${s}'`);let{finalState:m}=await de(s,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),d=fe(m,t.output);return I.info(`[sub-graph] '${s}' completed in-process`),d}catch(m){if(m instanceof P||m?.fallback)I.info(`[sub-graph] in-process fallback for '${s}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let o=ur(),i=pr(),n=dr(),a=fr(),u=`${o}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(s)}/trigger`,p={input:t.input||{},...a?{parentExecutionId:a}:{},...t.conversationId?{conversationId:t.conversationId}:{}};I.info(`[sub-graph] dispatching '${s}' (${t.async?"async":"sync"}) from parent ${a||"<none>"}`);let h=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(p)});if(!h.ok){let m=null,d="";try{m=await h.json(),d=m?.error||m?.message||JSON.stringify(m)}catch{d=await h.text().catch(()=>"")}if(h.status===429){let A=m?.quotaInfo||{},M=new Error(`Sub-graph '${s}' blocked by execution quota (${A.used??"?"}/${A.limit??"?"} on plan ${A.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=s,M.quotaInfo=A,M}if(h.status===400){let A=new Error(`Sub-graph '${s}' rejected input: ${d}`);throw A.code="SUBGRAPH_INVALID_INPUT",A.status=400,A.subgraph=s,A.validationErrors=m?.validationErrors||null,A.missing=m?.missing||null,A}let E=new Error(`Sub-graph '${s}' trigger rejected (${h.status}): ${d}`);throw E.code="SUBGRAPH_TRIGGER_FAILED",E.status=h.status,E.subgraph=s,E}let c=await h.json(),l=c?.data?.jobId||c?.jobId;if(!l)throw new Error(`Sub-graph '${s}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(t.async)return I.info(`[sub-graph] async dispatch of '${s}' \u2192 jobId=${l} (not waiting)`),{jobId:l,status:"accepted",workflow:s};let y=Number.isFinite(t.timeoutMs)?t.timeoutMs:cr,S=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:ar,w=`${o}/executions/${encodeURIComponent(l)}`,T=Date.now()+y,$="accepted",f=0;for(;Date.now()<T;){await new Promise(A=>setTimeout(A,S)),f+=1;let m=await fetch(w,{headers:{Authorization:`Bearer ${n}`}});if(!m.ok){if(m.status>=500){I.warn(`[sub-graph] status poll for ${l} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${l}: ${m.status}`)}let d=await m.json(),E=d?.data||d?.execution||d;if($=E?.status||$,lr.has($)){if($!=="completed"){let _=new Error(`Sub-graph '${s}' (${l}) ended in status '${$}'`);throw _.subgraphJobId=l,_.subgraphStatus=$,_}let A=E?.finalState||E?.state||{},M=fe(A,t.output);return I.info(`[sub-graph] '${s}' (${l}) completed after ${f} polls`),M}}let g=new Error(`Sub-graph '${s}' (${l}) timed out after ${Math.round(y/1e3)}s (last status: ${$})`);throw g.subgraphJobId=l,g.subgraphStatus=$,g}import{existsSync as ge,readFileSync as hr}from"node:fs";import{join as kt,dirname as me}from"node:path";var lt=class{static async loadContext(t,e,r={}){let o={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(t){let a=me(kt(e,t));for(let u of i){let p=await this.findAndMergeContextFiles(u,a,e);if(p){let h=u.replace(/\.[^.]+$/,"").toLowerCase();o[h]=p}}}let n=r.discovery||{};for(let[a,u]of Object.entries(n))try{let p=kt(e,u);ge(p)&&(o[a]=await this.loadFile(p))}catch(p){console.warn(`[workflow] could not load context '${a}' from '${u}': ${p.message}`)}return o}static async findAndMergeContextFiles(t,e,r){let o=[],i=e;for(;i.startsWith(r);){let n=kt(i,t);if(ge(n))try{o.unshift(await this.loadFile(n))}catch(u){console.warn(`[workflow] could not load ${t} from ${n}: ${u.message}`)}let a=me(i);if(a===i)break;i=a}return o.length===0?null:o.every(n=>typeof n=="string")?o.join(`
|
|
35
35
|
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var uo=Object.defineProperty;var Ie=(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 ge=(o,e)=>()=>(o&&(e=o(o=0)),e);var nt=(o,e)=>{for(var t in e)uo(o,t,{get:e[t],enumerable:!0})};function ho(o){re.impl={...it,...o}}var st,it,re,E,F=ge(()=>{st=()=>{},it={debug:st,info:st,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},re={impl:it};E={debug:(...o)=>re.impl.debug?.(...o),info:(...o)=>re.impl.info?.(...o),warn:(...o)=>re.impl.warn?.(...o),error:(...o)=>re.impl.error?.(...o)}});var Ne,Oe=ge(()=>{Ne=class{constructor(e,t,r=0){this.name=e,this.description=t,this.priority=r}async invoke(e,t={}){throw new Error(`${this.constructor.name}.invoke() must be implemented`)}canHandle(e){throw new Error(`${this.constructor.name}.canHandle() must be implemented`)}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var bt={};nt(bt,{clearSkills:()=>_t,getAllSkills:()=>wt,getSkill:()=>q,getSkillSource:()=>yt,hasSkill:()=>mt,listSkillIds:()=>St,registerSkill:()=>gt});function gt(o,e={}){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:r=!1}=e,i=o.id;if(G.has(i)&&!r){let s=ie.get(i);if(!(s===t)){let a=s||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${i}" is already registered by ${a}; ${l} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}G.set(i,Object.freeze({...o})),t===void 0?ie.delete(i):ie.set(i,t)}function q(o){return G.get(o)||null}function mt(o){return G.has(o)}function yt(o){return ie.get(o)||null}function wt(){return new Map(G)}function St(){return Array.from(G.keys())}function _t(){G.clear(),ie.clear()}var Pe,Ce,G,ie,ae=ge(()=>{Pe=Symbol.for("@zibby/agent-workflow.skills"),Ce=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Pe]||(globalThis[Pe]=new Map);globalThis[Ce]||(globalThis[Ce]=new Map);G=globalThis[Pe],ie=globalThis[Ce]});var ce={};nt(ce,{getAgentStrategy:()=>je,invokeAgent:()=>$t,listStrategies:()=>It,registerStrategy:()=>Et,resolveInvocationModel:()=>vt});function Et(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=H.findIndex(t=>t.getName()===o.getName());e>=0?H[e]=o:H.push(o)}function It(){return H.map(o=>o.getName())}function vt({config:o={},options:e={},strategyName:t,envModel:r}={}){let i=o.models||{},s=e.nodeName&&i[e.nodeName]||null,n=i.default||null,a=o.agent?.[t]?.model||null,l=(typeof r=="string"?r.trim():"")||null;return s||n||a||e.model||l||null}function je(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let s=H.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}E.debug(`[workflow] agent selection: requested=${r}`);let i=H.find(s=>s.getName()===r);if(!i){let s=H.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${s}`)}if(!i.canHandle(o))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return E.debug(`[workflow] using agent: ${i.getName()}`),i}async function $t(o,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},i={...e,state:r},s=je(i),n=r.config||t.config||{},a=vt({config:n,options:t,strategyName:s.name,envModel:process.env.MODEL}),l={...t,model:a,workspace:r.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],plugins:t.plugins||e.plugins||[],config:n},u=o,f=l.skills||[];if(f.length>0&&!t.skipPromptFragments){let y=f.map(h=>{let g=q(h)?.promptFragment;return typeof g=="function"?g():g}).filter(Boolean);y.length>0&&(u+=`
|
|
1
|
+
var uo=Object.defineProperty;var Ie=(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 ge=(o,e)=>()=>(o&&(e=o(o=0)),e);var nt=(o,e)=>{for(var t in e)uo(o,t,{get:e[t],enumerable:!0})};function ho(o){re.impl={...it,...o}}var st,it,re,E,F=ge(()=>{st=()=>{},it={debug:st,info:st,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},re={impl:it};E={debug:(...o)=>re.impl.debug?.(...o),info:(...o)=>re.impl.info?.(...o),warn:(...o)=>re.impl.warn?.(...o),error:(...o)=>re.impl.error?.(...o)}});var Ne,Oe=ge(()=>{Ne=class{constructor(e,t,r=0){this.name=e,this.description=t,this.priority=r}async invoke(e,t={}){throw new Error(`${this.constructor.name}.invoke() must be implemented`)}canHandle(e){throw new Error(`${this.constructor.name}.canHandle() must be implemented`)}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var bt={};nt(bt,{clearSkills:()=>_t,getAllSkills:()=>wt,getSkill:()=>q,getSkillSource:()=>yt,hasSkill:()=>mt,listSkillIds:()=>St,registerSkill:()=>gt});function gt(o,e={}){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:r=!1}=e,i=o.id;if(G.has(i)&&!r){let s=ie.get(i);if(!(s===t)){let a=s||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${i}" is already registered by ${a}; ${l} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}G.set(i,Object.freeze({...o})),t===void 0?ie.delete(i):ie.set(i,t)}function q(o){return G.get(o)||null}function mt(o){return G.has(o)}function yt(o){return ie.get(o)||null}function wt(){return new Map(G)}function St(){return Array.from(G.keys())}function _t(){G.clear(),ie.clear()}var Pe,Ce,G,ie,ae=ge(()=>{Pe=Symbol.for("@zibby/agent-workflow.skills"),Ce=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Pe]||(globalThis[Pe]=new Map);globalThis[Ce]||(globalThis[Ce]=new Map);G=globalThis[Pe],ie=globalThis[Ce]});var ce={};nt(ce,{getAgentStrategy:()=>je,invokeAgent:()=>$t,listStrategies:()=>It,registerStrategy:()=>Et,resolveInvocationModel:()=>vt});function Et(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=H.findIndex(t=>t.getName()===o.getName());e>=0?H[e]=o:H.push(o)}function It(){return H.map(o=>o.getName())}function vt({config:o={},options:e={},strategyName:t,envModel:r}={}){let i=o.models||{},s=e.nodeName&&i[e.nodeName]||null,n=i.default||null,a=o.agent?.[t]?.model||null,l=(typeof r=="string"?r.trim():"")||null;return s||n||a||e.model||l||null}function je(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let s=H.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}E.debug(`[workflow] agent selection: requested=${r}`);let i=H.find(s=>s.getName()===r);if(!i){let s=H.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${s}`)}if(!i.canHandle(o))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return E.debug(`[workflow] using agent: ${i.getName()}`),i}async function $t(o,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},i={...e,state:r},s=je(i),n=r.config||t.config||{},a=vt({config:n,options:t,strategyName:s.name,envModel:process.env.MODEL}),l={...t,model:a,workspace:r.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],extraMcpServers:t.extraMcpServers||r.extraMcpServers||e.extraMcpServers||[],plugins:t.plugins||e.plugins||[],config:n},u=o,f=l.skills||[];if(f.length>0&&!t.skipPromptFragments){let y=f.map(h=>{let g=q(h)?.promptFragment;return typeof g=="function"?g():g}).filter(Boolean);y.length>0&&(u+=`
|
|
2
2
|
|
|
3
3
|
${y.join(`
|
|
4
4
|
|
|
@@ -29,7 +29,7 @@ ${dt}`,e.col=ut))}return o(n,r,i)}}var me=class{constructor(){this._currentNode=
|
|
|
29
29
|
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(ct,e):process.stdout.write.bind(process.stdout)(`${ne} ${ct} ${e}
|
|
30
30
|
`)}stepMemory(e){let t=N.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(lt,t):process.stdout.write.bind(process.stdout)(`${ne} ${lt} ${t}
|
|
31
31
|
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Te,N.red(e)):process.stdout.write.bind(process.stdout)(`${ne} ${Te} ${N.red(e)}
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${go} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:i}=t;if(i)for(let n of i)this._rawWrite(`${$e} ${n}`);let s=r?N.dim(` ${pt(r)}`):"";this._rawWrite(`${at} ${N.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:i}=r,s=i?N.dim(` ${pt(i)}`):"";this._rawWrite(`${Te} ${N.red(t)}`),this._rawWrite(`${at} ${N.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(N.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},x=new me;var se=".zibby/output",ke="sessions",W=".session-info.json",Ae=".zibby-stop",mo="result.json",yo="raw_stream_output.txt",wo="events.json",So=Object.freeze(["codebase-memory","code-scan"]),xe=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];J.helpers.inc||J.registerHelper("inc",o=>Number(o)+1);J.helpers.json||J.registerHelper("json",o=>JSON.stringify(o,null,2));J.helpers.eq||J.registerHelper("eq",(o,e)=>o===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new oe(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return E.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,i=d=>t&&typeof t.get=="function"?t.get(d):e?.[d];if(typeof this.customExecute=="function"){E.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let d=await this.customExecute(e);return typeof d=="object"&&d!==null&&d.success===!1?{success:!1,error:d.error||"Node execution failed",raw:d.raw||null}:this.isZodSchema?(E.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(d),raw:null}):{success:!0,output:d,raw:null}}catch(d){return E.error(`[workflow] node '${this.name}' failed: ${d.message}`),d.name==="ZodError"&&E.error(`Schema errors: ${JSON.stringify(d.issues||d.errors,null,2)}`),{success:!1,error:d.message,raw:null}}}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=J.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let n=i("_skillHints");n&&(s=`${n}
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${go} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:i}=t;if(i)for(let n of i)this._rawWrite(`${$e} ${n}`);let s=r?N.dim(` ${pt(r)}`):"";this._rawWrite(`${at} ${N.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:i}=r,s=i?N.dim(` ${pt(i)}`):"";this._rawWrite(`${Te} ${N.red(t)}`),this._rawWrite(`${at} ${N.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(N.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},x=new me;var se=".zibby/output",ke="sessions",W=".session-info.json",Ae=".zibby-stop",mo="result.json",yo="raw_stream_output.txt",wo="events.json",So=Object.freeze(["codebase-memory","code-scan","artifact"]),xe=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];J.helpers.inc||J.registerHelper("inc",o=>Number(o)+1);J.helpers.json||J.registerHelper("json",o=>JSON.stringify(o,null,2));J.helpers.eq||J.registerHelper("eq",(o,e)=>o===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new oe(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return E.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,i=d=>t&&typeof t.get=="function"?t.get(d):e?.[d];if(typeof this.customExecute=="function"){E.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let d=await this.customExecute(e);return typeof d=="object"&&d!==null&&d.success===!1?{success:!1,error:d.error||"Node execution failed",raw:d.raw||null}:this.isZodSchema?(E.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(d),raw:null}):{success:!0,output:d,raw:null}}catch(d){return E.error(`[workflow] node '${this.name}' failed: ${d.message}`),d.name==="ZodError"&&E.error(`Schema errors: ${JSON.stringify(d.issues||d.errors,null,2)}`),{success:!1,error:d.message,raw:null}}}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=J.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let n=i("_skillHints");n&&(s=`${n}
|
|
33
33
|
|
|
34
34
|
${s}`);let a=r(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let d=Me(u,W);if(kt(d)){let y=JSON.parse(Tt(d,"utf-8"));y.currentNode=this.name,Be(d,JSON.stringify(y,null,2),"utf-8")}let c=Me(u,"..",W);if(kt(c))try{let y=JSON.parse(Tt(c,"utf-8"));y.currentNode=this.name,Be(c,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(d){E.debug(`[workflow] could not update session info: ${d.message}`)}let f=null;for(let d=0;d<=this.retries;d++)try{E.debug(`[workflow] node '${this.name}' attempt ${d}`);let c=r().config||{},y=c.agents||{},h=this.config.agent??y[this.name]??null,g={state:r()};h&&(g.preferredAgent=h);let I={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:u,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},_=e?._coreInvokeAgent;_||(_=(await Promise.resolve().then(()=>(X(),ce))).invokeAgent);let m=await _(s,g,I),w,S;if(typeof m=="string"?(w=m,S=null):m.structured?(w=m.raw||JSON.stringify(m.structured,null,2),S=m.structured):(w=m.raw||JSON.stringify(m,null,2),S=m.extracted||null),u)try{let p=Me(u,this.name,"raw_stream_output.txt");_o(bo(p),{recursive:!0}),Be(p,typeof w=="string"?w:JSON.stringify(w),"utf-8")}catch(p){E.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&S){E.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(S,null,2)}`);let p=S;if(typeof this.onComplete=="function")try{p=await this.onComplete(r(),S)}catch($){E.warn(`[workflow] onComplete hook failed: ${$.message}`)}return{success:!0,output:p,raw:w}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:w}),raw:w}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(w);return E.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),x.step("Output parsed"),{success:!0,output:p,raw:w}}return{success:!0,output:w,raw:w}}catch(c){f=c,d<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${d+1}/${this.retries})\u2026`)}return{success:!1,error:f.message,raw:null}}};F();F();import{mkdirSync as vo,existsSync as Y,statSync as Bt,readdirSync as Mt,rmSync as $o}from"node:fs";import{spawn as Ct}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as To}from"node:url";import{AsyncLocalStorage as ko}from"node:async_hooks";import{AsyncLocalStorage as Eo}from"node:async_hooks";var De=new Eo;function le(){let o=De.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=De.getStore()||le(),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 De.run(r,e)}var Le=new Map,Fe=new Map,xt=new Map;function Nt(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");Le.set(o,e),Fe.set(o,"ready"),xt.set(o,{...t,cachedAt:Date.now()})}function Ot(o,e){Fe.set(o,"failed"),xt.set(o,{error:e?.message||String(e),failedAt:Date.now()}),Le.delete(o)}function Pt(o){return Fe.get(o)==="ready"?Le.get(o):null}var ye=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Ao(){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"}},Rt=new ko,jt=Promise.resolve();async function xo(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([n,a])=>typeof n=="string"&&n&&typeof a=="string"):[];if(t.length===0)return e();let r=Rt.getStore()===!0,i=null;if(!r){let n=jt;jt=new Promise(a=>{i=a}),await n}let s=new Map;try{for(let[n,a]of t)s.set(n,Object.prototype.hasOwnProperty.call(process.env,n)?process.env[n]:void 0),process.env[n]=a;return E.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await Rt.run(!0,e)}finally{for(let[n,a]of s)a===void 0?delete process.env[n]:process.env[n]=a;i&&i()}}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,i=process.env.PROJECT_API_TOKEN;if(!t||!r||!i)throw new O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:i}}async function Oo({apiBase:o,authToken:e,body:t}){let r;try{r=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(s){throw new O("network",`begin fetch failed: ${s.message}`)}let i=null;try{i=await r.json()}catch{}if(!r.ok){if(r.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(r.status===429){let s=i?.quotaInfo||{},n=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw n.code="SUBGRAPH_QUOTA_EXCEEDED",n.status=429,n.quotaInfo=s,n}if(r.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new O("begin-status",`begin returned ${r.status}`)}return i?.data||i}async function z({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||E.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){E.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function Po(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(Y(t)&&Y(r))return;vo(e,{recursive:!0});let i=U(e,".lock"),s=!1;try{let{openSync:n,closeSync:a}=await import("node:fs"),l=n(i,"wx");a(l),s=!0}catch(n){if(n.code!=="EEXIST")throw n}if(!s){let n=Date.now()+3e4;for(;Date.now()<n;){if(Y(t)&&Y(r))return;await new Promise(a=>setTimeout(a,100))}throw new O("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let f=Ct("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),d=Ct("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(d.stdin);let c,y,h=()=>{if(c!==void 0&&y!==void 0){if(c!==0)return u(new Error(`curl exited ${c}`));if(y!==0)return u(new Error(`tar exited ${y}`));l()}};f.on("close",g=>{c=g,h()}),d.on("close",g=>{y=g,h()}),f.on("error",u),d.on("error",u)});let{writeFileSync:n,unlinkSync:a}=await import("node:fs");n(t,"");try{a(i)}catch{}}catch(n){try{let{unlinkSync:a}=await import("node:fs");a(i)}catch{}throw new O("bundle-extract-failed",n.message)}}async function Co(o){let e=U(o,"graph.mjs");if(!Y(e))throw new O("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(To(e).href)}catch(i){throw new O("import-failed",`${i?.code||i?.name||"unknown"}: ${i.message}`)}let r=t.default||Object.values(t).find(i=>typeof i=="function"&&i.prototype?.buildGraph);if(!r)throw new O("entry-class-missing","no buildGraph() class export found");return r}async function Dt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=le(),r;try{r=No()}catch(p){throw p}E.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let i=await Oo({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:s,runtimeTag:n,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:f,bundleReady:d,nodeConfigs:c}=i,y=Ao();if(n&&n!==y)throw await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:`runtimeTag mismatch: parent=${y} child=${n}`,code:"RUNTIME_MISMATCH"}}}),new O("runtime-mismatch",`${y} vs ${n}`);if(!d||!a)throw await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new O("no-bundle","workflow bundle not built yet");let h=Pt(o);if(!h){let p=U(ye,`${f}@${u||"0"}`);try{await Po(a,p);try{jo()}catch{}}catch($){throw $.fallback&&await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{h=await Co(p),Nt(o,h,{workflowUuid:f,version:u,runtimeTag:n,cacheDir:p})}catch($){throw Ot(o,$),await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new O("import-failed",$.message)}}let g=Date.now(),I=i.env&&typeof i.env=="object"&&!Array.isArray(i.env)?i.env:null,_=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,m={...e.input||{},..._?{nodeConfigs:c}:{}},w,S;try{w=await xo(I,async()=>{let $=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph();return At({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,m,{signal:e.signal}))}),S=w&&typeof w=="object"&&"state"in w?w.state:w}catch(p){throw await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-g}}),p}if(w&&typeof w=="object"&&w.stoppedExternally){await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",finalState:S,durationMs:Date.now()-g}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=s,p}return await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"completed",finalState:S,durationMs:Date.now()-g}}),{finalState:S,executionId:s}}function Ro(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),i;try{i=Bt(r)}catch{continue}if(i.isDirectory()){let s;try{s=Mt(r)}catch{continue}for(let n of s)t.push(U(r,n))}else e+=i.size}return e}function jo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(ye))return{evicted:0,freedBytes:0};let e=Mt(ye),t=[],r=0;for(let a of e){let l=U(ye,a),u;try{u=Bt(l)}catch{continue}let f=u.isDirectory()?Ro(l):u.size;r+=f,t.push({name:a,full:l,size:f,mtimeMs:u.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let i=Math.floor(o*.7),s=0,n=0;for(let a of t){if(r-s<=i)break;if(!Y(U(a.full,".lock")))try{$o(a.full,{recursive:!0,force:!0}),s+=a.size,n+=1}catch(l){E.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return n>0&&E.info(`[sub-graph cache] evicted ${n} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:n,freedBytes:s,totalBytes:r-s}}catch(e){return E.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Bo=2e3,Mo=600*1e3,Do=new Set(["completed","failed","canceled","timeout"]);function Lo(){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 Fo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Uo(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Wo(){return process.env.EXECUTION_ID||null}function Lt(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 Ue(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=le(),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{E.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:S}=await Dt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=Lt(S,e.output);return E.info(`[sub-graph] '${o}' completed in-process`),p}catch(S){if(S instanceof O||S?.fallback)E.info(`[sub-graph] in-process fallback for '${o}': ${S.reason||"unknown"} \u2014 using HTTP`);else throw S}let i=Lo(),s=Fo(),n=Uo(),a=Wo(),l=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(o)}/trigger`,u={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};E.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let f=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(u)});if(!f.ok){let S=null,p="";try{S=await f.json(),p=S?.error||S?.message||JSON.stringify(S)}catch{p=await f.text().catch(()=>"")}if(f.status===429){let k=S?.quotaInfo||{},M=new Error(`Sub-graph '${o}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=o,M.quotaInfo=k,M}if(f.status===400){let k=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=o,k.validationErrors=S?.validationErrors||null,k.missing=S?.missing||null,k}let $=new Error(`Sub-graph '${o}' trigger rejected (${f.status}): ${p}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=f.status,$.subgraph=o,$}let d=await f.json(),c=d?.data?.jobId||d?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(d).slice(0,200)}`);if(e.async)return E.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let y=Number.isFinite(e.timeoutMs)?e.timeoutMs:Mo,h=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Bo,g=`${i}/executions/${encodeURIComponent(c)}`,I=Date.now()+y,_="accepted",m=0;for(;Date.now()<I;){await new Promise(k=>setTimeout(k,h)),m+=1;let S=await fetch(g,{headers:{Authorization:`Bearer ${n}`}});if(!S.ok){if(S.status>=500){E.warn(`[sub-graph] status poll for ${c} returned ${S.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${S.status}`)}let p=await S.json(),$=p?.data||p?.execution||p;if(_=$?.status||_,Do.has(_)){if(_!=="completed"){let b=new Error(`Sub-graph '${o}' (${c}) ended in status '${_}'`);throw b.subgraphJobId=c,b.subgraphStatus=_,b}let k=$?.finalState||$?.state||{},M=Lt(k,e.output);return E.info(`[sub-graph] '${o}' (${c}) completed after ${m} polls`),M}}let w=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(y/1e3)}s (last status: ${_})`);throw w.subgraphJobId=c,w.subgraphStatus=_,w}import{existsSync as Ft,readFileSync as Go}from"node:fs";import{join as We,dirname as Ut}from"node:path";var de=class{static async loadContext(e,t,r={}){let i={},s=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Ut(We(t,e));for(let l of s){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let f=l.replace(/\.[^.]+$/,"").toLowerCase();i[f]=u}}}let n=r.discovery||{};for(let[a,l]of Object.entries(n))try{let u=We(t,l);Ft(u)&&(i[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return i}static async findAndMergeContextFiles(e,t,r){let i=[],s=t;for(;s.startsWith(r);){let n=We(s,e);if(Ft(n))try{i.unshift(await this.loadFile(n))}catch(l){console.warn(`[workflow] could not load ${e} from ${n}: ${l.message}`)}let a=Ut(s);if(a===s)break;s=a}return i.length===0?null:i.every(n=>typeof n=="string")?i.join(`
|
|
35
35
|
|
package/dist/node-registry.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
var G=Object.defineProperty;var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var K=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})};var $=w(()=>{});var _,U,y,b,I=w(()=>{_=()=>{},U={debug:_,info:_,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},y={impl:U},b={debug:(...e)=>y.impl.debug?.(...e),info:(...e)=>y.impl.info?.(...e),warn:(...e)=>y.impl.warn?.(...e),error:(...e)=>y.impl.error?.(...e)}});function O(e){return V.get(e)||null}var S,E,V,X,R=w(()=>{S=Symbol.for("@zibby/agent-workflow.skills"),E=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[S]||(globalThis[S]=new Map);globalThis[E]||(globalThis[E]=new Map);V=globalThis[S],X=globalThis[E]});var
|
|
1
|
+
var G=Object.defineProperty;var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var K=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})};var $=w(()=>{});var _,U,y,b,I=w(()=>{_=()=>{},U={debug:_,info:_,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},y={impl:U},b={debug:(...e)=>y.impl.debug?.(...e),info:(...e)=>y.impl.info?.(...e),warn:(...e)=>y.impl.warn?.(...e),error:(...e)=>y.impl.error?.(...e)}});function O(e){return V.get(e)||null}var S,E,V,X,R=w(()=>{S=Symbol.for("@zibby/agent-workflow.skills"),E=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[S]||(globalThis[S]=new Map);globalThis[E]||(globalThis[E]=new Map);V=globalThis[S],X=globalThis[E]});var C={};K(C,{getAgentStrategy:()=>j,invokeAgent:()=>q,listStrategies:()=>H,registerStrategy:()=>D,resolveInvocationModel:()=>M});function D(e){if(!e||typeof e.getName!="function"||typeof e.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=f.findIndex(n=>n.getName()===e.getName());t>=0?f[t]=e:f.push(e)}function H(){return f.map(e=>e.getName())}function M({config:e={},options:t={},strategyName:n,envModel:r}={}){let l=e.models||{},o=t.nodeName&&l[t.nodeName]||null,i=l.default||null,c=e.agent?.[n]?.model||null,g=(typeof r=="string"?r.trim():"")||null;return o||i||c||t.model||g||null}function j(e={}){let{state:t={},preferredAgent:n=null}=e,r=n||t.agentType||process.env.AGENT_TYPE;if(!r){let o=f.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${o}`)}b.debug(`[workflow] agent selection: requested=${r}`);let l=f.find(o=>o.getName()===r);if(!l){let o=f.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${o}`)}if(!l.canHandle(e))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return b.debug(`[workflow] using agent: ${l.getName()}`),l}async function q(e,t={},n={}){let r=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},l={...t,state:r},o=j(l),i=r.config||n.config||{},c=M({config:i,options:n,strategyName:o.name,envModel:process.env.MODEL}),g={...n,model:c,workspace:r.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],extraMcpServers:n.extraMcpServers||r.extraMcpServers||t.extraMcpServers||[],plugins:n.plugins||t.plugins||[],config:i},a=e,h=g.skills||[];if(h.length>0&&!n.skipPromptFragments){let d=h.map(k=>{let s=O(k)?.promptFragment;return typeof s=="function"?s():s}).filter(Boolean);d.length>0&&(a+=`
|
|
2
2
|
|
|
3
3
|
${d.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let u=
|
|
6
|
-
fields: ${A.join(", ")}`)}return
|
|
5
|
+
`)}`)}let u=r._currentNodeConfig?.stores;if(Array.isArray(u)&&u.length>0&&typeof u[0]=="object"){let d=u.length<=8,k=u.map(s=>{let T=s?.id??s?.storeId??"",L=(s?.name??"").toString().trim()||T,Y=s?.type?` \xB7 ${s.type}`:"",z=(s?.description||"").toString().replace(/\s+/g," ").trim(),N=`- ${L} \xB7 ${z||"(no description)"}${Y} (id: ${T})`;if(d&&s?.schema&&typeof s.schema=="object"){let A=s.schema.properties&&typeof s.schema.properties=="object"?Object.keys(s.schema.properties):Object.keys(s.schema);A.length&&(N+=`
|
|
6
|
+
fields: ${A.join(", ")}`)}return N});a+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
9
|
${k.join(`
|
|
10
|
-
`)}`}let p=
|
|
10
|
+
`)}`}let p=r._currentNodeConfig?.extraPromptInstructions?.trim();return p&&(a+=`
|
|
11
11
|
|
|
12
12
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
13
13
|
PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
16
|
${p}
|
|
17
|
-
`),b.debug(`[workflow] prompt length: ${a.length} chars`),
|
|
18
|
-
${h}`),c.includes(".")||i.add(g)}return
|
|
17
|
+
`),b.debug(`[workflow] prompt length: ${a.length} chars`),o.invoke(a,g)}var v,f,P=w(()=>{$();I();R();v=Symbol.for("@zibby/agent-workflow.strategies");globalThis[v]||(globalThis[v]=[]);f=globalThis[v]});var x=Symbol.for("@zibby/agent-workflow.nodes");globalThis[x]||(globalThis[x]=new Map);var m=globalThis[x];function F(e,t){m.set(e,t)}function oe(e){return m.get(e)}function ie(e){return m.has(e)}function se(){return Array.from(m.keys())}function le(e){let t=m.get(e);return t?t.factory&&typeof t.create=="function"?t.create.toString():typeof t.execute=="function"?t.execute.toString():typeof t=="function"?t.toString():null:null}F("ai_agent",{name:"ai_agent",factory:!0,create:(e,t={})=>({name:e,_isCustomCode:!0,execute:async n=>{let r=n?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(P(),C))).invokeAgent);let l=t.extraPromptInstructions||"Execute the task based on the current state.",o=B(l,n),i=await r(o,{cwd:n.workspace||process.cwd(),model:n.model,tools:t.resolvedTools||null});return{success:!0,output:{raw:i,nodeId:e},raw:typeof i=="string"?i:i.raw}}})});function B(e,t){let n=/@([\w.]+)/g,r=new Set,l;for(;(l=n.exec(e))!==null;)r.add(l[1]);if(r.size===0)return e;let o=[],i=new Set;for(let c of r){let g=c.split(".")[0];if(i.has(g))continue;let a=c.split(".").reduce((p,d)=>p?.[d],t);if(a===void 0)continue;let h=typeof a=="string"?a:a?.raw??JSON.stringify(a,null,2),u=c.replace(/_/g," ").replace(/\b\w/g,p=>p.toUpperCase());o.push(`## ${u}
|
|
18
|
+
${h}`),c.includes(".")||i.add(g)}return o.length===0?e:`${e}
|
|
19
19
|
|
|
20
20
|
---
|
|
21
21
|
# Referenced Context
|
|
22
22
|
|
|
23
|
-
${
|
|
23
|
+
${o.join(`
|
|
24
24
|
|
|
25
|
-
`)}`}export{
|
|
25
|
+
`)}`}export{oe as getNodeImpl,le as getNodeTemplate,ie as hasNode,se as listNodeTypes,F as registerNode};
|
package/dist/node.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var nt=Object.defineProperty;var N=(r,t)=>()=>(r&&(t=r(r=0)),t);var at=(r,t)=>{for(var e in t)nt(r,e,{get:t[e],enumerable:!0})};var D,lt,
|
|
1
|
+
var nt=Object.defineProperty;var N=(r,t)=>()=>(r&&(t=r(r=0)),t);var at=(r,t)=>{for(var e in t)nt(r,e,{get:t[e],enumerable:!0})};var D,lt,v,p,A=N(()=>{D=()=>{},lt={debug:D,info:D,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},v={impl:lt},p={debug:(...r)=>v.impl.debug?.(...r),info:(...r)=>v.impl.info?.(...r),warn:(...r)=>v.impl.warn?.(...r),error:(...r)=>v.impl.error?.(...r)}});var z=N(()=>{});function V(r){return pt.get(r)||null}var P,M,pt,kt,q=N(()=>{P=Symbol.for("@zibby/agent-workflow.skills"),M=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[P]||(globalThis[P]=new Map);globalThis[M]||(globalThis[M]=new Map);pt=globalThis[P],kt=globalThis[M]});var tt={};at(tt,{getAgentStrategy:()=>Q,invokeAgent:()=>ht,listStrategies:()=>ft,registerStrategy:()=>dt,resolveInvocationModel:()=>X});function dt(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=y.findIndex(e=>e.getName()===r.getName());t>=0?y[t]=r:y.push(r)}function ft(){return y.map(r=>r.getName())}function X({config:r={},options:t={},strategyName:e,envModel:o}={}){let n=r.models||{},i=t.nodeName&&n[t.nodeName]||null,a=n.default||null,w=r.agent?.[e]?.model||null,u=(typeof o=="string"?o.trim():"")||null;return i||a||w||t.model||u||null}function Q(r={}){let{state:t={},preferredAgent:e=null}=r,o=e||t.agentType||process.env.AGENT_TYPE;if(!o){let i=y.map(a=>a.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}p.debug(`[workflow] agent selection: requested=${o}`);let n=y.find(i=>i.getName()===o);if(!n){let i=y.map(a=>a.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${i}`)}if(!n.canHandle(r))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return p.debug(`[workflow] using agent: ${n.getName()}`),n}async function ht(r,t={},e={}){let o=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},n={...t,state:o},i=Q(n),a=o.config||e.config||{},w=X({config:a,options:e,strategyName:i.name,envModel:process.env.MODEL}),u={...e,model:w,workspace:o.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],extraMcpServers:e.extraMcpServers||o.extraMcpServers||t.extraMcpServers||[],plugins:e.plugins||t.plugins||[],config:a},h=r,b=u.skills||[];if(b.length>0&&!e.skipPromptFragments){let g=b.map(E=>{let l=V(E)?.promptFragment;return typeof l=="function"?l():l}).filter(Boolean);g.length>0&&(h+=`
|
|
2
2
|
|
|
3
3
|
${g.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
5
|
+
`)}`)}let s=o._currentNodeConfig?.stores;if(Array.isArray(s)&&s.length>0&&typeof s[0]=="object"){let g=s.length<=8,E=s.map(l=>{let I=l?.id??l?.storeId??"",O=(l?.name??"").toString().trim()||I,S=l?.type?` \xB7 ${l.type}`:"",f=(l?.description||"").toString().replace(/\s+/g," ").trim(),_=`- ${O} \xB7 ${f||"(no description)"}${S} (id: ${I})`;if(g&&l?.schema&&typeof l.schema=="object"){let c=l.schema.properties&&typeof l.schema.properties=="object"?Object.keys(l.schema.properties):Object.keys(l.schema);c.length&&(_+=`
|
|
6
6
|
fields: ${c.join(", ")}`)}return _});h+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
@@ -14,10 +14,10 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
|
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
16
|
${m}
|
|
17
|
-
`),p.debug(`[workflow] prompt length: ${h.length} chars`),
|
|
17
|
+
`),p.debug(`[workflow] prompt length: ${h.length} chars`),i.invoke(h,u)}var C,y,et=N(()=>{z();A();q();C=Symbol.for("@zibby/agent-workflow.strategies");globalThis[C]||(globalThis[C]=[]);y=globalThis[C]});import $ from"handlebars";var T=class{constructor(t){this.schema=t}parse(t){let e=t.match(/```json\s*([\s\S]*?)\s*```/);if(e)return this.validate(JSON.parse(e[1]));let o=[t.match(/\{[\s\S]*?\}/),t.match(/\{[\s\S]*\}/)].filter(Boolean).map(n=>n[0]);for(let n of o)try{return this.validate(JSON.parse(n))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:t.trim()})}validate(t){let e=[];for(let[o,n]of Object.entries(this.schema)){if(n.required&&!(o in t)&&e.push(`Missing required field: ${o}`),o in t&&n.type){let i=typeof t[o];i!==n.type&&e.push(`Field '${o}' expected ${n.type}, got ${i}`)}if(n.validate&&o in t){let i=n.validate(t[o]);i&&e.push(`Field '${o}': ${i}`)}}if(e.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${e.join(`
|
|
19
|
-
`)}`);return t}};
|
|
20
|
-
`?(a+=u,t.lineStart=!0,t.col=0,t.inEsc=!1):u==="\x1B"?(t.inEsc=!0,a+=u):t.inEsc?(a+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(t.inEsc=!1)):(t.col++,a+=u,t.col>=
|
|
19
|
+
`)}`);return t}};A();import{writeFileSync as F,readFileSync as rt,existsSync as ot,mkdirSync as mt}from"node:fs";import{join as j,dirname as gt}from"node:path";import d from"chalk";var ct="__WORKFLOW_GRAPH_LOG__",k=d.gray("\u2502"),ut=d.gray("\u250C"),G=d.gray("\u2514"),W=d.green("\u25C6"),H=d.hex("#c084fc")("\u25C6"),J=d.hex("#2dd4bf")("\u25C6"),x=d.red("\u25C6"),U=`${k} `,B=2;function K(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function Y(r,t){return(e,o,n)=>{if(typeof e!="string")return r(e,o,n);let i=process.stdout.columns||120,a="";for(let w=0;w<e.length;w++){let u=e[w];t.lineStart&&(a+=U,t.col=B,t.lineStart=!1),u===`
|
|
20
|
+
`?(a+=u,t.lineStart=!0,t.col=0,t.inEsc=!1):u==="\x1B"?(t.inEsc=!0,a+=u):t.inEsc?(a+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(t.inEsc=!1)):(t.col++,a+=u,t.col>=i&&(a+=`
|
|
21
21
|
${U}`,t.col=B))}return r(a,o,n)}}var R=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 t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=Y(this._origStdoutWrite,t),process.stderr.write=Y(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
22
22
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
23
23
|
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
|
|
@@ -25,10 +25,10 @@ ${U}`,t.col=B))}return r(a,o,n)}}var R=class{constructor(){this._currentNode=nul
|
|
|
25
25
|
`;this._origStdoutWrite?this._origStdoutWrite(e):process.stdout.write(e)}_writeDot(t,e){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
26
26
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${t} ${e}
|
|
27
27
|
`)):process.stdout.write.bind(process.stdout)(`${t} ${e}
|
|
28
|
-
`)}step(t){this._origStdoutWrite?this._writeDot(
|
|
28
|
+
`)}step(t){this._origStdoutWrite?this._writeDot(W,t):process.stdout.write.bind(process.stdout)(`${k} ${W} ${t}
|
|
29
29
|
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(H,t):process.stdout.write.bind(process.stdout)(`${k} ${H} ${t}
|
|
30
30
|
`)}stepMemory(t){let e=d.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(J,e):process.stdout.write.bind(process.stdout)(`${k} ${J} ${e}
|
|
31
31
|
`)}stepFail(t){this._origStdoutWrite?this._writeDot(x,d.red(t)):process.stdout.write.bind(process.stdout)(`${k} ${x} ${d.red(t)}
|
|
32
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${ut} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:n}=e;if(n)for(let a of n)this._rawWrite(`${
|
|
32
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${ut} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:n}=e;if(n)for(let a of n)this._rawWrite(`${W} ${a}`);let i=o?d.dim(` ${K(o)}`):"";this._rawWrite(`${G} ${d.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:n}=o,i=n?d.dim(` ${K(n)}`):"";this._rawWrite(`${x} ${d.red(e)}`),this._rawWrite(`${G} ${d.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(d.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},Z=new R;var L=".session-info.json";var Et=Object.freeze(["codebase-memory","code-scan","artifact"]);$.helpers.inc||$.registerHelper("inc",r=>Number(r)+1);$.helpers.json||$.registerHelper("json",r=>JSON.stringify(r,null,2));$.helpers.eq||$.registerHelper("eq",(r,t)=>r===t);var st=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode&&!t._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=t.outputSchema&&!this.isZodSchema?new T(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){if(this.config._isRouter)return p.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let o=()=>e&&typeof e.getAll=="function"?e.getAll():t,n=s=>e&&typeof e.get=="function"?e.get(s):t?.[s];if(typeof this.customExecute=="function"){p.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let s=await this.customExecute(t);return typeof s=="object"&&s!==null&&s.success===!1?{success:!1,error:s.error||"Node execution failed",raw:s.raw||null}:this.isZodSchema?(p.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(s),raw:null}):{success:!0,output:s,raw:null}}catch(s){return p.error(`[workflow] node '${this.name}' failed: ${s.message}`),s.name==="ZodError"&&p.error(`Schema errors: ${JSON.stringify(s.issues||s.errors,null,2)}`),{success:!1,error:s.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=$.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(o())):i=this.prompt;let a=n("_skillHints");a&&(i=`${a}
|
|
33
33
|
|
|
34
|
-
${
|
|
34
|
+
${i}`);let w=o(),u=w.cwd||process.cwd(),h=w.sessionPath;try{if(h){let s=j(h,L);if(ot(s)){let g=JSON.parse(rt(s,"utf-8"));g.currentNode=this.name,F(s,JSON.stringify(g,null,2),"utf-8")}let m=j(h,"..",L);if(ot(m))try{let g=JSON.parse(rt(m,"utf-8"));g.currentNode=this.name,F(m,JSON.stringify(g,null,2),"utf-8")}catch{}}}catch(s){p.debug(`[workflow] could not update session info: ${s.message}`)}let b=null;for(let s=0;s<=this.retries;s++)try{p.debug(`[workflow] node '${this.name}' attempt ${s}`);let m=o().config||{},g=m.agents||{},E=this.config.agent??g[this.name]??null,l={state:o()};E&&(l.preferredAgent=E);let I={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:h,config:m,nodeName:this.name,timeout:this.config?.timeout||3e5},O=t?._coreInvokeAgent;O||(O=(await Promise.resolve().then(()=>(et(),tt))).invokeAgent);let S=await O(i,l,I),f,_;if(typeof S=="string"?(f=S,_=null):S.structured?(f=S.raw||JSON.stringify(S.structured,null,2),_=S.structured):(f=S.raw||JSON.stringify(S,null,2),_=S.extracted||null),h)try{let c=j(h,this.name,"raw_stream_output.txt");mt(gt(c),{recursive:!0}),F(c,typeof f=="string"?f:JSON.stringify(f),"utf-8")}catch(c){p.debug(`[workflow] could not save raw output: ${c.message}`)}if(this.isZodSchema&&_){p.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(_,null,2)}`);let c=_;if(typeof this.onComplete=="function")try{c=await this.onComplete(o(),_)}catch(it){p.warn(`[workflow] onComplete hook failed: ${it.message}`)}return{success:!0,output:c,raw:f}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:f}),raw:f}}catch(c){throw new Error(`onComplete failed: ${c.message}`,{cause:c})}if(this.parser){let c=this.parser.parse(f);return p.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(c,null,2)}`),Z.step("Output parsed"),{success:!0,output:c,raw:f}}return{success:!0,output:f,raw:f}}catch(m){b=m,s<this.retries&&p.info(`[workflow] node '${this.name}' failed, retrying (${s+1}/${this.retries})\u2026`)}return{success:!1,error:b.message,raw:null}}};export{st as Node};
|
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
var
|
|
1
|
+
var T=()=>{},O={debug:T,info:T,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},m={impl:O};var d={debug:(...e)=>m.impl.debug?.(...e),info:(...e)=>m.impl.info?.(...e),warn:(...e)=>m.impl.warn?.(...e),error:(...e)=>m.impl.error?.(...e)};var w=Symbol.for("@zibby/agent-workflow.skills"),b=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[w]||(globalThis[w]=new Map);globalThis[b]||(globalThis[b]=new Map);var _=globalThis[w],P=globalThis[b];function A(e){return _.get(e)||null}var y=Symbol.for("@zibby/agent-workflow.strategies");globalThis[y]||(globalThis[y]=[]);var a=globalThis[y];function D(e){if(!e||typeof e.getName!="function"||typeof e.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=a.findIndex(n=>n.getName()===e.getName());t>=0?a[t]=e:a.push(e)}function H(){return a.map(e=>e.getName())}function M({config:e={},options:t={},strategyName:n,envModel:o}={}){let s=e.models||{},i=t.nodeName&&s[t.nodeName]||null,l=s.default||null,u=e.agent?.[n]?.model||null,p=(typeof o=="string"?o.trim():"")||null;return i||l||u||t.model||p||null}function R(e={}){let{state:t={},preferredAgent:n=null}=e,o=n||t.agentType||process.env.AGENT_TYPE;if(!o){let i=a.map(l=>l.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}d.debug(`[workflow] agent selection: requested=${o}`);let s=a.find(i=>i.getName()===o);if(!s){let i=a.map(l=>l.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${i}`)}if(!s.canHandle(e))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return d.debug(`[workflow] using agent: ${s.getName()}`),s}async function K(e,t={},n={}){let o=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},s={...t,state:o},i=R(s),l=o.config||n.config||{},u=M({config:l,options:n,strategyName:i.name,envModel:process.env.MODEL}),p={...n,model:u,workspace:o.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],extraMcpServers:n.extraMcpServers||o.extraMcpServers||t.extraMcpServers||[],plugins:n.plugins||t.plugins||[],config:l},c=e,k=p.skills||[];if(k.length>0&&!n.skipPromptFragments){let f=k.map(h=>{let r=A(h)?.promptFragment;return typeof r=="function"?r():r}).filter(Boolean);f.length>0&&(c+=`
|
|
2
2
|
|
|
3
3
|
${f.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let g=o._currentNodeConfig?.stores;if(Array.isArray(g)&&g.length>0&&typeof g[0]=="object"){let f=g.length<=8,h=g.map(
|
|
6
|
-
fields: ${
|
|
5
|
+
`)}`)}let g=o._currentNodeConfig?.stores;if(Array.isArray(g)&&g.length>0&&typeof g[0]=="object"){let f=g.length<=8,h=g.map(r=>{let E=r?.id??r?.storeId??"",$=(r?.name??"").toString().trim()||E,x=r?.type?` \xB7 ${r.type}`:"",I=(r?.description||"").toString().replace(/\s+/g," ").trim(),v=`- ${$} \xB7 ${I||"(no description)"}${x} (id: ${E})`;if(f&&r?.schema&&typeof r.schema=="object"){let N=r.schema.properties&&typeof r.schema.properties=="object"?Object.keys(r.schema.properties):Object.keys(r.schema);N.length&&(v+=`
|
|
6
|
+
fields: ${N.join(", ")}`)}return v});c+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
9
|
${h.join(`
|
|
10
|
-
`)}`}let
|
|
10
|
+
`)}`}let S=o._currentNodeConfig?.extraPromptInstructions?.trim();return S&&(c+=`
|
|
11
11
|
|
|
12
12
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
13
13
|
PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
|
-
${
|
|
17
|
-
`),d.debug(`[workflow] prompt length: ${c.length} chars`),i.invoke(c,p)}export{
|
|
16
|
+
${S}
|
|
17
|
+
`),d.debug(`[workflow] prompt length: ${c.length} chars`),i.invoke(c,p)}export{R as getAgentStrategy,K as invokeAgent,H as listStrategies,D as registerStrategy,M as resolveInvocationModel};
|