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